diff --git a/.gitignore b/.gitignore index aac762d0a..ab765179f 100755 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ epub/temp *~ .#* figures/* +*/*.session diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..9071e3867 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,9 @@ +language: ruby +rvm: + - 1.9.3 +script: rake ci:parallel_check +notifications: + email: + recipients: + - jn.avila@free.fr + diff --git a/Gemfile b/Gemfile new file mode 100644 index 000000000..59fd845ae --- /dev/null +++ b/Gemfile @@ -0,0 +1,5 @@ +source 'https://rubygems.org' + +gem 'maruku', '0.7.1' +gem 'redcarpet' +gem 'parallel' diff --git a/README b/README deleted file mode 100644 index 665c4c0d7..000000000 --- a/README +++ /dev/null @@ -1,30 +0,0 @@ -Pro Git Book Contents -===================== - -This is the source code for the Pro Git book contents. It is licensed under the -Creative Commons Attribution-Non Commercial-Share Alike 3.0 license. I hope you -enjoy it, I hope it helps you learn Git, and I hope you'll support Apress and me -by purchasing a print copy of the book at Amazon: - -http://tinyurl.com/amazonprogit - -Making Ebooks -===================== - -On Fedora you can run something like this: - - $ yum install ruby calibre rubygems ruby-devel rubygem-ruby-debug - $ gem install rdiscount - $ makeebooks en # will produce a mobi - -Errata -===================== -If you see anything that is technically wrong or otherwise in need of correction, -please email me at schacon at gmail dot com to inform me. - - -Translation -===================== -If you wish to translate the book, I will put the translation up on the progit.org -site. Please put your translation into the appropriate subdirectory of this -project (ie: 'it' for Italian and so forth) and send me (schacon) a pull request. diff --git a/README.md b/README.md new file mode 100644 index 000000000..39d3f6dfa --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# Pro Git, 1st Edition + +This is the source for the 1st edition of the Pro Git book. The second edition has since been released and is what will be maintained and published going forward. Please suggest any changes to that version instead. + +You can find the new edition at: + +https://github.com/progit/progit2 + +If you're looking for the original README content, it can be found in the [README.original.md](README.original.md) file. diff --git a/README.original.md b/README.original.md new file mode 100644 index 000000000..b6556fd75 --- /dev/null +++ b/README.original.md @@ -0,0 +1,70 @@ +[![Build Status](https://secure.travis-ci.org/progit/progit.png?branch=master)](https://travis-ci.org/progit/progit) + +# Pro Git Book Contents + +This is the source code for the Pro Git book contents. It is licensed under +the Creative Commons Attribution-Non Commercial-Share Alike 3.0 license. I +hope you enjoy it, I hope it helps you learn Git, and I hope you'll support +Apress and me by purchasing a print copy of the book at Amazon: + +http://tinyurl.com/amazonprogit + +It is also available online at: + +http://git-scm.com/book/ + +and fully translated in 10 languages. + +# Making Ebooks + +On Fedora (16 and later) you can run something like this:: + + $ yum install ruby calibre rubygems ruby-devel rubygem-ruby-debug rubygem-rdiscount + $ makeebooks en # will produce a mobi + +On MacOS you can do like this: + +1. INSTALL ruby and rubygems +2. `$ gem install rdiscount` +3. DOWNLOAD Calibre for MacOS and install command line tools. You'll need some dependencies to generate a PDF: + * pandoc: http://johnmacfarlane.net/pandoc/installing.html + * xelatex: http://tug.org/mactex/ +4. `$ makeebooks zh` #will produce a mobi + +On Windows you can do like this: + +1. Install ruby and related tool from http://rubyinstaller.org/downloads/ + * RubyInstaller (ruby & gem) + * Development Kit (to build rdiscount gem) +2. Open `cmd` and `$ gem install rdiscount` +3. Install Calibre for Windows from http://calibre-ebook.com/download +4. `$ SET ebook_convert_path=c:\Program Files\Calibre2\ebook-convert.exe`. Modify to suit with your Calibre installed path. +5. Make ebooks: + * `$ ruby makeebooks vi` #will produce a mobi + * `$ SET FORMAT=epub` then `$ ruby makeebooks vi` #will produce an epub + +## Notes on pandoc + +Please use Pandoc version 1.11.1 or later as older versions (confirmed on 1.9.1.1) has a [bug](https://github.com/jgm/pandoc/issues/964) which hides a word after tilde `~`. You can do `pandoc -v` to see which version you have installed. + +# Errata + +If you see anything that is technically wrong or otherwise in need of +correction, please [open an issue](https://github.com/progit/progit/issues/new) and one of the maintainers will take a look. + + +# Translation + +If you wish to translate the book, your work will be put up on the +git-scm.com site. Please put your translation into the appropriate +subdirectory of this project, using the +[ISO 639](http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) code +and send a pull request. + +# Sending a pull request + +* Be careful to use UTF-8 encoding in your files. +* Do not mix changes to the original English with translations in a single pull request. +* If your pull request changes a translation, prefix your pull request and commits' messages with the ISO 639 code, e.g. `[de] Update chapter 2`. Please only push files where there is already some translation done. +* Make sure the translation changes can be automatically merged. The maintainers can not make the merge manually if there are some conflicts. +* Make as sure as possible that the changes work correctly for publishing to PDF, ebooks and the git-scm.com website. diff --git a/Rakefile b/Rakefile index 0cb5557cc..3aeaebf78 100644 --- a/Rakefile +++ b/Rakefile @@ -1,5 +1,7 @@ -require 'rake/clean' +# encoding: UTF-8 +require 'rake/clean' +require 'redcarpet' $lang = ENV['language'] $lang ||= 'en' @@ -9,7 +11,7 @@ namespace :epub do INDEX_FILEPATH = File.join(TMP_DIR, 'progit.html') TARGET_FILEPATH = "progit-#{$lang}.epub" - SOURCE_FILES = FileList.new(File.join($lang, '**', '*.markdown')).sort + SOURCE_FILES = FileList.new(File.join($lang, '0*', '*.markdown')).sort CONVERTED_MK_FILES = SOURCE_FILES.pathmap(File.join(TMP_DIR, '%f')) HTML_FILES = CONVERTED_MK_FILES.ext('html') @@ -59,7 +61,7 @@ namespace :epub do mk_file = File.open(mk_filename, 'r') do |mk| html_file = File.open(html_filename, 'w') do |html| - code = Maruku.new(mk.read).to_html + code = Maruku.new(mk.read.encode("UTF-8")).to_html code.gsub!(/^( 7, + "02-git-basics" => 2, + "03-git-branching" => 39, + "04-git-server" => 15, + "05-distributed-git" => 27, + "06-git-tools" => 1, + "07-customizing-git" => 3, + "08-git-and-other-scms" => 0, + "09-git-internals" => 4} + source_files = FileList.new(File.join(lang, '0*', '*.markdown')).sort + source_files.each do |mk_filename| + src_file = File.open(mk_filename, 'r') + figure_count = 0 + until src_file.eof? + line = src_file.readline + matches = line.match /^#/ + if matches + if line.match /^(#+).*#[[:blank:]]+$/ + out<< "\nBadly formatted title in #{mk_filename}: #{line}\n" + error_code = true + end + end + if line.match /^\s*Insert\s(.*)/i + if line.match /^\s*Insert\s(.*)/ + figure_count = figure_count + 1 + else + out << "\n#{lang}: Badly cased Insert directive: #{line}\n" + error_code = true + end + end + end + # This extraction is a bit contorted, because the pl translation renamed + # the files, so the match is done on the directories. + tab_fig_count = chapter_figure[File.basename(File.dirname(mk_filename))] + expected_figure_count = tab_fig_count ? tab_fig_count:0 + if figure_count > expected_figure_count + out << "\nToo many figures declared in #{mk_filename}\n" + error_code = true + end + end + begin + mark = (source_files.map{|mk_filename| File.open(mk_filename, 'r'){ + |mk| mk.read.encode("UTF-8")}}).join("\n\n") + require 'maruku' + code = Maruku.new(mark, :on_error => :raise, :error_stream => StderrDecorator.new(out)) + rescue + print $! + error_code = true + end + error_code +end + +$out = $stdout + +namespace :ci do + desc "Parallel Continuous integration" + task :parallel_check do + require 'parallel' + langs = FileList.new('??')+FileList.new('??-??') + results = Parallel.map(langs) do |lang| + error_code = test_lang(lang, $out) + if error_code + print "processing #{lang} KO\n" + else + print "processing #{lang} OK\n" + end + error_code + end + fail "At least one language conversion failed" if results.any? + end + + (FileList.new('??')+FileList.new('??-??')).each do |lang| + desc "testing " + lang + task (lang+"_check").to_sym do + error_code = test_lang(lang, $out) + fail "processing #{lang} KO\n" if error_code + print "processing #{lang} OK\n" + end + end + + desc "Continuous Integration" + task :check do + require 'maruku' + langs = FileList.new('??')+FileList.new('??-??') + if ENV['debug'] && $lang + langs = [$lang] + else + excluded_langs = [ + ] + excluded_langs.each do |lang| + puts "excluding #{lang}: known to fail" + end + langs -= excluded_langs + end + errors = langs.map do |lang| + print "processing #{lang} " + error_code=test_lang(lang, $out) + if error_code + print "KO\n" + else + print "OK\n" + end + error_code + end + fail "At least one language conversion failed" if errors.any? + end + +end diff --git a/ar/01-introduction/01-chapter1.markdown b/ar/01-introduction/01-chapter1.markdown index d920d76d0..6ec46b534 100644 --- a/ar/01-introduction/01-chapter1.markdown +++ b/ar/01-introduction/01-chapter1.markdown @@ -8,7 +8,7 @@ إذا كنت تعمل كمصمم غرافيك أو ويب وتريد طريقة لمتابعة جميع الإصدارت والتعديلات التي تجريها على صورة أو قالب ما (الأمر الذي سيعجبك بالتأكيد)، فإن نظام إدارة الإصدارات (VCS) هو الحل الأمثل. حيث يمكنك من إرجاع الملفات الى حالة كانت عليها سابقاً، أو ارجاع المشروع بأكمله لحالة سابقة، يمكنك أيضاً مقارنة التغيرات الحاصلة مع مرور الزمن، أو معرفة من قام بتعديل معين أدى الى خطأ ما، من قام بتقديم إقتراح ومتى قام بذلك، والمزيد. إستخدامك لنظام إدارة الإصدارات يعني أيضاً أنه اذا قمت بخطأ ما في مرحلة من المراحل أو خسرت ملفات المشروع لسبب ما، يمكنك استرجاعها الى حالها بسهولة. كل هذه الميزات مقابل تعب خفيف منك. -### نظم إدارة الإصدارات المحلية ### +### أنظمة إدارة الإصدارات المحلية ### تقوم الطريقة التي يقوم بها معظم المستخدمين لإدارة إصداراة مشاريعهم على "نسخ الملفات" الى مكان آخر. يقوم المعظم بهذه الطريقة لأنها تبدوا وكأنها الحل الأسهل، ولكنها تجلب المشاكل والأخطاء بشكل لا يحتمل أيضاً. من السهل جداً أن تنسى بأي مجلد وضعت نسخة معينة أو أن تقوم بالتغيير أو الحذف عن طريق الخطا لملف ما. @@ -27,7 +27,7 @@ Insert 18333fig0101.png Insert 18333fig0102.png الشكل 1-2. مخطط أنظمة إدارة الإصدارات المركزية. -تقدم هذه الطرقة العديد من الأفضليات على أنظمة ادارة الإصدارات المحلية. فعلى سبيل المثال، جميع المشاركين في المشروع يعرف مالذي يقوم به المشارك الآخر الى حد معين. مدراء المشروع يستطيعون التحكم بمن يستطيع فعل ماذا في النظام العام; وبالطبع فإنه من الأسهل التعامل مع أنظمة إدارة الإصدارات المركزية على التعامل مع الأنظمة المحلية وقاعدات بياناتها من قبل كل مستخدم. +تقدم هذه الطريقة العديد من الأفضليات على أنظمة ادارة الإصدارات المحلية. فعلى سبيل المثال، جميع المشاركين في المشروع يعرف مالذي يقوم به المشارك الآخر الى حد معين. مدراء المشروع يستطيعون التحكم بمن يستطيع فعل ماذا في النظام العام; وبالطبع فإنه من الأسهل التعامل مع أنظمة إدارة الإصدارات المركزية على التعامل مع الأنظمة المحلية وقاعدات بياناتها من قبل كل مستخدم. ولكن، ومن جهة ثانية، فإن لهذه الطريقة جانباً سيئاً أيضاً. أهم هذه النقاط السيئة هي أنه هذه الأنظمة المركزية تقوم على مركز واحد للكود، أي إنه اذا حصل وتوقف المخدم لساعة، فلن يتمكن أحد من خفظ التغييرات أو القيام بأي تعديل على أي شيء يعمل عليه. إذا حصل وأن تعطل القرص الأساسي والذي يحوي على قاعدة البيانات المركزية، ولم تعمل النسخ الإحتياطية المخبأة، فإنك ستخسر كل شي عن تاريخ عملك في المشروع. تعاني أنظمة إدارة الإصدارات المحلية من هذه المشكلة أيضاً، وهي أنه عندما تكون جميع ملفات المشروع في مكان واحد فإنك على خطر من خساراة كل شيء! @@ -39,19 +39,19 @@ Insert 18333fig0102.png Insert 18333fig0103.png الشكل 1-3. مخطط أنظمة إدارة الإصدارات الموزعة. -وفوق هذا فإن معظم هذه الأنظمة يتعامل بشكل جيد جداً مع أكثر من نسخة خارجية للمشروع، أي يمكنك التعاون مع أكثر من مجموعة مختلفة من الأشخاص في طرقة مختلفة وفي وقت واحد وعلى مشروع واحد. يمكنك هذا من تطوير أكثر من طريقة عمل واحدة مناسبة لك، الأمر الذي لم يكن متاحاً مع أنظمة إدارة الإصدارات المركزية. +وفوق هذا فإن معظم هذه الأنظمة يتعامل بشكل جيد جداً مع أكثر من نسخة خارجية للمشروع، أي يمكنك التعاون مع أكثر من مجموعة مختلفة من الأشخاص في طرق مختلفة وفي وقت واحد وعلى مشروع واحد. يمكنك هذا من تطوير أكثر من طريقة عمل واحدة مناسبة لك، الأمر الذي لم يكن متاحاً مع أنظمة إدارة الإصدارات المركزية. -## لمخة تاريخية عن Git ## +## لمحة تاريخية عن Git ## -كما تبدأ العديد من الأشياء الجميلة في الحياة، بدأت Git كنوع من التدمير المبدع المثير للجدل. الـ Linux Kernel المعروف هو برنامج مفتوح المصدر ذو إطار واسع نوعاً ما. طوال حياة هذا المشروع (من 1991-2002)، كان يتم تناقل التعديلات على شكل ملفات إصلاح و ملفات مؤرشفة (مضغوطة). في 2002، في 2002 بدأ المشروع باستخدام نظام إدارة إصارات موزعة DVCS يدعى BitKeepter. +كما تبدأ العديد من الأشياء الجميلة في الحياة، بدأت Git كنوع من التدمير المبدع المثير للجدل. الـ Linux Kernel المعروف هو برنامج مفتوح المصدر ذو إطار واسع نوعاً ما. طوال حياة هذا المشروع (من 1991-2002)، كان يتم تناقل التعديلات على شكل ملفات إصلاح و ملفات مؤرشفة (مضغوطة). في 2002، في 2002 بدأ المشروع باستخدام نظام إدارة إصارات موزعة DVCS يدعى BitKeeper. -في 2005، بدأت العلاقة بالإنهيار بين المجتمع المطور للـ Linux Kernel والمجتمع التجاري المطور لـ BitKeeper، وتم العدول عن توفير البنامج بشكل مجاني. أثار هذا التغيير الرغبة في المجتمع المطور لـ Linux (وبالتحديد لينوس تورفالدوس، منشيء Linux) الى تطوير نظامهم الخاص بناء على الدروس التي تعلموها عند استخدامهم لـ BitKee[per. وتم وضع أهداف لكي يحققها النظام الجديد مشمولة بـ: +في 2005، بدأت العلاقة بالإنهيار بين المجتمع المطور للـ Linux Kernel والمجتمع التجاري المطور لـ BitKeeper، وتم العدول عن توفير البرنامج بشكل مجاني. أثار هذا التغيير الرغبة في المجتمع المطور لـ Linux (وبالتحديد لينوس تورفالدوس، منشيء Linux) الى تطوير نظامهم الخاص بناء على الدروس التي تعلموها عند استخدامهم لـ BitKeeper. وتم وضع أهداف لكي يحققها النظام الجديد مشمولة بـ: * السرعة * التصميم البسيط * الدعم القوي للبرمجة الغير خطية (الكثير من أشجار التطوير الفرعي) * التوزيع بشكل كامل -* القدرة على تحمل مشروعات ضمة مثل الـ Linux Kernel بشكل فعال (السرعة وحجم المعلومات) +* القدرة على تحمل مشروعات ضخمة مثل الـ Linux Kernel بشكل فعال (السرعة وحجم المعلومات) منذ ولادة Git في 2005، تطورت لكي تصبح ناضجة مع المحافظة على السهولة والمبادئ الأساسية التي وضعت عليها. حيث أنها سريعة بشكل لايصدق، و فعالة مع المشاريع الكبيرة، وتحوي على نظام تشجير ممتاز لدعم التطوير الغير خطي (انظر الفصل 3). @@ -64,7 +64,7 @@ Insert 18333fig0103.png الفرق الرئيسي بين Git وأي نظام إدارة إصدارات آخر (Subversion وأصدقاءه) هو الطريقة التي تتعامل بها Git مع المعلومات. تقوم معظم هذه الأنظمة بتخزين المعلومات كقائمة من التغيرات القائمة على الملفات. هذه الأنظمة (مثل CVS، Subversion، Perforce، Bazaar وغيرها) تتعامل مع المعلومات التي تحفظها كمجموعة ملفات والتغيرات القائمة عليها مع مرور الوقت، كما هو موضح في الشكل 1-4. Insert 18333fig0104.png -الشكل 1-4. الأنظمة الاخرى تقوم بحفظ معلومات التغيرات الحاصلة على كل ملف وكنها الإصدار الأول. +الشكل 1-4. الأنظمة الاخرى تقوم بحفظ معلومات التغيرات الحاصلة على كل ملف وكأنها الإصدار الأول. الأمر مختلف مع Git. حيث تعامل Git المعلومات المخزنة على أنها "لقطات" من نظام ملفات مصغر. ففي كل مرة تقوم بـ Commit أو تحفظ حالة المشروع، تقوم Git بأخذ صورة عن جميع الملفات في تلك اللحظة وتخزن رابطاً الى تلك اللقطة. ومن أجل السرعة، إذا لم يتغير الملف، لا تقوم Git بحفظة، بل تحفظ رابطاً عن الملف الأسبق منه المطابق. تتعامل Git مع المعلومات كما هو موضح في الشكل 1-5. @@ -77,7 +77,7 @@ Insert 18333fig0105.png أغلب العمليات في Git لا تحتاج سوى ملفات ومصادر داخلية لتعمل - أي بشكل عام، لا توجد معلومات تحتاجها من حاسوب آخر من الشبكة. إذا كنت قد استخدمت أحد أنظمة إداراة الإصدارات الأخرى والتي تعتمد عملياتها بشكل كبير على الشبكة فإن هذا سيجعلك تعتقد أن آلهة السرعة قد باركت Git وأعطتها هذه السرعة الجبارة. ستجد أنك تملك كامل تاريخ مشروعك موجود أمامك مباشرة، وأغلب العمليات أقرب ما تكون الى الآنية. -فعلى سبيل المثال، لكي تستعرض تاريخ مشروعك، لن تحتاج Git الى الذهاب الى مخدم معين للحصول علىه وعرضه، بل تقوم بقراءته مباشرة من حاسوبك. اي انك ستحصل على تاريخ مشروعك بشكل مباشر. اذا أردت استعراض التغيرات الحاصلة بين الإصدار الحالي لملف ما واصدار الشهر السابق، تستطيع Git النظر الى الملف من الشهر السابق وحساب الفروقات بينهما مباشرة، عوضاً عن طلب هذه المعلومات من مخدم خارجي. +فعلى سبيل المثال، لكي تستعرض تاريخ مشروعك، لن تحتاج Git الى الذهاب الى مخدم معين للحصول عليه وعرضه، بل تقوم بقراءته مباشرة من حاسوبك. اي انك ستحصل على تاريخ مشروعك بشكل مباشر. اذا أردت استعراض التغيرات الحاصلة بين الإصدار الحالي لملف ما واصدار الشهر السابق، تستطيع Git النظر الى الملف من الشهر السابق وحساب الفروقات بينهما مباشرة، عوضاً عن طلب هذه المعلومات من مخدم خارجي. هذا يعني أيضاً أن الأمور التي لا تستطيع فعلها عندما تكون مفصولاً عن الإنترنت أو عن الشبكة الداخلية قليلة جداً. إذا كنت في طائرة أو في القطار ولم تستطيع الإرتباط بالشبكة بشكل صحيح، يمكنك إكمال عملك بشكل طبيعي. في الأنظمة الأخرى يكون هذا الأمر مستحيلاً! أو من الممكن لك أن تعدل الملفات ولكن دون عمليات Commit لتغييراتك. في نظام Perforce على سبيل المثال، لا يمكنك فعل الكثير حينما تكون مفصولاً عن المخدم الأساسي; وفي Subversion أو CVS، يمكنك التعديل على الملفات لكن بدون عمليات Commit لتعديلاتك، قد تعتقد بأن هذا ليس بالأمر الكبير، ولكن ستتفاجئ بحجم الفرق الذي يصنعه. @@ -114,9 +114,9 @@ Insert 18333fig0106.png خطوات العمل الإعتيادية في Git غالباً ما تكون كالتالي: -1. تقوم بالتعديلات على الملفات في مجلد العمل. -2. تقوم بوضع هذه الملفات في مكان التهييئ (staging area)، حيث تقوم بإضافة اللقطات الى الـ staging area. -3. تقوم بعملية Commit، يتم أخذ الملفات المهيئة من مكان التهيئة Staging Area وتقوم بتخزين هذه الللقطة بشكل نهائي في مجلد عمل Git. +1. تقوم بالتعديلات على الملفات في مجلد العمل. +2. تقوم بوضع هذه الملفات في مكان التهييئ (staging area)، حيث تقوم بإضافة اللقطات الى الـ staging area. +3. تقوم بعملية Commit، يتم أخذ الملفات المهيئة من مكان التهيئة Staging Area وتقوم بتخزين هذه الللقطة بشكل نهائي في مجلد عمل Git. إذا كان هناك إصدار معين لملف، فسيكون Commited. إذا كان معدل ومضاف إلى مكان التهييئ staging area فهو مهيئ staged. If a particular version of a file is in the git directory, it’s considered committed. If it’s modified but has been added to the staging area, it is staged. And if it was changed since it was checked out but has not been staged, it is modified. In Chapter 2, you’ll learn more about these states and how you can either take advantage of them or skip the staged part entirely. @@ -161,14 +161,14 @@ If a particular version of a file is in the git directory, it’s considered com أو اذا كنت على نظام مبنى على ديبيان Debian مثل أوبونتو Ubuntu، يمكنك استخدام apt-get كالتالي: - $ apt-get install git-core + $ apt-get install git ### التنصيب على نظام الماك أو اس ### هناك طريقتين للتنصيب على ماك أو اس، الأسهل هي استخدام الواجهة الرسومية للتنصيب، والتي يمكنك تحميلها من صفحة المشروع على غوغل كود (انظر الشكل 1-7): - http://code.google.com/p/git-osx-installer + http://sourceforge.net/projects/git-osx-installer/ Insert 18333fig0107.png الشكل 1-7. تنصيب Git على ماك أو اس. @@ -184,7 +184,7 @@ Insert 18333fig0107.png يمكنك تنصيب Git على نظام ويندوز بسهولة. أحد أسهل الطرق هو استخدام مشروع msysGit. يمكنك تنصيب البرنامج من صفحة المشروع على غوغل كود: - http://code.google.com/p/msysgit + http://msysgit.github.com/ بعد التنصيب سيكون لدين نسختين من الأداة للـ command-line في ويندوز (بالإضافة الى أداة SSH والتي ستستفيد منها لاحقاً) والأداة بالواجهة الرسومية الإعتيادية. diff --git a/ar/02-git-basics/01-chapter2.markdown b/ar/02-git-basics/01-chapter2.markdown index 5b87c487c..72948c863 100644 --- a/ar/02-git-basics/01-chapter2.markdown +++ b/ar/02-git-basics/01-chapter2.markdown @@ -1,4 +1,4 @@ -# مبادئ Git # +# مبادئ Git # إذا كان هناك فصل واحد عليك قراءته لكي تبدأ بإستخدام Git، فعليك بهذا الفصل! يغطي هذا الفصل جميع الأوامر الأساسية التي عليك معرفتها لكي تتمكن من القيام بأغلب الأمور أثناء استخدامك لـ Git. في نهاية هذا الفصل يجب أن تكون قادراً على انشاء واعداد الـ repository لمشروعك وعلى تحديد الملفات التي ستتم متابعتها والتي ستترك، وعلى تهييئ التغييرات لعمل commit عليها. ستتعلم أيضاً كيف تعد Git لكي تتجاهل بعض أنواع الملفات، كيف تقوم بالتراجع عن الأخطاء التي سترتكبها بسرعة وبسهولة، كيف تتصفح تاريخ مشروعك وكيف تعرض التغيرات بين الـ commits، وكيف تنشر وتسحب (push & pull) التغيرات من الـ repositories البعيدة عنك. @@ -40,27 +40,26 @@ هناك عدد من البروتوكولات المختلفة التي يمكنك اسستعمالها لنقل المعلومات في git. المثال السابق يستعمل بروتوكول 'git://'، ولكن من الممكن أن تجد أيضاً استخداماً لـ 'http(s)://' أو 'user@server:/path.git'، والتي تستعمل بروتوكول SSH في النقل. في الفصل الرابع من الكتاب ستتعرف على الخيارات المتوفرة للتواصل مع الـ repository الخاصة بك وميزات ومساوئ كل منها. ## تسجيل التعديلات في الـ repository ## +لديك repository أصلي ونسخة لتعمل عليها من ملفات المشروع. عليك أن تقوم ببعض التعديلات ثم تعمل commit لهذه التعديلات في repository الخاص بك في كل مرة يصل فيها المشروع إلى نقطة تود تسجيلها. -You have a bona fide Git repository and a checkout or working copy of the files for that project. You need to make some changes and commit snapshots of those changes into your repository each time the project reaches a state you want to record. +تذكر أنه كل ملف في مجلد العمل يمكن أن يكون في إحدى الحالتين فقط: مٌتَتَبّع tracked أو غير مٌتَتَبّع untracked. الملفات المٌتتبّعة هي ملفات كانت في أخر snapshot ويمكن إلغاء التعديلات عليها أو التعديل عليها أو وضعه في حالة staged (جاهز من أجل commit). الملفات غير المُتتبّعة هي كل الملفات الآخرى - أي ملف في مجلد العمل لم يكن موجوداً في آخر snapshot وليس معلماً بأنه staged. عندما تقوم باستنساخ repository جميع ملفاتك تكون بحالة متتبّعة tracked و غير معدلة unmodified لأنك قمت للتو بعمل check out ولم تقم بأي تعديل. -Remember that each file in your working directory can be in one of two states: tracked or untracked. Tracked files are files that were in the last snapshot; they can be unmodified, modified, or staged. Untracked files are everything else - any files in your working directory that were not in your last snapshot and are not in your staging area. When you first clone a repository, all of your files will be tracked and unmodified because you just checked them out and haven’t edited anything. - -As you edit files, Git sees them as modified, because you’ve changed them since your last commit. You stage these modified files and then commit all your staged changes, and the cycle repeats. This lifecycle is illustrated in Figure 2-1. +عندما تعدل الملفات، سيقوم git بتأشيرهم على أنهم modified، لأنك قمت بتغيرهم عن آخر commit. تقوم بعمل stage لهذه الملفات المعدلة ثم تقوم بعمل commit لجميع التغيرات في منطقة stage، وتتكرر العملية. يوضع الشكل 2-1 دورة العملية. Insert 18333fig0201.png -Figure 2-1. The lifecycle of the status of your files. +الشكل 2-1. دورة حالة الملفات. -### Checking the Status of Your Files ### +### تفقد حالة ملفاتك ### -The main tool you use to determine which files are in which state is the git status command. If you run this command directly after a clone, you should see something like this: +باستخدام الأمر git status يمكننا معرفة حالة الملفات لدينا. إذا قمت بتشغيل هذا الأمر مباشرة بعد قيامك بعمل clone يجب أن ترى شيئاً يشبه التالي: $ git status # On branch master - nothing to commit (working directory clean) + nothing to commit, working directory clean -This means you have a clean working directory—in other words, there are no tracked and modified files. Git also doesn’t see any untracked files, or they would be listed here. Finally, the command tells you which branch you’re on. For now, that is always master, which is the default; you won’t worry about it here. The next chapter will go over branches and references in detail. +وهذا يعني أنه لديك مجلد عمل نظيف - بمعنى آخر، لايوجد أي ملفات معدلة أو ملفات غير مُتتبّعة. كما أنّ هذا الأمر يخبرك بأي فرع branch أنت تعمل. حالياً، دائماً هو master، وهو الافتراضي؛ في الفصل المقبل سنمر على الأفرع و المرجعيات references بالتفصيل. -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: +لنقل بأنك قمت بإضافة ملف جديد على مشروعك، وليكن ملف README بسيط. إذا لم يكن الملف موجوداً مسبقاً، وقمت بتنفيذ الأمر `git status` سترى الملف غير مُتتبّعاً كما يلي: $ vim README $ git status @@ -71,15 +70,15 @@ Let’s say you add a new file to your project, a simple README file. If the fil # README nothing added to commit but untracked files present (use "git add" to track) -You can see that your new README file is untracked, because it’s under the “Untracked files” heading in your status output. Untracked basically means that Git sees a file you didn’t have in the previous snapshot (commit); Git won’t start including it in your commit snapshots until you explicitly tell it to do so. It does this so you don’t accidentally begin including generated binary files or other files that you did not mean to include. You do want to start including README, so let’s start tracking the file. +يمكنك ملاحظة أنّ ملفك الجديد README غير مُتتبّع، فهو تحت تبويب "untracked files" في خرج الأمر. ويعني ذلك أنّ git يرى ملفاً جديداً على commit السابقة؛ علماً أنّ git لن يقوم بإضافة هذا الملف إلى الملفات المتتبعة إلا إذا قمت بطلب ذلك بشكل مباشر، والهدف من ذلك من أجل حماية المشروع من الضم الخاطئ لملفات binary أو أي ملفات لا تود بإضافتها. إلاّ أنّك ترغب في إضافة README إلى الملفات المتتبّعة. وسنقوم بذلك حالاً. -### Tracking New Files ### +### تتبع الملفات الجديدة ### -In order to begin tracking a new file, you use the command `git add`. To begin tracking the README file, you can run this: +للقيام بتتبع ملف جديد عليه استخدام الأمر `git add` . مثلاً لنقم بتتبع الملف الجديد README: $ git add README -If you run your status command again, you can see that your README file is now tracked and staged: +إذا قمنا بتنفيذ الأمر `git status` مرة أخرى سنلاحظ أن الملف README أصبح متتبعاً وجاهزاً staged للقيام بعملية commit: $ git status # On branch master @@ -89,11 +88,11 @@ If you run your status command again, you can see that your README file is now t # new file: README # -You can tell that it’s staged because it’s under the “Changes to be committed” heading. If you commit at this point, the version of the file at the time you ran git add is what will be in the historical snapshot. You may recall that when you ran git init earlier, you then ran git add (files) — that was to begin tracking files in your directory. The git add command takes a path name for either a file or a directory; if it’s a directory, the command adds all the files in that directory recursively. +نستطيع معرفة بأن الملف staged من خلال ملاحظته تحت بند "changes to be comitted". إذا قمت بعمل commit في هذه اللحظة، سيقوم git بإضافة النسخة الحالية من الملف إلى snapshot. تذكر عندما قمنا بعمل git init سابقاً، ثم قمنا بإضافة الملفات عن طريق git add، كان ذلك للقيام ببدء تتبع الملفات في مجلد المشروع. يقبل الأمر git add مسار لملف أو لمجلد؛ فإذا كان المسار لمجلد سيقوم git بإضافة جميع الملفات والمجلدات ضمنه بشكل تعاودي recursively. -### Staging Modified Files ### +### تجهيز الملفات المعدلة ### -Let’s change a file that was already tracked. If you change a previously tracked file called `benchmarks.rb` and then run your `status` command again, you get something that looks like this: +لنقم بالتعديل على ملف قمنا بإضافته سابقاً. إذا قمنا مثلاً بالتعديل على ملف متتبع مسبقاً يدعى `benchmarks.rb` وقمنا بتنفيذ الأمر git status، سيكون الخرج مشابهاً للخرج التالي: $ git status # On branch master @@ -102,13 +101,13 @@ Let’s change a file that was already tracked. If you change a previously track # # new file: README # - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # # modified: benchmarks.rb # -The benchmarks.rb file appears under a section named “Changed but not updated” — which means that a file that is tracked has been modified in the working directory but not yet staged. To stage it, you run the `git add` command (it’s a multipurpose command — you use it to begin tracking new files, to stage files, and to do other things like marking merge-conflicted files as resolved). Let’s run `git add` now to stage the benchmarks.rb file, and then run `git status` again: +يظهر الملف benchmarks.rb تحت بند "changes not staged for commit" وهذا يعني أن الملف المُتتبّع قد خضع لعملية تعديل لكنه لم يخضع للتجهيز من أجل commit. للقيام بتجهيزه (أو تأشيره للإضافة إلى commit الجديد) يجب علينا تنفيذ الأمر `git add` (لاحظ بأنّه أمر متعدد الوظائف - نستطيع استخدامه لتتبع الملفات الجديدة، تجهيز الملفات من أجل commit، والقيام بأمور أخرى مثل حل الاعتراضات في حال القيام بدمج merge). لنقم بتنفيذ git add الآن لوضع benchmarks.rb بحالة staged، ومن ثم لنقم بتنفيذ الأمر git status لنرى ما الذي قد تغيّر: $ git add benchmarks.rb $ git status @@ -120,7 +119,7 @@ The benchmarks.rb file appears under a section named “Changed but not updated # modified: benchmarks.rb # -Both files are staged and will go into your next commit. At this point, suppose you remember one little change that you want to make in benchmarks.rb before you commit it. You open it again and make that change, and you’re ready to commit. However, let’s run `git status` one more time: +كلا الملفين الآن جاهز للإدخال بعملية commit المقبلة. في هذه النقطة، لنفرض أنك تود القيام بتعديل على ملف benchmarks.rb قبل القيام بعملية commit، ستقوم بفتح الملف والتعديل عليه وأنك جاهز للقيام بعملية commit. لكن قبل ذلك، دعنا نقوم بتنفيذ الأمر git status مرة إضافية: $ vim benchmarks.rb $ git status @@ -131,13 +130,13 @@ Both files are staged and will go into your next commit. At this point, suppose # new file: README # modified: benchmarks.rb # - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # # modified: benchmarks.rb # -What the heck? Now benchmarks.rb is listed as both staged and unstaged. How is that possible? It turns out that Git stages a file exactly as it is when you run the git add command. If you commit now, the version of benchmarks.rb as it was when you last ran the git add command is how it will go into the commit, not the version of the file as it looks in your working directory when you run git commit. If you modify a file after you run `git add`, you have to run `git add` again to stage the latest version of the file: +ما الذي يحصل؟ كيف أصبح benchmarks.rb موجوداً تحت التبويبين staged و unstaged؟ لقد اتضح لنا أنّ git يقوم بتجهيز الملف على حالته عند قيامك بتنفيذ الأمر git add. إذا قمت بعمل commit الآن، ستكون نسخة benchmarks.rb كما كانت عند قيامك بتنفيذ الأمر git add وليس النسخة الجديدة التي حصلنا عليها بعد قيامنا بتعديل الملف. لذا إذا قمنا بتعديل ملف قبل قيامنا بتنفيذ git add، وقبل القيام بعملية commit، علينا تجهيز الملف مرة أخرى لعملية commit، وذلك بتنفيذ الأمر git add مرة جديدة: $ git add benchmarks.rb $ git status @@ -149,39 +148,45 @@ What the heck? Now benchmarks.rb is listed as both staged and unstaged. How is t # modified: benchmarks.rb # -### Ignoring Files ### +### تجاهل الملفات ### -Often, you’ll have a class of files that you don’t want Git to automatically add or even show you as being untracked. These are generally automatically generated files such as log files or files produced by your build system. In such cases, you can create a file listing patterns to match them named .gitignore. Here is an example .gitignore file: +غالباً ما تود من git تجاهل صنف من الملفات بحث لا يقوم بإضافتها تلقائياً أو لا يظهرها بأنّها غير متتبعة. تكون هذه الملفات عادة ملفات مولدة بشكل تلقائي مثل ملفات log و الملفات الوسيطة التي تولدها أدوات التطوير لديك. في مثل هذه الحالات/ يمكن إنشاء ملف .gitignore يحوي على أنماط لأسماء الملفات التي نرغب بتجاهلها. هذا مثال عمّا قد يحتويه ملف .gitignore: $ cat .gitignore *.[oa] *~ -The first line tells Git to ignore any files ending in .o or .a — object and archive files that may be the product of building your code. The second line tells Git to ignore all files that end with a tilde (`~`), which is used by many text editors such as Emacs to mark temporary files. You may also include a log, tmp, or pid directory; automatically generated documentation; and so on. Setting up a .gitignore file before you get going is generally a good idea so you don’t accidentally commit files that you really don’t want in your Git repository. +أول سطر يقوم بتوجيه git إلى تجاهل أي ملفات ذات لواحق من النوع o أو a - ملفات الكائنات وملفات الأرشيف وهي ملفات وسيطة تولدها أدوات بناء الكود عادة. السطر الثاني يوجه git إلى تجاهل أي ملفات تنتهي بالرمز (~) والتي تكون ملفات مؤقتة عادةً تستخدمها بعض برامج تحرير الكود. قد ترغب أيضاً بإضافة مجلدات log و tmp أو pid؛ أو حتى ملفات التوثيق تلقائية التوليد (من الكود عادة)، وغيرها. ينصح بإضافة ملف .gitignore في بداية إنشاء repository حتى نتجنب إضافة بعض الملفات عن طريق الخطأ وتلويث respository. -The rules for the patterns you can put in the .gitignore file are as follows: +قواعد الأنماط التي يمكن وضعها ضمن ملف .gitignore هي كالتالي: -* Blank lines or lines starting with # are ignored. -* Standard glob patterns work. -* 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 القياسية تعمل. +* يمكن إنهاء النمط برمز (/) للدلالة على أنه يستهدف مجلداً. +* يمكن نفي نمط ما عن طريق وضع علامة التعجب (!) في بداية السطر قبل النمط. -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) . +أنماط Glob عبارة عن نسخة مبسطة من Regular Expressions يتم استخدامها ضمن واجهة الأوامر shell. رمز النجمة (`*`) يطابق صفر-محرفاً أو أكثر. `[abc]` تطابق أي محارف ضمن الأقواس المربعة في هذه الحالة تكون a b c؛ علامة الاستفهام (?) تطابق محرفاً واحداً فقط؛ بينما تطابق الأقواس المربعة التي تحوي على محارف مفصولة بإشارة hyphen أي محرفاً يقع في المجال بين محرف البداية والنهاية - مثلا [0-9] يطابق محارف الأرقام بين 0 و 9 ضمناً. -Here is another example .gitignore file: +مثال عن ملف .gitignore: # a comment – this is ignored - *.a # no .a files - !lib.a # but do track lib.a, even though you're ignoring .a files above - /TODO # only ignore the root TODO file, not subdir/TODO - build/ # ignore all files in the build/ directory - doc/*.txt # ignore doc/notes.txt, but not doc/server/arch.txt + # no .a files + *.a + # but do track lib.a, even though you're ignoring .a files above + !lib.a + # only ignore the root TODO file, not subdir/TODO + /TODO + # ignore all files in the build/ directory + build/ + # ignore doc/notes.txt, but not doc/server/arch.txt + doc/*.txt -### Viewing Your Staged and Unstaged Changes ### +### مشاهدة التغيّرات المجهّزة والتغيّرات غير المجهّزة ### -If the `git status` command is too vague for you — you want to know exactly what you changed, not just which files were changed — you can use the `git diff` command. We’ll cover `git diff` in more detail later; but you’ll probably use it most often to answer these two questions: What have you changed but not yet staged? And what have you staged that you are about to commit? Although `git status` answers those questions very generally, `git diff` shows you the exact lines added and removed — the patch, as it were. +إذا لم تكتف بالمعلومات التي يقدمها لك أمر `git status` يمكنك استخدام أمر `git diff` للحصول على معلومات تفصيلية حول التغيرات التي طرأت على الملفات. سنقوم لاحقاً بالتعمق في هذا الأمر، لكن الآن سنكتفي بالإشارة إلى الاستخدامات الغالبة له؛ حيث أنك ستستخدمه غالباً للحصول على أجوبة على هذين السؤالين: ما الذي قمنا بالتعديل عليه ولم نجهزه بعد لعملية commit؟ ما الملفات التي أصبحت جاهزة للدخول في عملية commit المقبلة؟ +بالرغم من أنه يمكننا أن نحصل على هذه المعلومات باستخدام أمر `git status` إلا أنّ أمر `git diff` يوضح لنا التغيرات التي جرت على مستوى السطر والحرف - ما الذي قمنا بإضافته وما الذي أزلناه! -Let’s say you edit and stage the README file again and then edit the benchmarks.rb file without staging it. If you run your `status` command, you once again see something like this: +لنقل أنك قمت بالتعديل على ملف README مرة أخرى وأشرته للإضافة إلى عملية commit وقمت بالتعديل على ملف benchmarks.rb ولم تضفه إلى قائمة الملفات الجاهزة لعملية commit؛ إذا قمت بتنفيذ الأمر `status` ستشاهد مرة أخرى شيئاً من الشكل: $ git status # On branch master @@ -190,13 +195,13 @@ Let’s say you edit and stage the README file again and then edit the benchmark # # new file: README # - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # # modified: benchmarks.rb # -To see what you’ve changed but not yet staged, type `git diff` with no other arguments: +لترى ما قمت بالتعديل عليه ولم تجهزه للإضافة نفذ الأمر `git diff` بدون إضافات: $ git diff diff --git a/benchmarks.rb b/benchmarks.rb @@ -215,9 +220,9 @@ To see what you’ve changed but not yet staged, type `git diff` with no other a log = git.commits('master', 15) log.size -That command compares what is in your working directory with what is in your staging area. The result tells you the changes you’ve made that you haven’t yet staged. +يقوم هذا الأمر بعمل مقارنة بين الملفات ضمن مجلد العمل والملفات الموجودة في منطقة التعديلات المجهزة للإضافة staging area. وتخبرنا نتيجته بالتعديلات التي أجريناها ولم نقم بتجهيزها للإضافة إلى عملية commit المقبلة. -If you want to see what you’ve staged that will go into your next commit, you can use `git diff –-cached`. (In Git versions 1.6.1 and later, you can also use `git diff –-staged`, which may be easier to remember.) This command compares your staged changes to your last commit: +لمشاهدة الملفات ذات الحالة staged والتي ستدخل في عملية commit المقبلة، يمكن استخدام الأمر `git diff --cached` (بالنسبة للإصدارات 1.6.1 وما بعد من git يمكنك أيضاً استخدام الأمر `git diff --staged` )، كالتالي: $ git diff --cached diff --git a/README b/README @@ -232,9 +237,9 @@ If you want to see what you’ve staged that will go into your next commit, you + +Grit is a Ruby library for extracting information from a Git repository -It’s important to note that `git diff` by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. This can be confusing, because if you’ve staged all of your changes, `git diff` will give you no output. +من الجدير بالذكر أن أمر `git diff` لوحده لا يقوم بعرض جميع التعديلات التي تمت من آخر commit - فهو يقوم بعرض فقط التعديلات التي لم تؤشر على أنها staged. ويمكن أن يسبب ذلك بعض الإرباك، حيث أنك إذا قمت بإضافة جميع التعديلات إلى قائمة staged فلن يقوم بعرض أي شي في خرج تنفيذه. -For another example, if you stage the benchmarks.rb file and then edit it, you can use `git diff` to see the changes in the file that are staged and the changes that are unstaged: +كمثال أيضاً، إذا قمنا بإضافة benchmarks.rb إلى قائمة staged ومن ثم قمنا بالتعديل عليه من جديد، يمكننا استخدام أمر `git diff` للحصول على لائحة بالتغييرات التي حصلت ولم تضف إلى قائمة staged كالتالي: $ git add benchmarks.rb $ echo '# test line' >> benchmarks.rb @@ -245,12 +250,11 @@ For another example, if you stage the benchmarks.rb file and then edit it, you c # # modified: benchmarks.rb # - # Changed but not updated: + # Changes not staged for commit: # # modified: benchmarks.rb # -Now you can use `git diff` to see what is still unstaged $ git diff diff --git a/benchmarks.rb b/benchmarks.rb @@ -263,7 +267,7 @@ Now you can use `git diff` to see what is still unstaged ##pp Grit::GitRuby.cache_client.stats +# test line -and `git diff --cached` to see what you’ve staged so far: +وباستخدام `git diff --cached` نتمكن من رؤية ما تم تجهيزه للإضافة إلى عملية commit القادمة: $ git diff --cached diff --git a/benchmarks.rb b/benchmarks.rb @@ -282,16 +286,15 @@ and `git diff --cached` to see what you’ve staged so far: log = git.commits('master', 15) log.size -### Committing Your Changes ### +### القيام بعملية (اعتماد) commit للتغيّرات ### -Now that your staging area is set up the way you want it, you can commit your changes. Remember that anything that is still unstaged — any files you have created or modified that you haven’t run `git add` on since you edited them — won’t go into this commit. They will stay as modified files on your disk. -In this case, the last time you ran `git status`, you saw that everything was staged, so you’re ready to commit your changes. The simplest way to commit is to type `git commit`: +بعد اكمال تجهيز الملفات التي ترغب بإضافتها إلى النسخة snapshot الجديدة، يمكنك تنفيذ أمر commit ليتم اعتماد التعديلات التي أجريتها في سجل git. تذكر أنّ أي ملف لم يتم تجهيزه - سواء لم تقم بإضافته باستخدام الأمر git add بعد إنشاءه أو التعديل عليه - لن يدخل في هذه الإعتمادية، وستبقى على أنها ملفات تم تعديلها في مجلد العمل. أبسط طريقة لاعتماد التعديلات هي القيام بأمر `git commit` كالتالي: $ git commit -Doing so launches your editor of choice. (This is set by your shell’s `$EDITOR` environment variable — usually vim or emacs, although you can configure it with whatever you want using the `git config --global core.editor` command as you saw in Chapter 1). +تنفيذ هذا الأمر سيطلب منا إدخال رسالة عملية commit - عادة ما يتم فتح محرر النصوص المشار إليه بمتغير البيئة `$EDITOR`. يمكنك تهيئته عن طريق الأمر `git config --global core.editor` كما شاهدنا في الفصل الأول. -The editor displays the following text (this example is a Vim screen): +يقوم محرر النصوص بعرض هذه الشاشة (مثالنا باستخدام VIM): # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. @@ -306,27 +309,27 @@ The editor displays the following text (this example is a Vim screen): ~ ".git/COMMIT_EDITMSG" 10L, 283C -You can see that the default commit message contains the latest output of the `git status` command commented out and one empty line on top. You can remove these comments and type your commit message, or you can leave them there to help you remember what you’re committing. (For an even more explicit reminder of what you’ve modified, you can pass the `-v` option to `git commit`. Doing so also puts the diff of your change in the editor so you can see exactly what you did.) When you exit the editor, Git creates your commit with that commit message (with the comments and diff stripped out). +يمكنك ملاحظة أن رسالة عملية commit تحوي على خرج آخر عملية `git status` على شكل تعليقات بالإضافة إلى سطر فارغ في بداية الملف. يمكنك إزالة هذه التعليقات، أو يمكنك تركها لمساعدتك بتذكر ما قمت باعتماد تعديلاته. يمكنك الحصول على معلومات أكثر تفصلياً إذا قمت بتمرير الخيار `-v` إلى الأمر `git commit`. حيث يقوم ذلك بإضافة خرج أمر `git diff` إلى رسالة commit على شكل تعليقات أيضاً. عند إغلاق المحرر يقوم git بإنشاء commit ويتجاهل التعليقات. -Alternatively, you can type your commit message inline with the `commit` command by specifying it after a -m flag, like this: +علماً أنّه يمكنك كتابة رسالة الاعتمادية مباشرة من خلال تمرير الخيار `-m` إلى الأمر `git commit` على الشكل التالي: $ git commit -m "Story 182: Fix benchmarks for speed" [master]: created 463dc4f: "Fix benchmarks for speed" 2 files changed, 3 insertions(+), 0 deletions(-) create mode 100644 README -Now you’ve created your first commit! You can see that the commit has given you some output about itself: which branch you committed to (master), what SHA-1 checksum the commit has (`463dc4f`), how many files were changed, and statistics about lines added and removed in the commit. +مبروك، لقد قمت بعمل أول commit لك! يعطيك خرج العملية معلومات عنها: في أي فرع branch تم الإعتماد (هنا master)، ما قيمة هاش SHA-1 الخاصة بالعملية ( هنا `463dc4f`)، عدد الملفات التي تغيّرت، بالإضافة إلى إحصاءات حول الأسطر التي أضيفت وأزيلت في هذه العملية. -Remember that the commit records the snapshot you set up in your staging area. Anything you didn’t stage is still sitting there modified; you can do another commit to add it to your history. Every time you perform a commit, you’re recording a snapshot of your project that you can revert to or compare to later. +تذكر أنّ عملية commit تأخذ صورة عن الملفات في قائمة staged. أي شيء لم تقم بإضافته إلى هذه القائمة ما زال في مجلد العمل بحالة "معدل" modified؛ يمكنك القيام بإضافتهم من خلال عملية commit جديدة إلى التأريخ في git. نستنتج أنّه في كل عملية commit يقوم git بأخذ "صورة" snapshot عن المشروع يمكننا العودة لها لاحقاً أو مقارنتها أو غير ذلك.. -### Skipping the Staging Area ### +### تجاوز منطقة التجهيز Staging Area ### -Although it can be amazingly useful for crafting commits exactly how you want them, the staging area is sometimes a bit more complex than you need in your workflow. If you want to skip the staging area, Git provides a simple shortcut. Providing the `-a` option to the `git commit` command makes Git automatically stage every file that is already tracked before doing the commit, letting you skip the `git add` part: +منطقة التجهيز تكون أحياناً معقدة أكثر مما تحتاج في عملك إلا أنّها مفيدة لعمل commits تماماً كما تودهم أن يكونوا. إذا أردت تجاوز منطقة التجهيز، يوفر git اختصاراً بسيطاً لذلك. باستخدام الأمر `git commit -a` يقوم git بإضافة الملفات المتتبعة إلى منطقة التجهيز بشكل تلقائي، كأنك قمت بعمل `git add`: $ git status # On branch master # - # Changed but not updated: + # Changes not staged for commit: # # modified: benchmarks.rb # @@ -334,25 +337,25 @@ Although it can be amazingly useful for crafting commits exactly how you want th [master 83e38c7] added new benchmarks 1 files changed, 5 insertions(+), 0 deletions(-) -Notice how you don’t have to run `git add` on the benchmarks.rb file in this case before you commit. +لاحظ بأنك لاتحتاج إلى تنفيذ الأمر `git add` على ملف benchmark.rb قبل القيام بعملية commit. -### Removing Files ### +### إزالة الملفات ### -To remove a file from Git, you have to remove it from your tracked files (more accurately, remove it from your staging area) and then commit. The `git rm` command does that and also removes the file from your working directory so you don’t see it as an untracked file next time around. +لحذف ملف من git، يجب عليك إزالته من قائمة الملفات المتتبعة (وبشكل أدق، إزالته من منطقة التجهيز) ومن ثم القيام بعملية commit. الأمر `git rm` يقوم بعمل ذلك كما يقوم بحذف الملف من مجلد العمل الخاص بك لذا لن تراه بعد الآن في قائمة الملفات غير المتتبعة في المرة المقبلة. -If you simply remove the file from your working directory, it shows up under the “Changed but not updated” (that is, _unstaged_) area of your `git status` output: +إذا قمت بإزالة الملف من مجلد العمل، يظهر تحت بند "تعديلات غير مجهزة للاعتماد" (أي _unstaged_) من خرج الأمر `git status`: $ rm grit.gemspec $ git status # On branch master # - # Changed but not updated: + # Changes not staged for commit: # (use "git add/rm ..." to update what will be committed) # # deleted: grit.gemspec # -Then, if you run `git rm`, it stages the file’s removal: +فإذا قمت بتنفيذ أمر `git rm` يقوم بتجهيز عملية الحذف ليتم اعتمادها: $ git rm grit.gemspec rm 'grit.gemspec' @@ -365,31 +368,31 @@ Then, if you run `git rm`, it stages the file’s removal: # deleted: grit.gemspec # -The next time you commit, the file will be gone and no longer tracked. If you modified the file and added it to the index already, you must force the removal with the `-f` option. This is a safety feature to prevent accidental removal of data that hasn’t yet been recorded in a snapshot and that can’t be recovered from Git. +وفي المرة المقبلة التي ستقوم فيها بعمل commit، سيتم إزالة الملف من قائمة التتبع. إذا قمت مسبقاً بتعديل الملف وإضفته إلى الفهرس، يجب عليه تنفيذ عملية الحذف قسرياً وذلك بإضافة الخيار `-f`. يتم اتباع هذه الطريقة بغية حماية البيانات من أية عمليات حذف "عرضية" لملفات لم يتم تسجيلها ضمن git ولايمكن استعادتها بعد ذلك. -Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. In other words, you may want to keep the file on your hard drive but not have Git track it anymore. This is particularly useful if you forgot to add something to your `.gitignore` file and accidentally added it, like a large log file or a bunch of `.a` compiled files. To do this, use the `--cached` option: +أما إذا أردت إزالة الملف من منطقة التجهيز مع الحفاظ عليه في مجلد العمل (أي إزالته من تتبع git مع بقاءه على وسيطة التخزين) - وهو شيء مفيد إذا قمت بنسيان إضافة شيء ما إلى ملف `.gitignore` وأضفته عن طريق الخطأ ؛ كملف log كبير مثلاً - استخدم الخيار `--cached` مع الأمر `git rm` كالتالي: $ git rm --cached readme.txt -You can pass files, directories, and file-glob patterns to the `git rm` command. That means you can do things such as +يمكنك تمرير أسماء ملفات، مجلدات، وأنماط glob للأمر `git rm`. وهذا يعني بأنه يمكننا عمل أشياء كالتالي: $ git rm log/\*.log -Note the backslash (`\`) in front of the `*`. This is necessary because Git does its own filename expansion in addition to your shell’s filename expansion. This command removes all files that have the `.log` extension in the `log/` directory. Or, you can do something like this: +لاحظ الشرطة العكسية (`\`) قبل رمز النجمة `*`. إنّها ضرورية لأن git يقوم بعمل توسعة الأسماء الخاصة به بالإضافة إلى التوسعة الخاصة بسطر الأوامر. هذا الأمر يقوم بحذف كافة الملفات التي تملك اللاحقة `.log` في مجلد `/log`. أو يمكنك عمل شيء كالتالي: $ git rm \*~ -This command removes all files that end with `~`. +وهذا الأمر يقوم بحذف كافة الملفات المنتهية بالمحرف `~`. -### Moving Files ### +### نقل الملفات ### -Unlike many other VCS systems, Git doesn’t explicitly track file movement. If you rename a file in Git, no metadata is stored in Git that tells it you renamed the file. However, Git is pretty smart about figuring that out after the fact — we’ll deal with detecting file movement a bit later. +على خلاف أغلب أنظمة إدارة الإصدارات VCS الأخرى، لا يقوم git بتعقب حركة الملفات بشكل صريح. إذا قمت بإعادة تسمية ملف ضمن git، لايتم تسجيل أي بيانات وصفية metadata في git تقوم بأنك قمت بإعادة تسمية الملف. لكن، git ذكي جداً في استعياب ذلك - وسنقوم بمناقشة الأمر بعد قليل. -Thus it’s a bit confusing that Git has a `mv` command. If you want to rename a file in Git, you can run something like +إذا أردت القيام بإعادة تسمية ملف يمكنك استخدام أمر `mv` في git كالتالي: $ git mv file_from file_to -and it works fine. In fact, if you run something like this and look at the status, you’ll see that Git considers it a renamed file: +إذا قمنا بتنفيذ الأمر والنظر إلى خرج أمر `git status`: $ git mv README.txt README $ git status @@ -402,23 +405,23 @@ and it works fine. In fact, if you run something like this and look at the statu # renamed: README.txt -> README # -However, this is equivalent to running something like this: +وهو مكافئ للقيام بتنفيذ الأوامر التالي على التسلسل: $ mv README.txt README $ git rm README.txt $ 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 `mv` is one command instead of three — it’s a convenience function. More important, you can use any tool you like to rename a file, and address the add/rm later, before you commit. +يدرك git بأنك قمت بعملية إعادة تسمية، لذا فالإختلاف الوحيد بين الطريقتين هو أنّ `git mv` عبارة عن أمر واحد، وليس ثلاثة أوامر. يمكن الاستفادة من هذه الخاصة باستخدام أية أدوات للقيام بعمليات إعادة التسمية، واستخدام add/rm قبل القيام بعملية commit. -## Viewing the Commit History ## +## مراجعة تأريخ عمليات commit ## -After you have created several commits, or if you have cloned a repository with an existing commit history, you’ll probably want to look back to see what has happened. The most basic and powerful tool to do this is the `git log` command. +بعد قيامك بعدد من عمليات الاعتماد commit، أو استنساخ repository بسجل تأريخ، ربما ستود إلقاء نظرة على ما جرى. أبسط وأقوى أداة لعمل ذلك هي الأمر `git log`. -These examples use a very simple project called simplegit that I often use for demonstrations. To get the project, run +هذه الأمثلة تستخدم مشروع بسيط جداً يدعى simplegit أقوم باستخدامه في عمليات العرض بأغلب الأحيان. للحصول على المشروع قم باستنساخه عن موقع github كالتالي: git clone git://github.com/schacon/simplegit-progit.git -When you run `git log` in this project, you should get output that looks something like this: +عندما تقوم بعمل `git log` ضمن المشروع، سيظهر لديك خرج مشابه للتالي: $ git log commit ca82a6dff817ec66f44342007202690a93763949 @@ -439,11 +442,11 @@ When you run `git log` in this project, you should get output that looks somethi first commit -By default, with no arguments, `git log` lists the commits made in that repository in reverse chronological order. That is, the most recent commits show up first. As you can see, this command lists each commit with its SHA-1 checksum, the author’s name and e-mail, the date written, and the commit message. +بتنفيذ الأمر بدون بارمترات، يقوم git بعرض عمليات commit في repository بترتيب زمني معكوس - من الأحدث إلى الأقدم. كما يقوم بعرض بجانب كل commit هاش SHA-1 checksum الخاص بها، اسم وبريد الكاتب الإلكتروني، تاريخ الاعتماد، ورسالة الاعتماد. -A huge number and variety of options to the `git log` command are available to show you exactly what you’re looking for. Here, we’ll show you some of the most-used options. +يمكن إرفاق الأمر `git log` بعدد كبير من الخيارات للحصول على المعلومات التي نريدها بالضبط.. تجد في الأسفل مثالاً عن أكثر الخيارات استخداماً. -One of the more helpful options is `-p`, which shows the diff introduced in each commit. You can also use `-2`, which limits the output to only the last two entries: +أحد أهم الخيارات هو `-p`، والذي يقوم بإظهار الفوارق المستحدثة بين عمليات commit المختلفة. يمكن أيضاً استخدام الخيار `-2` ليحد خرج النتيجة إلى آخر عمليتين: $ git log –p -2 commit ca82a6dff817ec66f44342007202690a93763949 @@ -483,8 +486,7 @@ One of the more helpful options is `-p`, which shows the diff introduced in each -end \ No newline at end of file -This option displays the same information but with a diff directly following each entry. This is very helpful for code review or to quickly browse what happened during a series of commits that a collaborator has added. -You can also use a series of summarizing options with `git log`. For example, if you want to see some abbreviated stats for each commit, you can use the `--stat` option: +هذا الخيار يعرض نفس المعلومات بالإضافة خرج diff بعده مباشرة. فهو مهم جداً من أجل مراجعة الكود واستعراض ما الذي تغير بشكل سريع ضمن سلسلة من عمليات commit. يمكنك أيضاً استخدام خيارات للتلخيص مع أمر `git log`. على سبيل المثال، إذا أردت رؤية بعض الإحصاءات المختصرة لكل commit، يمكنك استخدام الخيار `stat`: $ git log --stat commit ca82a6dff817ec66f44342007202690a93763949 @@ -516,43 +518,43 @@ You can also use a series of summarizing options with `git log`. For example, if lib/simplegit.rb | 25 +++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 0 deletions(-) -As you can see, the `--stat` option prints below each commit entry a list of modified files, how many files were changed, and how many lines in those files were added and removed. It also puts a summary of the information at the end. -Another really useful option is `--pretty`. This option changes the log output to formats other than the default. A few prebuilt options are available for you to use. The oneline option prints each commit on a single line, which is useful if you’re looking at a lot of commits. In addition, the `short`, `full`, and `fuller` options show the output in roughly the same format but with less or more information, respectively: +كما ترى باستخدام الخيار `--stat` يتم عرض قائمة من الملفات المعدلة، عدد الملفات التي تغيرت، وعدد الأسطر التي أضيفت أو أزيلت. كما يضع ملخصاً للمعلومات في النهاية. +يوجد خيار مفيد آخر وهو `--pretty`. هذا الخيار يغير خرج السل إلى صيغ غير الافتراضية. يوجد بعضها مركب مسبقاً. مثلاً `oneline` يقوم بطباعة كل commit على سطر لوحدها، وهذا أمر مفيد في حال كنت تنظر إلى العديد من عمليات commit. بالإضافة إلى `short`، `full` و `fuller` والتي تعرض خرجاً تقريباً بنفس الصيغة مع معلومات أكثر أو أقل: $ git log --pretty=oneline ca82a6dff817ec66f44342007202690a93763949 changed the version number 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 removed unnecessary test code a11bef06a3f659402fe7563abf99ad00de2209e6 first commit -The most interesting option is `format`, which allows you to specify your own log output format. This is especially useful when you’re generating output for machine parsing — because you specify the format explicitly, you know it won’t change with updates to Git: +أكثر الخيارات أهمية هو `format`، والذي يسمح لك بتحديد صيغة الخرج بشكل صريح بما يتناسب مع إعرابها آلياً - حيث أنك تعرف أنّه لن يتغير عند التحديث إلى git: $ git log --pretty=format:"%h - %an, %ar : %s" ca82a6d - Scott Chacon, 11 months ago : changed the version number 085bb3b - Scott Chacon, 11 months ago : removed unnecessary test code a11bef0 - Scott Chacon, 11 months ago : first commit -Table 2-1 lists some of the more useful options that format takes. - - Option Description of Output - %H Commit hash - %h Abbreviated commit hash - %T Tree hash - %t Abbreviated tree hash - %P Parent hashes - %p Abbreviated parent hashes - %an Author name - %ae Author e-mail - %ad Author date (format respects the –date= option) - %ar Author date, relative - %cn Committer name - %ce Committer email - %cd Committer date - %cr Committer date, relative - %s Subject - -You may be wondering what the difference is between _author_ and _committer_. The author is the person who originally wrote the work, whereas the committer is the person who last applied the work. So, if you send in a patch to a project and one of the core members applies the patch, both of you get credit — you as the author and the core member as the committer. We’ll cover this distinction a bit more in Chapter 5. - -The oneline and format options are particularly useful with another `log` option called `--graph`. This option adds a nice little ASCII graph showing your branch and merge history, which we can see our copy of the Grit project repository: +الجدول 2-1 يعرض بعض الخيارات المفيدة التي يمكن إضافتها إلى الصيغة. + + الخيار وصف الخرج + %H Commit هاش + %h الهاش الاعتمادي المختصر + %T هاش الشجرة + %t هاش الشجرة المختصر + %P هاشات الوالد + %p هاشات الوالد المختصرة + %an اسم الكاتب + %ae بريد الكاتب الإلكتروني + %ad تاريخ الكاتب (يراعي الصيغة –date= option) + %ar تاريخ الكاتب - نسبياً + %cn اسم منفذ الاعتماد + %ce بريد منفذ الاعتماد الإلكتروني + %cd تاريخ منفذ الاعتماد + %cr تاريخ منفذ الاعتماد - نسبياً + %s العنوان + +قد تتسائل عن الاختلاف بين _الكاتب_ AUTHOR و _منفذ الاعتماد_ COMMITTER. الكاتب هو الشخص الذي كتب العمل بداية، بينما منفذ الاعتماد هو آخر شخص طبق العمل. لذا، إذا أرسلت باتشاً إلى مشروع وأحد المطورين الرئيسين قام بتطبيق الباتش، تأخذان كلاكما الاعتمادية - أنت ككاتب وهو كمنفذ اعتماد. + +وتكون هذه الخيارات مفيدة أكثر بالترافق مع الخيار `--graph`. حيث يضيف هذا الأمر غراف ASCII بسيط يوضح تأريخ الأفرع و الدمج، لاحظ التالي: $ git log --pretty=format:"%h %s" --graph * 2d3acf9 ignore errors from SIGCHLD on trap @@ -566,43 +568,43 @@ The oneline and format options are particularly useful with another `log` option * d6016bc require time for xmlschema * 11d191e Merge branch 'defunkt' into local -Those are only some simple output-formatting options to `git log` — there are many more. Table 2-2 lists the options we’ve covered so far and some other common formatting options that may be useful, along with how they change the output of the log command. +يوجد مجموعة من الخيارات البسيطة مع أمر `git log`. يوضح الجدول 2-2 قائمة من الخيارات التي قمنا بتغطيتها حتى الآن وبعض صيغ التنسيق الشائعة والتي قد تكون مفيدة، وبجانبها شرح مبسط عن التغيير الذي تجريه على الخرج. - Option Description - -p Show the patch introduced with each commit. - --stat Show statistics for files modified in each commit. + الخيار الوصف + -p يظهر الباتش المدخل مع كل عملية commit. + --stat يظهر إحصاءات حول التعديلات التي حصلت على الملفات مع كل عملية commit. --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. + --name-only يظهر قائمة الملفات المعدلة. + --name-status يظهر قائمة الملفات المعدلة عن طريق الإضافة والحذف وغير ذلك. + --abbrev-commit يظهر أول مجموعة من هاش SHA-1 بدلاً عن كامل الأحرف 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. + --graph عرض غراف ASCII مع الخرج يظهر عمليات التفريع و الدمج. --pretty Show commits in an alternate format. Options include oneline, short, full, fuller, and format (where you specify your own format). -### Limiting Log Output ### +### تحديد خرج السجل ### -In addition to output-formatting options, git log takes a number of useful limiting options — that is, options that let you show only a subset of commits. You’ve seen one such option already — the `-2` option, which show only the last two commits. In fact, you can do `-`, where `n` is any integer to show the last `n` commits. In reality, you’re unlikely to use that often, because Git by default pipes all output through a pager so you see only one page of log output at a time. +بالإضافة تحديد شكل الخرج، يسمح git بأخذ مجموعة جزئية فقط من الخرج. وقد قمت بمشاهدة ذلك مسبقاً - الخيار `-2` المستخدم لعرض آخر عمليتي commit. في الواقع يمكنك استخدام `-` حيث `n` هي عدد صحيح لعرض آخر `n` عملية commit. في الحقيقة، لن تستخدمها على الغالب، لأن git يقوم بتمرير كامل الخرج لبرنامج تصفح لتتمكن من تصفح عمليات commit صفحة صفحة. -However, the time-limiting options such as `--since` and `--until` are very useful. For example, this command gets the list of commits made in the last two weeks: +من الخيارات الهامة جداً، المحددات الزمنية مثل `--since` و `--until`. على سبيل المثال، هذا الأمر يعطيك قائمة بعمليات commit التي حصلت في آخر أسبوعين: $ git log --since=2.weeks -This command works with lots of formats — you can specify a specific date (“2008-01-15”) or a relative date such as “2 years 1 day 3 minutes ago”. +ويعمل هذا الأمر مع أنواع كثيرة من الصيغ - يمكنك تحديد تاريخ محدد ("2008-01-15") أو تاريخ نسبي مثل "2 years 1 day 3 minutes ago". -You can also filter the list to commits that match some search criteria. The `--author` option allows you to filter on a specific author, and the `--grep` option lets you search for keywords in the commit messages. (Note that if you want to specify both author and grep options, you have to add `--all-match` or the command will match commits with either.) +يكطمط أيضاً تصفية قائمة عمليات commit من خلال محددات البحث. مثلاً خيار `--author` يقوم بتصفية النتائج وفق كاتب محدد، و `--grep` يقوم بالفلترة عن طريق كلمة مفتاحية. (لاحظ أنّه إذا قمت بإضافة خياراي author و grep، يجب عليك إضافة الخيار `--all-match` أو سيقوم git بعمل مطابقة مع أحدهما فقط). -The last really useful option to pass to `git log` as a filter is a path. If you specify a directory or file name, you can limit the log output to commits that introduced a change to those files. This is always the last option and is generally preceded by double dashes (`--`) to separate the paths from the options. +آخر الخيارات الهامة التي يمكن تمريرها إلى الأمر `git log` كمصناف هي المسار. إذا قمت بتحديد مجلد أو اسم ملف، يمكنك تحديد الخرج إلى عمليات commit التي آثرت في هذا المسار. ودائماً ما يكون آخر خيار يوضع في `log` ويسبق بداشين double dashes (`--`) ليفصل المسارات عن الخيارات. -In Table 2-3 we’ll list these and a few other common options for your reference. +في الجدول 2-3 - نعرض الخيارات التي يمكن إضافتها مع log. - Option Description - -(n) 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. + خيار وصف + -(n) يظهر آن n عملية commit. + --since, --after تحديد عمليات commit بعد التاريخ الذي يتلوها. + --until, --before تحديد عمليات commit حتى التاريخ الذي يتلوها. + --author فقط أظهر عمليات commit التابعة لهذا الكاتب. + --committer فقط أظهر عمليات commit التابعة لهذا المعتمد. -For example, if you want to see which commits modifying test files in the Git source code history were committed by Junio Hamano and were not merges in the month of October 2008, you can run something like this: +على سبيل المثال، إذا أردت رؤية أي عمليات commit عدلت ملفات الاختبار في تأريخ الكود المصدري والتي قام Junio Hamano بعملها ولم يتم دمجها في شهر أوكتوبر 2008، يمكن كتابة هذا الأمر: $ git log --pretty="%h - %s" --author=gitster --since="2008-10-01" \ --before="2008-11-01" --no-merges -- t/ @@ -613,7 +615,7 @@ For example, if you want to see which commits modifying test files in the Git so 51a94af - Fix "checkout --track -b newbranch" on detac b0ad11e - pull: allow "git pull origin $something:$cur -Of the nearly 20,000 commits in the Git source code history, this command shows the 6 that match those criteria. +من بين 20 ألف عملية commit تقريباً في تأريخ git الخاص بهذا الكود المصدري، أظهر الأمر فقط عمليات الاعتماد الستة المطابقة لمحددات البحث. ### Using a GUI to Visualize History ### @@ -671,7 +673,7 @@ Right below the “Changes to be committed” text, it says use `git reset HEAD # # modified: README.txt # - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # (use "git checkout -- ..." to discard changes in working directory) # @@ -684,7 +686,7 @@ The command is a bit strange, but it works. The benchmarks.rb file is modified b What if you realize that you don’t want to keep your changes to the benchmarks.rb file? How can you easily unmodify it — revert it back to what it looked like when you last committed (or initially cloned, or however you got it into your working directory)? Luckily, `git status` tells you how to do that, too. In the last example output, the unstaged area looks like this: - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # (use "git checkout -- ..." to discard changes in working directory) # @@ -1115,7 +1117,7 @@ This way, you can see the last commit easily: As you can tell, Git simply replaces the new command with whatever you alias it for. However, maybe you want to run an external command, rather than a Git subcommand. In that case, you start the command with a `!` character. This is useful if you write your own tools that work with a Git repository. We can demonstrate by aliasing `git visual` to run `gitk`: - $ git config --global alias.visual "!gitk" + $ git config --global alias.visual '!gitk' ## Summary ## diff --git a/ar/08-git-and-other-scms/01-chapter8.markdown b/ar/08-git-and-other-scms/01-chapter8.markdown deleted file mode 100644 index f9abf256b..000000000 --- a/ar/08-git-and-other-scms/01-chapter8.markdown +++ /dev/null @@ -1,685 +0,0 @@ -# Git and Other Systems # - -The world isn’t perfect. Usually, you can’t immediately switch every project you come in contact with to Git. Sometimes you’re stuck on a project using another VCS, and many times that system is Subversion. You’ll spend the first part of this chapter learning about `git svn`, the bidirectional Subversion gateway tool in Git. - -At some point, you may want to convert your existing project to Git. The second part of this chapter covers how to migrate your project into Git: first from Subversion, then from Perforce, and finally via a custom import script for a nonstandard importing case. - -## Git and Subversion ## - -Currently, the majority of open source development projects and a large number of corporate projects use Subversion to manage their source code. It’s the most popular open source VCS and has been around for nearly a decade. It’s also very similar in many ways to CVS, which was the big boy of the source-control world before that. - -One of Git’s great features is a bidirectional bridge to Subversion called `git svn`. This tool allows you to use Git as a valid client to a Subversion server, so you can use all the local features of Git and then push to a Subversion server as if you were using Subversion locally. This means you can do local branching and merging, use the staging area, use rebasing and cherry-picking, and so on, while your collaborators continue to work in their dark and ancient ways. It’s a good way to sneak Git into the corporate environment and help your fellow developers become more efficient while you lobby to get the infrastructure changed to support Git fully. The Subversion bridge is the gateway drug to the DVCS world. - -### git svn ### - -The base command in Git for all the Subversion bridging commands is `git svn`. You preface everything with that. It takes quite a few commands, so you’ll learn about the common ones while going through a few small workflows. - -It’s important to note that when you’re using `git svn`, you’re interacting with Subversion, which is a system that is far less sophisticated than Git. Although you can easily do local branching and merging, it’s generally best to keep your history as linear as possible by rebasing your work and avoiding doing things like simultaneously interacting with a Git remote repository. - -Don’t rewrite your history and try to push again, and don’t push to a parallel Git repository to collaborate with fellow Git developers at the same time. Subversion can have only a single linear history, and confusing it is very easy. If you’re working with a team, and some are using SVN and others are using Git, make sure everyone is using the SVN server to collaborate — doing so will make your life easier. - -### Setting Up ### - -To demonstrate this functionality, you need a typical SVN repository that you have write access to. If you want to copy these examples, you’ll have to make a writeable copy of my test repository. In order to do that easily, you can use a tool called `svnsync` that comes with more recent versions of Subversion — it should be distributed with at least 1.4. For these tests, I created a new Subversion repository on Google code that was a partial copy of the `protobuf` project, which is a tool that encodes structured data for network transmission. - -To follow along, you first need to create a new local Subversion repository: - - $ mkdir /tmp/test-svn - $ svnadmin create /tmp/test-svn - -Then, enable all users to change revprops — the easy way is to add a pre-revprop-change script that always exits 0: - - $ cat /tmp/test-svn/hooks/pre-revprop-change - #!/bin/sh - exit 0; - $ chmod +x /tmp/test-svn/hooks/pre-revprop-change - -You can now sync this project to your local machine by calling `svnsync init` with the to and from repositories. - - $ svnsync init file:///tmp/test-svn http://progit-example.googlecode.com/svn/ - -This sets up the properties to run the sync. You can then clone the code by running - - $ svnsync sync file:///tmp/test-svn - Committed revision 1. - Copied properties for revision 1. - Committed revision 2. - Copied properties for revision 2. - Committed revision 3. - ... - -Although this operation may take only a few minutes, if you try to copy the original repository to another remote repository instead of a local one, the process will take nearly an hour, even though there are fewer than 100 commits. Subversion has to clone one revision at a time and then push it back into another repository — it’s ridiculously inefficient, but it’s the only easy way to do this. - -### Getting Started ### - -Now that you have a Subversion repository to which you have write access, you can go through a typical workflow. You’ll start with the `git svn clone` command, which imports an entire Subversion repository into a local Git repository. Remember that if you’re importing from a real hosted Subversion repository, you should replace the `file:///tmp/test-svn` here with the URL of your Subversion repository: - - $ git svn clone file:///tmp/test-svn -T trunk -b branches -t tags - Initialized empty Git repository in /Users/schacon/projects/testsvnsync/svn/.git/ - r1 = b4e387bc68740b5af56c2a5faf4003ae42bd135c (trunk) - A m4/acx_pthread.m4 - A m4/stl_hash.m4 - ... - r75 = d1957f3b307922124eec6314e15bcda59e3d9610 (trunk) - Found possible branch point: file:///tmp/test-svn/trunk => \ - file:///tmp/test-svn /branches/my-calc-branch, 75 - Found branch parent: (my-calc-branch) d1957f3b307922124eec6314e15bcda59e3d9610 - Following parent with do_switch - Successfully followed parent - r76 = 8624824ecc0badd73f40ea2f01fce51894189b01 (my-calc-branch) - Checked out HEAD: - file:///tmp/test-svn/branches/my-calc-branch r76 - -This runs the equivalent of two commands — `git svn init` followed by `git svn fetch` — on the URL you provide. This can take a while. The test project has only about 75 commits and the codebase isn’t that big, so it takes just a few minutes. However, Git has to check out each version, one at a time, and commit it individually. For a project with hundreds or thousands of commits, this can literally take hours or even days to finish. - -The `-T trunk -b branches -t tags` part tells Git that this Subversion repository follows the basic branching and tagging conventions. If you name your trunk, branches, or tags differently, you can change these options. Because this is so common, you can replace this entire part with `-s`, which means standard layout and implies all those options. The following command is equivalent: - - $ git svn clone file:///tmp/test-svn -s - -At this point, you should have a valid Git repository that has imported your branches and tags: - - $ git branch -a - * master - my-calc-branch - tags/2.0.2 - tags/release-2.0.1 - tags/release-2.0.2 - tags/release-2.0.2rc1 - trunk - -It’s important to note how this tool namespaces your remote references differently. When you’re cloning a normal Git repository, you get all the branches on that remote server available locally as something like `origin/[branch]` - namespaced by the name of the remote. However, `git svn` assumes that you won’t have multiple remotes and saves all its references to points on the remote server with no namespacing. You can use the Git plumbing command `show-ref` to look at all your full reference names: - - $ git show-ref - 1cbd4904d9982f386d87f88fce1c24ad7c0f0471 refs/heads/master - aee1ecc26318164f355a883f5d99cff0c852d3c4 refs/remotes/my-calc-branch - 03d09b0e2aad427e34a6d50ff147128e76c0e0f5 refs/remotes/tags/2.0.2 - 50d02cc0adc9da4319eeba0900430ba219b9c376 refs/remotes/tags/release-2.0.1 - 4caaa711a50c77879a91b8b90380060f672745cb refs/remotes/tags/release-2.0.2 - 1c4cb508144c513ff1214c3488abe66dcb92916f refs/remotes/tags/release-2.0.2rc1 - 1cbd4904d9982f386d87f88fce1c24ad7c0f0471 refs/remotes/trunk - -A normal Git repository looks more like this: - - $ git show-ref - 83e38c7a0af325a9722f2fdc56b10188806d83a1 refs/heads/master - 3e15e38c198baac84223acfc6224bb8b99ff2281 refs/remotes/gitserver/master - 0a30dd3b0c795b80212ae723640d4e5d48cabdff refs/remotes/origin/master - 25812380387fdd55f916652be4881c6f11600d6f refs/remotes/origin/testing - -You have two remote servers: one named `gitserver` with a `master` branch; and another named `origin` with two branches, `master` and `testing`. - -Notice how in the example of remote references imported from `git svn`, tags are added as remote branches, not as real Git tags. Your Subversion import looks like it has a remote named tags with branches under it. - -### Committing Back to Subversion ### - -Now that you have a working repository, you can do some work on the project and push your commits back upstream, using Git effectively as a SVN client. If you edit one of the files and commit it, you have a commit that exists in Git locally that doesn’t exist on the Subversion server: - - $ git commit -am 'Adding git-svn instructions to the README' - [master 97031e5] Adding git-svn instructions to the README - 1 files changed, 1 insertions(+), 1 deletions(-) - -Next, you need to push your change upstream. Notice how this changes the way you work with Subversion — you can do several commits offline and then push them all at once to the Subversion server. To push to a Subversion server, you run the `git svn dcommit` command: - - $ git svn dcommit - Committing to file:///tmp/test-svn/trunk ... - M README.txt - Committed r79 - M README.txt - r79 = 938b1a547c2cc92033b74d32030e86468294a5c8 (trunk) - No changes between current HEAD and refs/remotes/trunk - Resetting to the latest refs/remotes/trunk - -This takes all the commits you’ve made on top of the Subversion server code, does a Subversion commit for each, and then rewrites your local Git commit to include a unique identifier. This is important because it means that all the SHA-1 checksums for your commits change. Partly for this reason, working with Git-based remote versions of your projects concurrently with a Subversion server isn’t a good idea. If you look at the last commit, you can see the new `git-svn-id` that was added: - - $ git log -1 - commit 938b1a547c2cc92033b74d32030e86468294a5c8 - Author: schacon - Date: Sat May 2 22:06:44 2009 +0000 - - Adding git-svn instructions to the README - - git-svn-id: file:///tmp/test-svn/trunk@79 4c93b258-373f-11de-be05-5f7a86268029 - -Notice that the SHA checksum that originally started with `97031e5` when you committed now begins with `938b1a5`. If you want to push to both a Git server and a Subversion server, you have to push (`dcommit`) to the Subversion server first, because that action changes your commit data. - -### Pulling in New Changes ### - -If you’re working with other developers, then at some point one of you will push, and then the other one will try to push a change that conflicts. That change will be rejected until you merge in their work. In `git svn`, it looks like this: - - $ git svn dcommit - Committing to file:///tmp/test-svn/trunk ... - Merge conflict during commit: Your file or directory 'README.txt' is probably \ - out-of-date: resource out of date; try updating at /Users/schacon/libexec/git-\ - core/git-svn line 482 - -To resolve this situation, you can run `git svn rebase`, which pulls down any changes on the server that you don’t have yet and rebases any work you have on top of what is on the server: - - $ git svn rebase - M README.txt - r80 = ff829ab914e8775c7c025d741beb3d523ee30bc4 (trunk) - First, rewinding head to replay your work on top of it... - Applying: first user change - -Now, all your work is on top of what is on the Subversion server, so you can successfully `dcommit`: - - $ git svn dcommit - Committing to file:///tmp/test-svn/trunk ... - M README.txt - Committed r81 - M README.txt - r81 = 456cbe6337abe49154db70106d1836bc1332deed (trunk) - No changes between current HEAD and refs/remotes/trunk - Resetting to the latest refs/remotes/trunk - -It’s important to remember that unlike Git, which requires you to merge upstream work you don’t yet have locally before you can push, `git svn` makes you do that only if the changes conflict. If someone else pushes a change to one file and then you push a change to another file, your `dcommit` will work fine: - - $ git svn dcommit - Committing to file:///tmp/test-svn/trunk ... - M configure.ac - Committed r84 - M autogen.sh - r83 = 8aa54a74d452f82eee10076ab2584c1fc424853b (trunk) - M configure.ac - r84 = cdbac939211ccb18aa744e581e46563af5d962d0 (trunk) - W: d2f23b80f67aaaa1f6f5aaef48fce3263ac71a92 and refs/remotes/trunk differ, \ - using rebase: - :100755 100755 efa5a59965fbbb5b2b0a12890f1b351bb5493c18 \ - 015e4c98c482f0fa71e4d5434338014530b37fa6 M autogen.sh - First, rewinding head to replay your work on top of it... - Nothing to do. - -This is important to remember, because the outcome is a project state that didn’t exist on either of your computers when you pushed. If the changes are incompatible but don’t conflict, you may get issues that are difficult to diagnose. This is different than using a Git server — in Git, you can fully test the state on your client system before publishing it, whereas in SVN, you can’t ever be certain that the states immediately before commit and after commit are identical. - -You should also run this command to pull in changes from the Subversion server, even if you’re not ready to commit yourself. You can run `git svn fetch` to grab the new data, but `git svn rebase` does the fetch and then updates your local commits. - - $ git svn rebase - M generate_descriptor_proto.sh - r82 = bd16df9173e424c6f52c337ab6efa7f7643282f1 (trunk) - First, rewinding head to replay your work on top of it... - Fast-forwarded master to refs/remotes/trunk. - -Running `git svn rebase` every once in a while makes sure your code is always up to date. You need to be sure your working directory is clean when you run this, though. If you have local changes, you must either stash your work or temporarily commit it before running `git svn rebase` — otherwise, the command will stop if it sees that the rebase will result in a merge conflict. - -### Git Branching Issues ### - -When you’ve become comfortable with a Git workflow, you’ll likely create topic branches, do work on them, and then merge them in. If you’re pushing to a Subversion server via git svn, you may want to rebase your work onto a single branch each time instead of merging branches together. The reason to prefer rebasing is that Subversion has a linear history and doesn’t deal with merges like Git does, so git svn follows only the first parent when converting the snapshots into Subversion commits. - -Suppose your history looks like the following: you created an `experiment` branch, did two commits, and then merged them back into `master`. When you `dcommit`, you see output like this: - - $ git svn dcommit - Committing to file:///tmp/test-svn/trunk ... - M CHANGES.txt - Committed r85 - M CHANGES.txt - r85 = 4bfebeec434d156c36f2bcd18f4e3d97dc3269a2 (trunk) - No changes between current HEAD and refs/remotes/trunk - Resetting to the latest refs/remotes/trunk - COPYING.txt: locally modified - INSTALL.txt: locally modified - M COPYING.txt - M INSTALL.txt - Committed r86 - M INSTALL.txt - M COPYING.txt - r86 = 2647f6b86ccfcaad4ec58c520e369ec81f7c283c (trunk) - No changes between current HEAD and refs/remotes/trunk - Resetting to the latest refs/remotes/trunk - -Running `dcommit` on a branch with merged history works fine, except that when you look at your Git project history, it hasn’t rewritten either of the commits you made on the `experiment` branch — instead, all those changes appear in the SVN version of the single merge commit. - -When someone else clones that work, all they see is the merge commit with all the work squashed into it; they don’t see the commit data about where it came from or when it was committed. - -### Subversion Branching ### - -Branching in Subversion isn’t the same as branching in Git; if you can avoid using it much, that’s probably best. However, you can create and commit to branches in Subversion using git svn. - -#### Creating a New SVN Branch #### - -To create a new branch in Subversion, you run `git svn branch [branchname]`: - - $ git svn branch opera - Copying file:///tmp/test-svn/trunk at r87 to file:///tmp/test-svn/branches/opera... - Found possible branch point: file:///tmp/test-svn/trunk => \ - file:///tmp/test-svn/branches/opera, 87 - Found branch parent: (opera) 1f6bfe471083cbca06ac8d4176f7ad4de0d62e5f - Following parent with do_switch - Successfully followed parent - r89 = 9b6fe0b90c5c9adf9165f700897518dbc54a7cbf (opera) - -This does the equivalent of the `svn copy trunk branches/opera` command in Subversion and operates on the Subversion server. It’s important to note that it doesn’t check you out into that branch; if you commit at this point, that commit will go to `trunk` on the server, not `opera`. - -### Switching Active Branches ### - -Git figures out what branch your dcommits go to by looking for the tip of any of your Subversion branches in your history — you should have only one, and it should be the last one with a `git-svn-id` in your current branch history. - -If you want to work on more than one branch simultaneously, you can set up local branches to `dcommit` to specific Subversion branches by starting them at the imported Subversion commit for that branch. If you want an `opera` branch that you can work on separately, you can run - - $ git branch opera remotes/opera - -Now, if you want to merge your `opera` branch into `trunk` (your `master` branch), you can do so with a normal `git merge`. But you need to provide a descriptive commit message (via `-m`), or the merge will say "Merge branch opera" instead of something useful. - -Remember that although you’re using `git merge` to do this operation, and the merge likely will be much easier than it would be in Subversion (because Git will automatically detect the appropriate merge base for you), this isn’t a normal Git merge commit. You have to push this data back to a Subversion server that can’t handle a commit that tracks more than one parent; so, after you push it up, it will look like a single commit that squashed in all the work of another branch under a single commit. After you merge one branch into another, you can’t easily go back and continue working on that branch, as you normally can in Git. The `dcommit` command that you run erases any information that says what branch was merged in, so subsequent merge-base calculations will be wrong — the dcommit makes your `git merge` result look like you ran `git merge --squash`. Unfortunately, there’s no good way to avoid this situation — Subversion can’t store this information, so you’ll always be crippled by its limitations while you’re using it as your server. To avoid issues, you should delete the local branch (in this case, `opera`) after you merge it into trunk. - -### Subversion Commands ### - -The `git svn` toolset provides a number of commands to help ease the transition to Git by providing some functionality that’s similar to what you had in Subversion. Here are a few commands that give you what Subversion used to. - -#### SVN Style History #### - -If you’re used to Subversion and want to see your history in SVN output style, you can run `git svn log` to view your commit history in SVN formatting: - - $ git svn log - ------------------------------------------------------------------------ - r87 | schacon | 2009-05-02 16:07:37 -0700 (Sat, 02 May 2009) | 2 lines - - autogen change - - ------------------------------------------------------------------------ - r86 | schacon | 2009-05-02 16:00:21 -0700 (Sat, 02 May 2009) | 2 lines - - Merge branch 'experiment' - - ------------------------------------------------------------------------ - r85 | schacon | 2009-05-02 16:00:09 -0700 (Sat, 02 May 2009) | 2 lines - - updated the changelog - -You should know two important things about `git svn log`. First, it works offline, unlike the real `svn log` command, which asks the Subversion server for the data. Second, it only shows you commits that have been committed up to the Subversion server. Local Git commits that you haven’t dcommited don’t show up; neither do commits that people have made to the Subversion server in the meantime. It’s more like the last known state of the commits on the Subversion server. - -#### SVN Annotation #### - -Much as the `git svn log` command simulates the `svn log` command offline, you can get the equivalent of `svn annotate` by running `git svn blame [FILE]`. The output looks like this: - - $ git svn blame README.txt - 2 temporal Protocol Buffers - Google's data interchange format - 2 temporal Copyright 2008 Google Inc. - 2 temporal http://code.google.com/apis/protocolbuffers/ - 2 temporal - 22 temporal C++ Installation - Unix - 22 temporal ======================= - 2 temporal - 79 schacon Committing in git-svn. - 78 schacon - 2 temporal To build and install the C++ Protocol Buffer runtime and the Protocol - 2 temporal Buffer compiler (protoc) execute the following: - 2 temporal - -Again, it doesn’t show commits that you did locally in Git or that have been pushed to Subversion in the meantime. - -#### SVN Server Information #### - -You can also get the same sort of information that `svn info` gives you by running `git svn info`: - - $ git svn info - Path: . - URL: https://schacon-test.googlecode.com/svn/trunk - Repository Root: https://schacon-test.googlecode.com/svn - Repository UUID: 4c93b258-373f-11de-be05-5f7a86268029 - Revision: 87 - Node Kind: directory - Schedule: normal - Last Changed Author: schacon - Last Changed Rev: 87 - Last Changed Date: 2009-05-02 16:07:37 -0700 (Sat, 02 May 2009) - -This is like `blame` and `log` in that it runs offline and is up to date only as of the last time you communicated with the Subversion server. - -#### Ignoring What Subversion Ignores #### - -If you clone a Subversion repository that has `svn:ignore` properties set anywhere, you’ll likely want to set corresponding `.gitignore` files so you don’t accidentally commit files that you shouldn’t. `git svn` has two commands to help with this issue. The first is `git svn create-ignore`, which automatically creates corresponding `.gitignore` files for you so your next commit can include them. - -The second command is `git svn show-ignore`, which prints to stdout the lines you need to put in a `.gitignore` file so you can redirect the output into your project exclude file: - - $ git svn show-ignore > .git/info/exclude - -That way, you don’t litter the project with `.gitignore` files. This is a good option if you’re the only Git user on a Subversion team, and your teammates don’t want `.gitignore` files in the project. - -### Git-Svn Summary ### - -The `git svn` tools are useful if you’re stuck with a Subversion server for now or are otherwise in a development environment that necessitates running a Subversion server. You should consider it crippled Git, however, or you’ll hit issues in translation that may confuse you and your collaborators. To stay out of trouble, try to follow these guidelines: - -* Keep a linear Git history that doesn’t contain merge commits made by `git merge`. Rebase any work you do outside of your mainline branch back onto it; don’t merge it in. -* Don’t set up and collaborate on a separate Git server. Possibly have one to speed up clones for new developers, but don’t push anything to it that doesn’t have a `git-svn-id` entry. You may even want to add a `pre-receive` hook that checks each commit message for a `git-svn-id` and rejects pushes that contain commits without it. - -If you follow those guidelines, working with a Subversion server can be more bearable. However, if it’s possible to move to a real Git server, doing so can gain your team a lot more. - -## Migrating to Git ## - -If you have an existing codebase in another VCS but you’ve decided to start using Git, you must migrate your project one way or another. This section goes over some importers that are included with Git for common systems and then demonstrates how to develop your own custom importer. - -### Importing ### - -You’ll learn how to import data from two of the bigger professionally used SCM systems — Subversion and Perforce — both because they make up the majority of users I hear of who are currently switching, and because high-quality tools for both systems are distributed with Git. - -### Subversion ### - -If you read the previous section about using `git svn`, you can easily use those instructions to `git svn clone` a repository; then, stop using the Subversion server, push to a new Git server, and start using that. If you want the history, you can accomplish that as quickly as you can pull the data out of the Subversion server (which may take a while). - -However, the import isn’t perfect; and because it will take so long, you may as well do it right. The first problem is the author information. In Subversion, each person committing has a user on the system who is recorded in the commit information. The examples in the previous section show `schacon` in some places, such as the `blame` output and the `git svn log`. If you want to map this to better Git author data, you need a mapping from the Subversion users to the Git authors. Create a file called `users.txt` that has this mapping in a format like this: - - schacon = Scott Chacon - selse = Someo Nelse - -To get a list of the author names that SVN uses, you can run this: - - $ svn log --xml | grep author | sort -u | perl -pe 's/.>(.?)<./$1 = /' - -That gives you the log output in XML format — you can look for the authors, create a unique list, and then strip out the XML. (Obviously this only works on a machine with `grep`, `sort`, and `perl` installed.) Then, redirect that output into your users.txt file so you can add the equivalent Git user data next to each entry. - -You can provide this file to `git svn` to help it map the author data more accurately. You can also tell `git svn` not to include the metadata that Subversion normally imports, by passing `--no-metadata` to the `clone` or `init` command. This makes your `import` command look like this: - - $ git-svn clone http://my-project.googlecode.com/svn/ \ - --authors-file=users.txt --no-metadata -s my_project - -Now you should have a nicer Subversion import in your `my_project` directory. Instead of commits that look like this - - commit 37efa680e8473b615de980fa935944215428a35a - Author: schacon - Date: Sun May 3 00:12:22 2009 +0000 - - fixed install - go to trunk - - git-svn-id: https://my-project.googlecode.com/svn/trunk@94 4c93b258-373f-11de- - be05-5f7a86268029 -they look like this: - - commit 03a8785f44c8ea5cdb0e8834b7c8e6c469be2ff2 - Author: Scott Chacon - Date: Sun May 3 00:12:22 2009 +0000 - - fixed install - go to trunk - -Not only does the Author field look a lot better, but the `git-svn-id` is no longer there, either. - -You need to do a bit of `post-import` cleanup. For one thing, you should clean up the weird references that `git svn` set up. First you’ll move the tags so they’re actual tags rather than strange remote branches, and then you’ll move the rest of the branches so they’re local. - -To move the tags to be proper Git tags, run - - $ cp -Rf .git/refs/remotes/tags/* .git/refs/tags/ - $ rm -Rf .git/refs/remotes/tags - -This takes the references that were remote branches that started with `tag/` and makes them real (lightweight) tags. - -Next, move the rest of the references under `refs/remotes` to be local branches: - - $ cp -Rf .git/refs/remotes/* .git/refs/heads/ - $ rm -Rf .git/refs/remotes - -Now all the old branches are real Git branches and all the old tags are real Git tags. The last thing to do is add your new Git server as a remote and push to it. Because you want all your branches and tags to go up, you can run this: - - $ git push origin --all - -All your branches and tags should be on your new Git server in a nice, clean import. - -### Perforce ### - -The next system you’ll look at importing from is Perforce. A Perforce importer is also distributed with Git, but only in the `contrib` section of the source code — it isn’t available by default like `git svn`. To run it, you must get the Git source code, which you can download from git.kernel.org: - - $ git clone git://git.kernel.org/pub/scm/git/git.git - $ cd git/contrib/fast-import - -In this `fast-import` directory, you should find an executable Python script named `git-p4`. You must have Python and the `p4` tool installed on your machine for this import to work. For example, you’ll import the Jam project from the Perforce Public Depot. To set up your client, you must export the P4PORT environment variable to point to the Perforce depot: - - $ export P4PORT=public.perforce.com:1666 - -Run the `git-p4 clone` command to import the Jam project from the Perforce server, supplying the depot and project path and the path into which you want to import the project: - - $ git-p4 clone //public/jam/src@all /opt/p4import - Importing from //public/jam/src@all into /opt/p4import - Reinitialized existing Git repository in /opt/p4import/.git/ - Import destination: refs/remotes/p4/master - Importing revision 4409 (100%) - -If you go to the `/opt/p4import` directory and run `git log`, you can see your imported work: - - $ git log -2 - commit 1fd4ec126171790efd2db83548b85b1bbbc07dc2 - Author: Perforce staff - Date: Thu Aug 19 10:18:45 2004 -0800 - - Drop 'rc3' moniker of jam-2.5. Folded rc2 and rc3 RELNOTES into - the main part of the document. Built new tar/zip balls. - - Only 16 months later. - - [git-p4: depot-paths = "//public/jam/src/": change = 4409] - - commit ca8870db541a23ed867f38847eda65bf4363371d - Author: Richard Geiger - Date: Tue Apr 22 20:51:34 2003 -0800 - - Update derived jamgram.c - - [git-p4: depot-paths = "//public/jam/src/": change = 3108] - -You can see the `git-p4` identifier in each commit. It’s fine to keep that identifier there, in case you need to reference the Perforce change number later. However, if you’d like to remove the identifier, now is the time to do so — before you start doing work on the new repository. You can use `git filter-branch` to remove the identifier strings en masse: - - $ git filter-branch --msg-filter ' - sed -e "/^\[git-p4:/d" - ' - Rewrite 1fd4ec126171790efd2db83548b85b1bbbc07dc2 (123/123) - Ref 'refs/heads/master' was rewritten - -If you run `git log`, you can see that all the SHA-1 checksums for the commits have changed, but the `git-p4` strings are no longer in the commit messages: - - $ git log -2 - commit 10a16d60cffca14d454a15c6164378f4082bc5b0 - Author: Perforce staff - Date: Thu Aug 19 10:18:45 2004 -0800 - - Drop 'rc3' moniker of jam-2.5. Folded rc2 and rc3 RELNOTES into - the main part of the document. Built new tar/zip balls. - - Only 16 months later. - - commit 2b6c6db311dd76c34c66ec1c40a49405e6b527b2 - Author: Richard Geiger - Date: Tue Apr 22 20:51:34 2003 -0800 - - Update derived jamgram.c - -Your import is ready to push up to your new Git server. - -### A Custom Importer ### - -If your system isn’t Subversion or Perforce, you should look for an importer online — quality importers are available for CVS, Clear Case, Visual Source Safe, even a directory of archives. If none of these tools works for you, you have a rarer tool, or you otherwise need a more custom importing process, you should use `git fast-import`. This command reads simple instructions from stdin to write specific Git data. It’s much easier to create Git objects this way than to run the raw Git commands or try to write the raw objects (see Chapter 9 for more information). This way, you can write an import script that reads the necessary information out of the system you’re importing from and prints straightforward instructions to stdout. You can then run this program and pipe its output through `git fast-import`. - -To quickly demonstrate, you’ll write a simple importer. Suppose you work in current, you back up your project by occasionally copying the directory into a time-stamped `back_YYYY_MM_DD` backup directory, and you want to import this into Git. Your directory structure looks like this: - - $ ls /opt/import_from - back_2009_01_02 - back_2009_01_04 - back_2009_01_14 - back_2009_02_03 - current - -In order to import a Git directory, you need to review how Git stores its data. As you may remember, Git is fundamentally a linked list of commit objects that point to a snapshot of content. 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 you did in the "An Example Git Enforced Policy" section of Chapter 7, we’ll write this in Ruby, because it’s what I 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. - -To begin, you’ll change into the target directory and identify every subdirectory, each of which is a snapshot that you want to import as a commit. You’ll change into each subdirectory and print the commands necessary to export it. Your basic main loop looks like this: - - last_mark = nil - - # loop through the directories - Dir.chdir(ARGV[0]) do - Dir.glob("*").each do |dir| - next if File.file?(dir) - - # move into the target directory - Dir.chdir(dir) do - last_mark = print_export(dir, last_mark) - end - end - end - -You run `print_export` inside each directory, which takes the manifest and mark of the previous snapshot and returns the manifest and mark of this one; that way, you can link them properly. "Mark" is the `fast-import` term for an identifier you give to a commit; as you create commits, you give each one a mark that you can use to link to it from other commits. So, the first thing to do in your `print_export` method is generate a mark from the directory name: - - mark = convert_dir_to_mark(dir) - -You’ll do this by creating an array of directories and using the index value as the mark, because a mark must be an integer. Your method looks like this: - - $marks = [] - def convert_dir_to_mark(dir) - if !$marks.include?(dir) - $marks << dir - end - ($marks.index(dir) + 1).to_s - end - -Now that you have an integer representation of your commit, you need a date for the commit metadata. Because the date is expressed in the name of the directory, you’ll parse it out. The next line in your `print_export` file is - - date = convert_dir_to_date(dir) - -where `convert_dir_to_date` is defined as - - def convert_dir_to_date(dir) - if dir == 'current' - return Time.now().to_i - else - dir = dir.gsub('back_', '') - (year, month, day) = dir.split('_') - return Time.local(year, month, day).to_i - end - end - -That returns an integer value for the date of each directory. The last piece of meta-information you need for each commit is the committer data, which you hardcode in a global variable: - - $author = 'Scott Chacon ' - -Now you’re ready to begin printing out the commit data for your importer. The initial information states that you’re defining a commit object and what branch it’s on, followed by the mark you’ve generated, the committer information and commit message, and then the previous commit, if any. The code looks like this: - - # print the import information - puts 'commit refs/heads/master' - puts 'mark :' + mark - puts "committer #{$author} #{date} -0700" - export_data('imported from ' + dir) - puts 'from :' + last_mark if last_mark - -You hardcode the time zone (-0700) because doing so is easy. If you’re importing from another system, you must specify the time zone as an offset. -The commit message must be expressed in a special format: - - data (size)\n(contents) - -The format consists of the word data, the size of the data to be read, a newline, and finally the data. Because you need to use the same format to specify the file contents later, you create a helper method, `export_data`: - - def export_data(string) - print "data #{string.size}\n#{string}" - end - -All that’s left is to specify the file contents for each snapshot. This is easy, because you have each one in a directory — you can print out the `deleteall` command followed by the contents of each file in the directory. Git will then record each snapshot appropriately: - - puts 'deleteall' - Dir.glob("**/*").each do |file| - next if !File.file?(file) - inline_data(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. 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. - -The format for listing the new file contents or specifying a modified file with the new contents is as follows: - - M 644 inline path/to/file - data (size) - (file contents) - -Here, 644 is the mode (if you have executable files, you need to detect and specify 755 instead), and inline says you’ll list the contents immediately after this line. Your `inline_data` method looks like this: - - def inline_data(file, code = 'M', mode = '644') - content = File.read(file) - puts "#{code} #{mode} inline #{file}" - export_data(content) - end - -You reuse the `export_data` method you defined earlier, because it’s the same as the way you specified your commit message data. - -The last thing you need to do is to return the current mark so it can be passed to the next iteration: - - return mark - -NOTE: If you are running on Windows you'll need to make sure that you add one extra step. As metioned before, Windows uses CRLF for new line characters while git fast-import expects only LF. To get around this problem and make git fast-import happy, you need to tell ruby to use LF instead of CRLF: - - $stdout.binmode - -That’s it. If you run this script, you’ll get content that looks something like this: - - $ ruby import.rb /opt/import_from - commit refs/heads/master - mark :1 - committer Scott Chacon 1230883200 -0700 - data 29 - imported from back_2009_01_02deleteall - M 644 inline file.rb - data 12 - version two - commit refs/heads/master - mark :2 - committer Scott Chacon 1231056000 -0700 - data 29 - imported from back_2009_01_04from :1 - deleteall - M 644 inline file.rb - data 14 - version three - M 644 inline new.rb - data 16 - new version one - (...) - -To run the importer, pipe this output through `git fast-import` while in the Git directory you want to import into. You can create a new directory and then run `git init` in it for a starting point, and then run your script: - - $ git init - Initialized empty Git repository in /opt/import_to/.git/ - $ ruby import.rb /opt/import_from | git fast-import - git-fast-import statistics: - --------------------------------------------------------------------- - Alloc'd objects: 5000 - Total objects: 18 ( 1 duplicates ) - blobs : 7 ( 1 duplicates 0 deltas) - trees : 6 ( 0 duplicates 1 deltas) - commits: 5 ( 0 duplicates 0 deltas) - tags : 0 ( 0 duplicates 0 deltas) - Total branches: 1 ( 1 loads ) - marks: 1024 ( 5 unique ) - atoms: 3 - Memory total: 2255 KiB - pools: 2098 KiB - objects: 156 KiB - --------------------------------------------------------------------- - pack_report: getpagesize() = 4096 - pack_report: core.packedGitWindowSize = 33554432 - pack_report: core.packedGitLimit = 268435456 - pack_report: pack_used_ctr = 9 - pack_report: pack_mmap_calls = 5 - pack_report: pack_open_windows = 1 / 1 - pack_report: pack_mapped = 1356 / 1356 - --------------------------------------------------------------------- - -As you can see, when it completes successfully, it gives you a bunch of statistics about what it accomplished. In this case, you imported 18 objects total for 5 commits into 1 branch. Now, you can run `git log` to see your new history: - - $ git log -2 - commit 10bfe7d22ce15ee25b60a824c8982157ca593d41 - Author: Scott Chacon - Date: Sun May 3 12:57:39 2009 -0700 - - imported from current - - commit 7e519590de754d079dd73b44d695a42c9d2df452 - Author: Scott Chacon - Date: Tue Feb 3 01:00:00 2009 -0700 - - imported from back_2009_02_03 - -There you go — a nice, clean Git repository. It’s important to note that nothing is checked out — you don’t have any files in your working directory at first. To get them, you must reset your branch to where `master` is now: - - $ ls - $ git reset --hard master - HEAD is now at 10bfe7d imported from current - $ ls - file.rb lib - -You can do a lot more with the `fast-import` tool — handle different modes, binary data, multiple branches and merging, tags, progress indicators, and more. A number of examples of more complex scenarios are available in the `contrib/fast-import` directory of the Git source code; one of the better ones is the `git-p4` script I just covered. - -## Summary ## - -You should feel comfortable using Git with Subversion or importing nearly any existing repository into a new Git one without losing data. The next chapter will cover the raw internals of Git so you can craft every single byte, if need be. diff --git a/ar/09-git-internals/01-chapter9.markdown b/ar/09-git-internals/01-chapter9.markdown deleted file mode 100644 index 917e1c170..000000000 --- a/ar/09-git-internals/01-chapter9.markdown +++ /dev/null @@ -1,977 +0,0 @@ -# Git Internals # - -You may have skipped to this chapter from a previous chapter, or you may have gotten here after reading the rest of the book — in either case, this is where you’ll go over the inner workings and implementation of Git. I found that learning this information was fundamentally important to understanding how useful and powerful Git is, but others have argued to me that it can be confusing and unnecessarily complex for beginners. Thus, I’ve made this discussion the last chapter in the book so you could read it early or later in your learning process. I leave it up to you to decide. - -Now that you’re here, let’s get started. First, if it isn’t yet clear, Git is fundamentally a content-addressable filesystem with a VCS user interface written on top of it. You’ll learn more about what this means in a bit. - -In the early days of Git (mostly pre 1.5), the user interface was much more complex because it emphasized this filesystem rather than a polished VCS. In the last few years, the UI has been refined until it’s as clean and easy to use as any system out there; but often, the stereotype lingers about the early Git UI that was complex and difficult to learn. - -The content-addressable filesystem layer is amazingly cool, so I’ll cover that first in this chapter; then, you’ll learn about the transport mechanisms and the repository maintenance tasks that you may eventually have to deal with. - -## Plumbing and Porcelain ## - -This book covers how to use Git with 30 or so verbs such as `checkout`, `branch`, `remote`, and so on. But because Git was initially a toolkit for a VCS rather than a full user-friendly VCS, it has a bunch of verbs that do low-level work and were designed to be chained together UNIX style or called from scripts. These commands are generally referred to as "plumbing" commands, and the more user-friendly commands are called "porcelain" commands. - -The book’s first eight chapters deal almost exclusively with porcelain commands. But in this chapter, you’ll be dealing mostly with the lower-level plumbing commands, because they give you access to the inner workings of Git and help demonstrate how and why Git does what it does. These commands aren’t meant to be used manually on the command line, but rather to be used as building blocks for new tools and custom scripts. - -When you run `git init` in a new or existing directory, Git creates the `.git` directory, which is where almost everything that Git stores and manipulates is located. If you want to back up or clone your repository, copying this single directory elsewhere gives you nearly everything you need. This entire chapter basically deals with the stuff in this directory. Here’s what it looks like: - - $ ls - HEAD - branches/ - config - description - hooks/ - index - info/ - objects/ - refs/ - -You may see some other files in there, but this is a fresh `git init` repository — it’s what you see by default. The `branches` directory isn’t used by newer Git versions, and the `description` file is only used by the GitWeb program, so don’t worry about those. The `config` file contains your project-specific configuration options, and the `info` directory keeps a global exclude file for ignored patterns that you don’t want to track in a .gitignore file. The `hooks` directory contains your client- or server-side hook scripts, which are discussed in detail in Chapter 6. - -This leaves four important entries: the `HEAD` and `index` files and the `objects` and `refs` directories. These are the core parts of Git. The `objects` directory stores all the content for your database, the `refs` directory stores pointers into commit objects in that data (branches), the `HEAD` file points to the branch you currently have checked out, and the `index` file is where Git stores your staging area information. You’ll now look at each of these sections in detail to see how Git operates. - -## Git Objects ## - -Git is a content-addressable filesystem. Great. What does that mean? -It means that at the core of Git is a simple key-value data store. You can insert any kind of content into it, and it will give you back a key that you can use to retrieve the content again at any time. To demonstrate, you can use the plumbing command `hash-object`, which takes some data, stores it in your `.git` directory, and gives you back the key the data is stored as. First, you initialize a new Git repository and verify that there is nothing in the `objects` directory: - - $ mkdir test - $ cd test - $ git init - Initialized empty Git repository in /tmp/test/.git/ - $ find .git/objects - .git/objects - .git/objects/info - .git/objects/pack - $ find .git/objects -type f - $ - -Git has initialized the `objects` directory and created `pack` and `info` subdirectories in it, but there are no regular files. Now, store some text in your Git database: - - $ echo 'test content' | git hash-object -w --stdin - d670460b4b4aece5915caf5c68d12f560a9fe3e4 - -The `-w` tells `hash-object` to store the object; otherwise, the command simply tells you what the key would be. `--stdin` tells the command to read the content from stdin; if you don’t specify this, `hash-object` expects the path to a file. The output from the command is a 40-character checksum hash. This is the SHA-1 hash — a checksum of the content you’re storing plus a header, which you’ll learn about in a bit. Now you can see how Git has stored your data: - - $ find .git/objects -type f - .git/objects/d6/70460b4b4aece5915caf5c68d12f560a9fe3e4 - -You can see a file in the `objects` directory. This is how Git stores the content initially — as a single file per piece of content, named with the SHA-1 checksum of the content and its header. The subdirectory is named with the first 2 characters of the SHA, and the filename is the remaining 38 characters. - -You can pull the content back out of Git with the `cat-file` command. This command is sort of a Swiss army knife for inspecting Git objects. Passing `-p` to it instructs the `cat-file` command to figure out the type of content and display it nicely for you: - - $ git cat-file -p d670460b4b4aece5915caf5c68d12f560a9fe3e4 - test content - -Now, you can add content to Git and pull it back out again. You can also do this with content in files. For example, you can do some simple version control on a file. First, create a new file and save its contents in your database: - - $ echo 'version 1' > test.txt - $ git hash-object -w test.txt - 83baae61804e65cc73a7201a7252750c76066a30 - -Then, write some new content to the file, and save it again: - - $ echo 'version 2' > test.txt - $ git hash-object -w test.txt - 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a - -Your database contains the two new versions of the file as well as the first content you stored there: - - $ find .git/objects -type f - .git/objects/1f/7a7a472abf3dd9643fd615f6da379c4acb3e3a - .git/objects/83/baae61804e65cc73a7201a7252750c76066a30 - .git/objects/d6/70460b4b4aece5915caf5c68d12f560a9fe3e4 - -Now you can revert the file back to the first version - - $ git cat-file -p 83baae61804e65cc73a7201a7252750c76066a30 > test.txt - $ cat test.txt - version 1 - -or the second version: - - $ git cat-file -p 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a > test.txt - $ cat test.txt - version 2 - -But remembering the SHA-1 key for each version of your file isn’t practical; plus, you aren’t storing the filename in your system — just the content. This object type is called a blob. You can have Git tell you the object type of any object in Git, given its SHA-1 key, with `cat-file -t`: - - $ git cat-file -t 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a - blob - -### Tree Objects ### - -The next type you’ll look at is the tree object, which solves the problem of storing the filename and also allows you to store a group of files together. Git stores content in a manner similar to a UNIX filesystem, but a bit simplified. All the content is stored as tree and blob objects, with trees corresponding to UNIX directory entries and blobs corresponding more or less to inodes or file contents. A single tree object contains one or more tree entries, each of which contains a SHA-1 pointer to a blob or subtree with its associated mode, type, and filename. For example, the most recent tree in the simplegit project may look something like this: - - $ git cat-file -p master^{tree} - 100644 blob a906cb2a4a904a152e80877d4088654daad0c859 README - 100644 blob 8f94139338f9404f26296befa88755fc2598c289 Rakefile - 040000 tree 99f1a6d12cb4b6f19c8655fca46c3ecf317074e0 lib - -The `master^{tree}` syntax specifies the tree object that is pointed to by the last commit on your `master` branch. Notice that the `lib` subdirectory isn’t a blob but a pointer to another tree: - - $ git cat-file -p 99f1a6d12cb4b6f19c8655fca46c3ecf317074e0 - 100644 blob 47c6340d6459e05787f644c2447d2595f5d3a54b simplegit.rb - -Conceptually, the data that Git is storing is something like Figure 9-1. - -Insert 18333fig0901.png -Figure 9-1. Simple version of the Git data model. - -You can create your own tree. Git normally creates a tree by taking the state of your staging area or index and writing a tree object from it. So, to create a tree object, you first have to set up an index by staging some files. To create an index with a single entry — the first version of your text.txt file — you can use the plumbing command `update-index`. You use this command to artificially add the earlier version of the test.txt file to a new staging area. You must pass it the `--add` option because the file doesn’t yet exist in your staging area (you don’t even have a staging area set up yet) and `--cacheinfo` because the file you’re adding isn’t in your directory but is in your database. Then, you specify the mode, SHA-1, and filename: - - $ git update-index --add --cacheinfo 100644 \ - 83baae61804e65cc73a7201a7252750c76066a30 test.txt - -In this case, you’re specifying a mode of `100644`, which means it’s a normal file. Other options are `100755`, which means it’s an executable file; and `120000`, which specifies a symbolic link. The mode is taken from normal UNIX modes but is much less flexible — these three modes are the only ones that are valid for files (blobs) in Git (although other modes are used for directories and submodules). - -Now, you can use the `write-tree` command to write the staging area out to a tree object. No `-w` option is needed — calling `write-tree` automatically creates a tree object from the state of the index if that tree doesn’t yet exist: - - $ git write-tree - d8329fc1cc938780ffdd9f94e0d364e0ea74f579 - $ git cat-file -p d8329fc1cc938780ffdd9f94e0d364e0ea74f579 - 100644 blob 83baae61804e65cc73a7201a7252750c76066a30 test.txt - -You can also verify that this is a tree object: - - $ git cat-file -t d8329fc1cc938780ffdd9f94e0d364e0ea74f579 - tree - -You’ll now create a new tree with the second version of test.txt and a new file as well: - - $ echo 'new file' > new.txt - $ git update-index test.txt - $ git update-index --add new.txt - -Your staging area now has the new version of test.txt as well as the new file new.txt. Write out that tree (recording the state of the staging area or index to a tree object) and see what it looks like: - - $ git write-tree - 0155eb4229851634a0f03eb265b69f5a2d56f341 - $ git cat-file -p 0155eb4229851634a0f03eb265b69f5a2d56f341 - 100644 blob fa49b077972391ad58037050f2a75f74e3671e92 new.txt - 100644 blob 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a test.txt - -Notice that this tree has both file entries and also that the test.txt SHA is the "version 2" SHA from earlier (`1f7a7a`). Just for fun, you’ll add the first tree as a subdirectory into this one. You can read trees into your staging area by calling `read-tree`. In this case, you can read an existing tree into your staging area as a subtree by using the `--prefix` option to `read-tree`: - - $ git read-tree --prefix=bak d8329fc1cc938780ffdd9f94e0d364e0ea74f579 - $ git write-tree - 3c4e9cd789d88d8d89c1073707c3585e41b0e614 - $ git cat-file -p 3c4e9cd789d88d8d89c1073707c3585e41b0e614 - 040000 tree d8329fc1cc938780ffdd9f94e0d364e0ea74f579 bak - 100644 blob fa49b077972391ad58037050f2a75f74e3671e92 new.txt - 100644 blob 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a test.txt - -If you created a working directory from the new tree you just wrote, you would get the two files in the top level of the working directory and a subdirectory named `bak` that contained the first version of the test.txt file. You can think of the data that Git contains for these structures as being like Figure 9-2. - -Insert 18333fig0902.png -Figure 9-2. The content structure of your current Git data. - -### Commit Objects ### - -You have three trees that specify the different snapshots of your project that you want to track, but the earlier problem remains: you must remember all three SHA-1 values in order to recall the snapshots. You also don’t have any information about who saved the snapshots, when they were saved, or why they were saved. This is the basic information that the commit object stores for you. - -To create a commit object, you call `commit-tree` and specify a single tree SHA-1 and which commit objects, if any, directly preceded it. Start with the first tree you wrote: - - $ echo 'first commit' | git commit-tree d8329f - fdf4fc3344e67ab068f836878b6c4951e3b15f3d - -Now you can look at your new commit object with `cat-file`: - - $ git cat-file -p fdf4fc3 - tree d8329fc1cc938780ffdd9f94e0d364e0ea74f579 - author Scott Chacon 1243040974 -0700 - committer Scott Chacon 1243040974 -0700 - - first commit - -The format for a commit object is simple: it specifies the top-level tree for the snapshot of the project at that point; the author/committer information pulled from your `user.name` and `user.email` configuration settings, with the current timestamp; a blank line, and then the commit message. - -Next, you’ll write the other two commit objects, each referencing the commit that came directly before it: - - $ echo 'second commit' | git commit-tree 0155eb -p fdf4fc3 - cac0cab538b970a37ea1e769cbbde608743bc96d - $ echo 'third commit' | git commit-tree 3c4e9c -p cac0cab - 1a410efbd13591db07496601ebc7a059dd55cfe9 - -Each of the three commit objects points to one of the three snapshot trees you created. Oddly enough, you have a real Git history now that you can view with the `git log` command, if you run it on the last commit SHA-1: - - $ git log --stat 1a410e - commit 1a410efbd13591db07496601ebc7a059dd55cfe9 - Author: Scott Chacon - Date: Fri May 22 18:15:24 2009 -0700 - - third commit - - bak/test.txt | 1 + - 1 files changed, 1 insertions(+), 0 deletions(-) - - commit cac0cab538b970a37ea1e769cbbde608743bc96d - Author: Scott Chacon - Date: Fri May 22 18:14:29 2009 -0700 - - second commit - - new.txt | 1 + - test.txt | 2 +- - 2 files changed, 2 insertions(+), 1 deletions(-) - - commit fdf4fc3344e67ab068f836878b6c4951e3b15f3d - Author: Scott Chacon - Date: Fri May 22 18:09:34 2009 -0700 - - first commit - - test.txt | 1 + - 1 files changed, 1 insertions(+), 0 deletions(-) - -Amazing. You’ve just done the low-level operations to build up a Git history without using any of the front ends. This is essentially what Git does when you run the `git add` and `git commit` commands — it stores blobs for the files that have changed, updates the index, writes out trees, and writes commit objects that reference the top-level trees and the commits that came immediately before them. These three main Git objects — the blob, the tree, and the commit — are initially stored as separate files in your `.git/objects` directory. Here are all the objects in the example directory now, commented with what they store: - - $ find .git/objects -type f - .git/objects/01/55eb4229851634a0f03eb265b69f5a2d56f341 # tree 2 - .git/objects/1a/410efbd13591db07496601ebc7a059dd55cfe9 # commit 3 - .git/objects/1f/7a7a472abf3dd9643fd615f6da379c4acb3e3a # test.txt v2 - .git/objects/3c/4e9cd789d88d8d89c1073707c3585e41b0e614 # tree 3 - .git/objects/83/baae61804e65cc73a7201a7252750c76066a30 # test.txt v1 - .git/objects/ca/c0cab538b970a37ea1e769cbbde608743bc96d # commit 2 - .git/objects/d6/70460b4b4aece5915caf5c68d12f560a9fe3e4 # 'test content' - .git/objects/d8/329fc1cc938780ffdd9f94e0d364e0ea74f579 # tree 1 - .git/objects/fa/49b077972391ad58037050f2a75f74e3671e92 # new.txt - .git/objects/fd/f4fc3344e67ab068f836878b6c4951e3b15f3d # commit 1 - -If you follow all the internal pointers, you get an object graph something like Figure 9-3. - -Insert 18333fig0903.png -Figure 9-3. All the objects in your Git directory. - -### Object Storage ### - -I mentioned earlier that a header is stored with the content. Let’s take a minute to look at how Git stores its objects. You’ll see how to store a blob object — in this case, the string "what is up, doc?" — interactively in the Ruby scripting language. You can start up interactive Ruby mode with the `irb` command: - - $ irb - >> content = "what is up, doc?" - => "what is up, doc?" - -Git constructs a header that starts with the type of the object, in this case a blob. Then, it adds a space followed by the size of the content and finally a null byte: - - >> header = "blob #{content.length}\0" - => "blob 16\000" - -Git concatenates the header and the original content and then calculates the SHA-1 checksum of that new content. You can calculate the SHA-1 value of a string in Ruby by including the SHA1 digest library with the `require` command and then calling `Digest::SHA1.hexdigest()` with the string: - - >> store = header + content - => "blob 16\000what is up, doc?" - >> require 'digest/sha1' - => true - >> sha1 = Digest::SHA1.hexdigest(store) - => "bd9dbf5aae1a3862dd1526723246b20206e5fc37" - -Git compresses the new content with zlib, which you can do in Ruby with the zlib library. First, you need to require the library and then run `Zlib::Deflate.deflate()` on the content: - - >> require 'zlib' - => true - >> zlib_content = Zlib::Deflate.deflate(store) - => "x\234K\312\311OR04c(\317H,Q\310,V(-\320QH\311O\266\a\000_\034\a\235" - -Finally, you’ll write your zlib-deflated content to an object on disk. You’ll determine the path of the object you want to write out (the first two characters of the SHA-1 value being the subdirectory name, and the last 38 characters being the filename within that directory). In Ruby, you can use the `FileUtils.mkdir_p()` function to create the subdirectory if it doesn’t exist. Then, open the file with `File.open()` and write out the previously zlib-compressed content to the file with a `write()` call on the resulting file handle: - - >> path = '.git/objects/' + sha1[0,2] + '/' + sha1[2,38] - => ".git/objects/bd/9dbf5aae1a3862dd1526723246b20206e5fc37" - >> require 'fileutils' - => true - >> FileUtils.mkdir_p(File.dirname(path)) - => ".git/objects/bd" - >> File.open(path, 'w') { |f| f.write zlib_content } - => 32 - -That’s it — you’ve created a valid Git blob object. All Git objects are stored the same way, just with different types — instead of the string blob, the header will begin with commit or tree. Also, although the blob content can be nearly anything, the commit and tree content are very specifically formatted. - -## Git References ## - -You can run something like `git log 1a410e` to look through your whole history, but you still have to remember that `1a410e` is the last commit in order to walk that history to find all those objects. You need a file in which you can store the SHA-1 value under a simple name so you can use that pointer rather than the raw SHA-1 value. - -In Git, these are called "references" or "refs"; you can find the files that contain the SHA-1 values in the `.git/refs` directory. In the current project, this directory contains no files, but it does contain a simple structure: - - $ find .git/refs - .git/refs - .git/refs/heads - .git/refs/tags - $ find .git/refs -type f - $ - -To create a new reference that will help you remember where your latest commit is, you can technically do something as simple as this: - - $ echo "1a410efbd13591db07496601ebc7a059dd55cfe9" > .git/refs/heads/master - -Now, you can use the head reference you just created instead of the SHA-1 value in your Git commands: - - $ git log --pretty=oneline master - 1a410efbd13591db07496601ebc7a059dd55cfe9 third commit - cac0cab538b970a37ea1e769cbbde608743bc96d second commit - fdf4fc3344e67ab068f836878b6c4951e3b15f3d first commit - -You aren’t encouraged to directly edit the reference files. Git provides a safer command to do this if you want to update a reference called `update-ref`: - - $ git update-ref refs/heads/master 1a410efbd13591db07496601ebc7a059dd55cfe9 - -That’s basically what a branch in Git is: a simple pointer or reference to the head of a line of work. To create a branch back at the second commit, you can do this: - - $ git update-ref refs/heads/test cac0ca - -Your branch will contain only work from that commit down: - - $ git log --pretty=oneline test - cac0cab538b970a37ea1e769cbbde608743bc96d second commit - fdf4fc3344e67ab068f836878b6c4951e3b15f3d first commit - -Now, your Git database conceptually looks something like Figure 9-4. - -Insert 18333fig0904.png -Figure 9-4. Git directory objects with branch head references included. - -When you run commands like `git branch (branchname)`, Git basically runs that `update-ref` command to add the SHA-1 of the last commit of the branch you’re on into whatever new reference you want to create. - -### The HEAD ### - -The question now is, when you run `git branch (branchname)`, how does Git know the SHA-1 of the last commit? The answer is the HEAD file. The HEAD file is a symbolic reference to the branch you’re currently on. By symbolic reference, I mean that unlike a normal reference, it doesn’t generally contain a SHA-1 value but rather a pointer to another reference. If you look at the file, you’ll normally see something like this: - - $ cat .git/HEAD - ref: refs/heads/master - -If you run `git checkout test`, Git updates the file to look like this: - - $ cat .git/HEAD - ref: refs/heads/test - -When you run `git commit`, it creates the commit object, specifying the parent of that commit object to be whatever SHA-1 value the reference in HEAD points to. - -You can also manually edit this file, but again a safer command exists to do so: `symbolic-ref`. You can read the value of your HEAD via this command: - - $ git symbolic-ref HEAD - refs/heads/master - -You can also set the value of HEAD: - - $ git symbolic-ref HEAD refs/heads/test - $ cat .git/HEAD - ref: refs/heads/test - -You can’t set a symbolic reference outside of the refs style: - - $ git symbolic-ref HEAD test - fatal: Refusing to point HEAD outside of refs/ - -### Tags ### - -You’ve just gone over Git’s three main object types, but there is a fourth. The tag object is very much like a commit object — it contains a tagger, a date, a message, and a pointer. The main difference is that a tag object points to a commit rather than a tree. It’s like a branch reference, but it never moves — it always points to the same commit but gives it a friendlier name. - -As discussed in Chapter 2, there are two types of tags: annotated and lightweight. You can make a lightweight tag by running something like this: - - $ git update-ref refs/tags/v1.0 cac0cab538b970a37ea1e769cbbde608743bc96d - -That is all a lightweight tag is — a branch that never moves. An annotated tag is more complex, however. If you create an annotated tag, Git creates a tag object and then writes a reference to point to it rather than directly to the commit. You can see this by creating an annotated tag (`-a` specifies that it’s an annotated tag): - - $ git tag -a v1.1 1a410efbd13591db07496601ebc7a059dd55cfe9 –m 'test tag' - -Here’s the object SHA-1 value it created: - - $ cat .git/refs/tags/v1.1 - 9585191f37f7b0fb9444f35a9bf50de191beadc2 - -Now, run the `cat-file` command on that SHA-1 value: - - $ git cat-file -p 9585191f37f7b0fb9444f35a9bf50de191beadc2 - object 1a410efbd13591db07496601ebc7a059dd55cfe9 - type commit - tag v1.1 - tagger Scott Chacon Sat May 23 16:48:58 2009 -0700 - - test tag - -Notice that the object entry points to the commit SHA-1 value that you tagged. Also notice that it doesn’t need to point to a commit; you can tag any Git object. In the Git source code, for example, the maintainer has added their GPG public key as a blob object and then tagged it. You can view the public key by running - - $ git cat-file blob junio-gpg-pub - -in the Git source code. The Linux kernel also has a non-commit-pointing tag object — the first tag created points to the initial tree of the import of the source code. - -### Remotes ### - -The third type of reference that you’ll see is a remote reference. If you add a remote and push to it, Git stores the value you last pushed to that remote for each branch in the `refs/remotes` directory. For instance, you can add a remote called `origin` and push your `master` branch to it: - - $ git remote add origin git@github.com:schacon/simplegit-progit.git - $ git push origin master - Counting objects: 11, done. - Compressing objects: 100% (5/5), done. - Writing objects: 100% (7/7), 716 bytes, done. - Total 7 (delta 2), reused 4 (delta 1) - To git@github.com:schacon/simplegit-progit.git - a11bef0..ca82a6d master -> master - -Then, you can see what the `master` branch on the `origin` remote was the last time you communicated with the server, by checking the `refs/remotes/origin/master` file: - - $ cat .git/refs/remotes/origin/master - ca82a6dff817ec66f44342007202690a93763949 - -Remote references differ from branches (`refs/heads` references) mainly in that they can’t be checked out. Git moves them around as bookmarks to the last known state of where those branches were on those servers. - -## Packfiles ## - -Let’s go back to the objects database for your test Git repository. At this point, you have 11 objects — 4 blobs, 3 trees, 3 commits, and 1 tag: - - $ find .git/objects -type f - .git/objects/01/55eb4229851634a0f03eb265b69f5a2d56f341 # tree 2 - .git/objects/1a/410efbd13591db07496601ebc7a059dd55cfe9 # commit 3 - .git/objects/1f/7a7a472abf3dd9643fd615f6da379c4acb3e3a # test.txt v2 - .git/objects/3c/4e9cd789d88d8d89c1073707c3585e41b0e614 # tree 3 - .git/objects/83/baae61804e65cc73a7201a7252750c76066a30 # test.txt v1 - .git/objects/95/85191f37f7b0fb9444f35a9bf50de191beadc2 # tag - .git/objects/ca/c0cab538b970a37ea1e769cbbde608743bc96d # commit 2 - .git/objects/d6/70460b4b4aece5915caf5c68d12f560a9fe3e4 # 'test content' - .git/objects/d8/329fc1cc938780ffdd9f94e0d364e0ea74f579 # tree 1 - .git/objects/fa/49b077972391ad58037050f2a75f74e3671e92 # new.txt - .git/objects/fd/f4fc3344e67ab068f836878b6c4951e3b15f3d # commit 1 - -Git compresses the contents of these files with zlib, and you’re not storing much, so all these files collectively take up only 925 bytes. You’ll add some larger content to the repository to demonstrate an interesting feature of Git. Add the repo.rb file from the Grit library you worked with earlier — this is about a 12K source code file: - - $ curl http://github.com/mojombo/grit/raw/master/lib/grit/repo.rb > repo.rb - $ git add repo.rb - $ git commit -m 'added repo.rb' - [master 484a592] added repo.rb - 3 files changed, 459 insertions(+), 2 deletions(-) - delete mode 100644 bak/test.txt - create mode 100644 repo.rb - rewrite test.txt (100%) - -If you look at the resulting tree, you can see the SHA-1 value your repo.rb file got for the blob object: - - $ git cat-file -p master^{tree} - 100644 blob fa49b077972391ad58037050f2a75f74e3671e92 new.txt - 100644 blob 9bc1dc421dcd51b4ac296e3e5b6e2a99cf44391e repo.rb - 100644 blob e3f094f522629ae358806b17daf78246c27c007b test.txt - -You can then use `git cat-file` to see how big that object is: - - $ git cat-file -s 9bc1dc421dcd51b4ac296e3e5b6e2a99cf44391e - 12898 - -Now, modify that file a little, and see what happens: - - $ echo '# testing' >> repo.rb - $ git commit -am 'modified repo a bit' - [master ab1afef] modified repo a bit - 1 files changed, 1 insertions(+), 0 deletions(-) - -Check the tree created by that commit, and you see something interesting: - - $ git cat-file -p master^{tree} - 100644 blob fa49b077972391ad58037050f2a75f74e3671e92 new.txt - 100644 blob 05408d195263d853f09dca71d55116663690c27c repo.rb - 100644 blob e3f094f522629ae358806b17daf78246c27c007b test.txt - -The blob is now a different blob, which means that although you added only a single line to the end of a 400-line file, Git stored that new content as a completely new object: - - $ git cat-file -s 05408d195263d853f09dca71d55116663690c27c - 12908 - -You have two nearly identical 12K objects on your disk. Wouldn’t it be nice if Git could store one of them in full but then the second object only as the delta between it and the first? - -It turns out that it can. The initial format in which Git saves objects on disk is called a loose object format. However, occasionally Git packs up several of these objects into a single binary file called a packfile in order to save space and be more efficient. Git does this if you have too many loose objects around, if you run the `git gc` command manually, or if you push to a remote server. To see what happens, you can manually ask Git to pack up the objects by calling the `git gc` command: - - $ git gc - Counting objects: 17, done. - Delta compression using 2 threads. - Compressing objects: 100% (13/13), done. - Writing objects: 100% (17/17), done. - Total 17 (delta 1), reused 10 (delta 0) - -If you look in your objects directory, you’ll find that most of your objects are gone, and a new pair of files has appeared: - - $ find .git/objects -type f - .git/objects/71/08f7ecb345ee9d0084193f147cdad4d2998293 - .git/objects/d6/70460b4b4aece5915caf5c68d12f560a9fe3e4 - .git/objects/info/packs - .git/objects/pack/pack-7a16e4488ae40c7d2bc56ea2bd43e25212a66c45.idx - .git/objects/pack/pack-7a16e4488ae40c7d2bc56ea2bd43e25212a66c45.pack - -The objects that remain are the blobs that aren’t pointed to by any commit — in this case, the "what is up, doc?" example and the "test content" example blobs you created earlier. Because you never added them to any commits, they’re considered dangling and aren’t packed up in your new packfile. - -The other files are your new packfile and an index. The packfile is a single file containing the contents of all the objects that were removed from your filesystem. The index is a file that contains offsets into that packfile so you can quickly seek to a specific object. What is cool is that although the objects on disk before you ran the `gc` were collectively about 12K in size, the new packfile is only 6K. You’ve halved your disk usage by packing your objects. - -How does Git do this? When Git packs objects, it looks for files that are named and sized similarly, and stores just the deltas from one version of the file to the next. You can look into the packfile and see what Git did to save space. The `git verify-pack` plumbing command allows you to see what was packed up: - - $ git verify-pack -v \ - .git/objects/pack/pack-7a16e4488ae40c7d2bc56ea2bd43e25212a66c45.idx - 0155eb4229851634a0f03eb265b69f5a2d56f341 tree 71 76 5400 - 05408d195263d853f09dca71d55116663690c27c blob 12908 3478 874 - 09f01cea547666f58d6a8d809583841a7c6f0130 tree 106 107 5086 - 1a410efbd13591db07496601ebc7a059dd55cfe9 commit 225 151 322 - 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a blob 10 19 5381 - 3c4e9cd789d88d8d89c1073707c3585e41b0e614 tree 101 105 5211 - 484a59275031909e19aadb7c92262719cfcdf19a commit 226 153 169 - 83baae61804e65cc73a7201a7252750c76066a30 blob 10 19 5362 - 9585191f37f7b0fb9444f35a9bf50de191beadc2 tag 136 127 5476 - 9bc1dc421dcd51b4ac296e3e5b6e2a99cf44391e blob 7 18 5193 1 - 05408d195263d853f09dca71d55116663690c27c \ - ab1afef80fac8e34258ff41fc1b867c702daa24b commit 232 157 12 - cac0cab538b970a37ea1e769cbbde608743bc96d commit 226 154 473 - d8329fc1cc938780ffdd9f94e0d364e0ea74f579 tree 36 46 5316 - e3f094f522629ae358806b17daf78246c27c007b blob 1486 734 4352 - f8f51d7d8a1760462eca26eebafde32087499533 tree 106 107 749 - fa49b077972391ad58037050f2a75f74e3671e92 blob 9 18 856 - fdf4fc3344e67ab068f836878b6c4951e3b15f3d commit 177 122 627 - chain length = 1: 1 object - pack-7a16e4488ae40c7d2bc56ea2bd43e25212a66c45.pack: ok - -Here, the `9bc1d` blob, which if you remember was the first version of your repo.rb file, is referencing the `05408` blob, which was the second version of the file. The third column in the output is the size of the object in the pack, so you can see that `05408` takes up 12K of the file but that `9bc1d` only takes up 7 bytes. What is also interesting is that the second version of the file is the one that is stored intact, whereas the original version is stored as a delta — this is because you’re most likely to need faster access to the most recent version of the file. - -The really nice thing about this is that it can be repacked at any time. Git will occasionally repack your database automatically, always trying to save more space. You can also manually repack at any time by running `git gc` by hand. - -## The Refspec ## - -Throughout this book, you’ve used simple mappings from remote branches to local references; but they can be more complex. -Suppose you add a remote like this: - - $ git remote add origin git@github.com:schacon/simplegit-progit.git - -It adds a section to your `.git/config` file, specifying the name of the remote (`origin`), the URL of the remote repository, and the refspec for fetching: - - [remote "origin"] - url = git@github.com:schacon/simplegit-progit.git - fetch = +refs/heads/*:refs/remotes/origin/* - -The format of the refspec is an optional `+`, followed by `:`, where `` is the pattern for references on the remote side and `` is where those references will be written locally. The `+` tells Git to update the reference even if it isn’t a fast-forward. - -In the default case that is automatically written by a `git remote add` command, Git fetches all the references under `refs/heads/` on the server and writes them to `refs/remotes/origin/` locally. So, if there is a `master` branch on the server, you can access the log of that branch locally via - - $ git log origin/master - $ git log remotes/origin/master - $ git log refs/remotes/origin/master - -They’re all equivalent, because Git expands each of them to `refs/remotes/origin/master`. - -If you want Git instead to pull down only the `master` branch each time, and not every other branch on the remote server, you can change the fetch line to - - fetch = +refs/heads/master:refs/remotes/origin/master - -This is just the default refspec for `git fetch` for that remote. If you want to do something one time, you can specify the refspec on the command line, too. To pull the `master` branch on the remote down to `origin/mymaster` locally, you can run - - $ git fetch origin master:refs/remotes/origin/mymaster - -You can also specify multiple refspecs. On the command line, you can pull down several branches like so: - - $ git fetch origin master:refs/remotes/origin/mymaster \ - topic:refs/remotes/origin/topic - From git@github.com:schacon/simplegit - ! [rejected] master -> origin/mymaster (non fast forward) - * [new branch] topic -> origin/topic - -In this case, the master branch pull was rejected because it wasn’t a fast-forward reference. You can override that by specifying the `+` in front of the refspec. - -You can also specify multiple refspecs for fetching in your configuration file. If you want to always fetch the master and experiment branches, add two lines: - - [remote "origin"] - url = git@github.com:schacon/simplegit-progit.git - fetch = +refs/heads/master:refs/remotes/origin/master - fetch = +refs/heads/experiment:refs/remotes/origin/experiment - -You can’t use partial globs in the pattern, so this would be invalid: - - fetch = +refs/heads/qa*:refs/remotes/origin/qa* - -However, you can use namespacing to accomplish something like that. If you have a QA team that pushes a series of branches, and you want to get the master branch and any of the QA team’s branches but nothing else, you can use a config section like this: - - [remote "origin"] - url = git@github.com:schacon/simplegit-progit.git - fetch = +refs/heads/master:refs/remotes/origin/master - fetch = +refs/heads/qa/*:refs/remotes/origin/qa/* - -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. - -### 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? You accomplish that by using refspecs to push. - -If the QA team wants to push their `master` branch to `qa/master` on the remote server, they can run - - $ git push origin master:refs/heads/qa/master - -If they want Git to do that automatically each time they run `git push origin`, they can add a `push` value to their config file: - - [remote "origin"] - url = git@github.com:schacon/simplegit-progit.git - fetch = +refs/heads/*:refs/remotes/origin/* - push = refs/heads/master:refs/heads/qa/master - -Again, this will cause a `git push origin` to push the local `master` branch to the remote `qa/master` branch by default. - -### Deleting References ### - -You can also use the refspec to delete references from the remote server by running something like this: - - $ git push origin :topic - -Because the refspec is `:`, by leaving off the `` part, this basically says to make the topic branch on the remote nothing, which deletes it. - -## Transfer Protocols ## - -Git can transfer data between two repositories in two major ways: over HTTP and via the so-called smart protocols used in the `file://`, `ssh://`, and `git://` transports. This section will quickly cover how these two main protocols operate. - -### The Dumb Protocol ### - -Git transport over HTTP is often referred to as the dumb protocol because it requires no Git-specific code on the server side during the transport process. The fetch process is a series of GET requests, where the client can assume the layout of the Git repository on the server. Let’s follow the `http-fetch` process for the simplegit library: - - $ git clone http://github.com/schacon/simplegit-progit.git - -The first thing this command does is pull down the `info/refs` file. This file is written by the `update-server-info` command, which is why you need to enable that as a `post-receive` hook in order for the HTTP transport to work properly: - - => GET info/refs - ca82a6dff817ec66f44342007202690a93763949 refs/heads/master - -Now you have a list of the remote references and SHAs. Next, you look for what the HEAD reference is so you know what to check out when you’re finished: - - => GET HEAD - ref: refs/heads/master - -You need to check out the `master` branch when you’ve completed the process. -At this point, you’re ready to start the walking process. Because your starting point is the `ca82a6` commit object you saw in the `info/refs` file, you start by fetching that: - - => GET objects/ca/82a6dff817ec66f44342007202690a93763949 - (179 bytes of binary data) - -You get an object back — that object is in loose format on the server, and you fetched it over a static HTTP GET request. You can zlib-uncompress it, strip off the header, and look at the commit content: - - $ git cat-file -p ca82a6dff817ec66f44342007202690a93763949 - tree cfda3bf379e4f8dba8717dee55aab78aef7f4daf - parent 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 - author Scott Chacon 1205815931 -0700 - committer Scott Chacon 1240030591 -0700 - - changed the version number - -Next, you have two more objects to retrieve — `cfda3b`, which is the tree of content that the commit we just retrieved points to; and `085bb3`, which is the parent commit: - - => GET objects/08/5bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 - (179 bytes of data) - -That gives you your next commit object. Grab the tree object: - - => GET objects/cf/da3bf379e4f8dba8717dee55aab78aef7f4daf - (404 - Not Found) - -Oops — it looks like that tree object isn’t in loose format on the server, so you get a 404 response back. There are a couple of reasons for this — the object could be in an alternate repository, or it could be in a packfile in this repository. Git checks for any listed alternates first: - - => GET objects/info/http-alternates - (empty file) - -If this comes back with a list of alternate URLs, Git checks for loose files and packfiles there — this is a nice mechanism for projects that are forks of one another to share objects on disk. However, because no alternates are listed in this case, your object must be in a packfile. To see what packfiles are available on this server, you need to get the `objects/info/packs` file, which contains a listing of them (also generated by `update-server-info`): - - => GET objects/info/packs - P pack-816a9b2334da9953e530f27bcac22082a9f5b835.pack - -There is only one packfile on the server, so your object is obviously in there, but you’ll check the index file to make sure. This is also useful if you have multiple packfiles on the server, so you can see which packfile contains the object you need: - - => GET objects/pack/pack-816a9b2334da9953e530f27bcac22082a9f5b835.idx - (4k of binary data) - -Now that you have the packfile index, you can see if your object is in it — because the index lists the SHAs of the objects contained in the packfile and the offsets to those objects. Your object is there, so go ahead and get the whole packfile: - - => GET objects/pack/pack-816a9b2334da9953e530f27bcac22082a9f5b835.pack - (13k of binary data) - -You have your tree object, so you continue walking your commits. They’re all also within the packfile you just downloaded, so you don’t have to do any more requests to your server. Git checks out a working copy of the `master` branch that was pointed to by the HEAD reference you downloaded at the beginning. - -The entire output of this process looks like this: - - $ git clone http://github.com/schacon/simplegit-progit.git - Initialized empty Git repository in /private/tmp/simplegit-progit/.git/ - got ca82a6dff817ec66f44342007202690a93763949 - walk ca82a6dff817ec66f44342007202690a93763949 - got 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 - Getting alternates list for http://github.com/schacon/simplegit-progit.git - Getting pack list for http://github.com/schacon/simplegit-progit.git - Getting index for pack 816a9b2334da9953e530f27bcac22082a9f5b835 - Getting pack 816a9b2334da9953e530f27bcac22082a9f5b835 - which contains cfda3bf379e4f8dba8717dee55aab78aef7f4daf - walk 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 - walk a11bef06a3f659402fe7563abf99ad00de2209e6 - -### The Smart Protocol ### - -The HTTP method is simple but a bit inefficient. Using smart protocols is a more common method of transferring data. These protocols have a process on the remote end that is intelligent about Git — it can read local data and figure out what the client has or needs and generate custom data for it. There are two sets of processes for transferring data: a pair for uploading data and a pair for downloading data. - -#### Uploading Data #### - -To upload data to a remote process, Git uses the `send-pack` and `receive-pack` processes. The `send-pack` process runs on the client and connects to a `receive-pack` process on the remote side. - -For example, say you run `git push origin master` in your project, and `origin` is defined as a URL that uses the SSH protocol. Git fires up the `send-pack` process, which initiates a connection over SSH to your server. It tries to run a command on the remote server via an SSH call that looks something like this: - - $ ssh -x git@github.com "git-receive-pack 'schacon/simplegit-progit.git'" - 005bca82a6dff817ec66f4437202690a93763949 refs/heads/master report-status delete-refs - 003e085bb3bcb608e1e84b2432f8ecbe6306e7e7 refs/heads/topic - 0000 - -The `git-receive-pack` command immediately responds with one line for each reference it currently has — in this case, just the `master` branch and its SHA. The first line also has a list of the server’s capabilities (here, `report-status` and `delete-refs`). - -Each line starts with a 4-byte hex value specifying how long the rest of the line is. Your first line starts with 005b, which is 91 in hex, meaning that 91 bytes remain on that line. The next line starts with 003e, which is 62, so you read the remaining 62 bytes. The next line is 0000, meaning the server is done with its references listing. - -Now that it knows the server’s state, your `send-pack` process determines what commits it has that the server doesn’t. For each reference that this push will update, the `send-pack` process tells the `receive-pack` process that information. For instance, if you’re updating the `master` branch and adding an `experiment` branch, the `send-pack` response may look something like this: - - 0085ca82a6dff817ec66f44342007202690a93763949 15027957951b64cf874c3557a0f3547bd83b3ff6 refs/heads/master report-status - 00670000000000000000000000000000000000000000 cdfdb42577e2506715f8cfeacdbabc092bf63e8d refs/heads/experiment - 0000 - -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. - -Git sends a line for each reference you’re updating with the old SHA, the new SHA, and the reference that is being updated. The first line also has the client’s capabilities. Next, the client uploads a packfile of all the objects the server doesn’t have yet. Finally, the server responds with a success (or failure) indication: - - 000Aunpack ok - -#### Downloading Data #### - -When you download data, the `fetch-pack` and `upload-pack` processes are involved. The client initiates a `fetch-pack` process that connects to an `upload-pack` process on the remote side to negotiate what data will be transferred down. - -There are different ways to initiate the `upload-pack` process on the remote repository. You can run via SSH in the same manner as the `receive-pack` process. You can also initiate the process via the Git daemon, which listens on a server on port 9418 by default. The `fetch-pack` process sends data that looks like this to the daemon after connecting: - - 003fgit-upload-pack schacon/simplegit-progit.git\0host=myserver.com\0 - -It starts with the 4 bytes specifying how much data is following, then the command to run followed by a null byte, and then the server’s hostname followed by a final null byte. The Git daemon checks that the command can be run and that the repository exists and has public permissions. If everything is cool, it fires up the `upload-pack` process and hands off the request to it. - -If you’re doing the fetch over SSH, `fetch-pack` instead runs something like this: - - $ ssh -x git@github.com "git-upload-pack 'schacon/simplegit-progit.git'" - -In either case, after `fetch-pack` connects, `upload-pack` sends back something like this: - - 0088ca82a6dff817ec66f44342007202690a93763949 HEAD\0multi_ack thin-pack \ - side-band side-band-64k ofs-delta shallow no-progress include-tag - 003fca82a6dff817ec66f44342007202690a93763949 refs/heads/master - 003e085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 refs/heads/topic - 0000 - -This is very similar to what `receive-pack` responds with, but the capabilities are different. In addition, it sends back the HEAD reference so the client knows what to check out if this is a clone. - -At this point, the `fetch-pack` process looks at what objects it has and responds with the objects that it needs by sending "want" and then the SHA it wants. It sends all the objects it already has with "have" and then the SHA. At the end of this list, it writes "done" to initiate the `upload-pack` process to begin sending the packfile of the data it needs: - - 0054want ca82a6dff817ec66f44342007202690a93763949 ofs-delta - 0032have 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 - 0000 - 0009done - -That is a very basic case of the transfer protocols. In more complex cases, the client supports `multi_ack` or `side-band` capabilities; but this example shows you the basic back and forth used by the smart protocol processes. - -## Maintenance and Data Recovery ## - -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. - -### Maintenance ### - -Occasionally, Git automatically runs a command called "auto gc". 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: - - $ 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 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. Suppose your repository contains the following branches and tags: - - $ find .git/refs -type f - .git/refs/heads/experiment - .git/refs/heads/master - .git/refs/tags/v1.0 - .git/refs/tags/v1.1 - -If you run `git gc`, you’ll no longer have these files in the `refs` directory. Git will move them for the sake of efficiency into a file named `.git/packed-refs` that looks like this: - - $ cat .git/packed-refs - # pack-refs with: peeled - cac0cab538b970a37ea1e769cbbde608743bc96d refs/heads/experiment - ab1afef80fac8e34258ff41fc1b867c702daa24b refs/heads/master - cac0cab538b970a37ea1e769cbbde608743bc96d refs/tags/v1.0 - 9585191f37f7b0fb9444f35a9bf50de191beadc2 refs/tags/v1.1 - ^1a410efbd13591db07496601ebc7a059dd55cfe9 - -If you update a reference, Git doesn’t edit this file but instead writes a new file to `refs/heads`. To get the appropriate SHA for a given reference, Git checks for that reference in the `refs` directory and then checks the `packed-refs` file as a fallback. However, if you can’t find a reference in the `refs` directory, it’s probably in your `packed-refs` file. - -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. - -### Data Recovery ### - -At some point in your Git journey, you may accidentally lose a commit. Generally, this happens because you force-delete a branch that had work on it, and it turns out you wanted the branch after all; or you hard-reset a branch, thus abandoning commits that you wanted something from. Assuming this happens, how can you get your commits back? - -Here’s an example that hard-resets the master branch in your test repository to an older commit and then recovers the lost commits. First, let’s review where your repository is at this point: - - $ git log --pretty=oneline - ab1afef80fac8e34258ff41fc1b867c702daa24b modified repo a bit - 484a59275031909e19aadb7c92262719cfcdf19a added repo.rb - 1a410efbd13591db07496601ebc7a059dd55cfe9 third commit - cac0cab538b970a37ea1e769cbbde608743bc96d second commit - fdf4fc3344e67ab068f836878b6c4951e3b15f3d first commit - -Now, move the `master` branch back to the middle commit: - - $ git reset --hard 1a410efbd13591db07496601ebc7a059dd55cfe9 - HEAD is now at 1a410ef third commit - $ git log --pretty=oneline - 1a410efbd13591db07496601ebc7a059dd55cfe9 third commit - cac0cab538b970a37ea1e769cbbde608743bc96d second commit - fdf4fc3344e67ab068f836878b6c4951e3b15f3d first commit - -You’ve effectively lost the top two commits — you have no branch from which those commits are reachable. You need to find the latest commit SHA and then add a branch that points to it. The trick is finding that latest commit SHA — it’s not like you’ve memorized it, right? - -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 value to your ref files, as we covered in the "Git References" section of this chapter earlier. You can see where you’ve been at any time by running `git reflog`: - - $ git reflog - 1a410ef HEAD@{0}: 1a410efbd13591db07496601ebc7a059dd55cfe9: updating HEAD - ab1afef HEAD@{1}: ab1afef80fac8e34258ff41fc1b867c702daa24b: updating HEAD - -Here we can see the two commits that we have had checked out, however there is not much information here. To see the same information in a much more useful way, we can run `git log -g`, which will give you a normal log output for your reflog. - - $ git log -g - commit 1a410efbd13591db07496601ebc7a059dd55cfe9 - Reflog: HEAD@{0} (Scott Chacon ) - Reflog message: updating HEAD - Author: Scott Chacon - Date: Fri May 22 18:22:37 2009 -0700 - - third commit - - commit ab1afef80fac8e34258ff41fc1b867c702daa24b - Reflog: HEAD@{1} (Scott Chacon ) - Reflog message: updating HEAD - Author: Scott Chacon - Date: Fri May 22 18:15:24 2009 -0700 - - modified repo a bit - -It looks like the bottom commit is the one you lost, so you can recover it by creating a new branch at that commit. For example, you can start a branch named `recover-branch` at that commit (ab1afef): - - $ git branch recover-branch ab1afef - $ git log --pretty=oneline recover-branch - ab1afef80fac8e34258ff41fc1b867c702daa24b modified repo a bit - 484a59275031909e19aadb7c92262719cfcdf19a added repo.rb - 1a410efbd13591db07496601ebc7a059dd55cfe9 third commit - cac0cab538b970a37ea1e769cbbde608743bc96d second commit - fdf4fc3344e67ab068f836878b6c4951e3b15f3d first commit - -Cool — now you have a branch named `recover-branch` that is where your `master` branch used to be, making the first two commits reachable again. -Next, suppose your loss was for some reason not in the reflog — you can simulate that by removing `recover-branch` and deleting the reflog. Now the first two commits aren’t reachable by anything: - - $ git branch –D recover-branch - $ rm -Rf .git/logs/ - -Because the reflog data is kept in the `.git/logs/` directory, you effectively have no reflog. How can you recover that commit at this point? One way is to use the `git fsck` utility, which checks your database for integrity. If you run it with the `--full` option, it shows you all objects that aren’t pointed to by another object: - - $ git fsck --full - dangling blob d670460b4b4aece5915caf5c68d12f560a9fe3e4 - dangling commit ab1afef80fac8e34258ff41fc1b867c702daa24b - dangling tree aea790b9a58f6cf6f2804eeac9f0abbe9631e4c9 - dangling blob 7108f7ecb345ee9d0084193f147cdad4d2998293 - -In this case, you can see your missing commit after the dangling commit. You can recover it the same way, by adding a branch that points to that SHA. - -### 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. This is fine if the whole thing is source code, because Git is highly optimized to compress that data efficiently. However, if someone at any point in the history of your project added a single huge file, every clone for all time will be forced to download that large file, even if it was removed from the project in the very next commit. Because it’s reachable from the history, it will always be there. - -This can be a huge problem when you’re converting Subversion or Perforce repositories into Git. Because you don’t download the whole history in those systems, this type of addition carries few consequences. If you did an import from another system or otherwise find that your repository is much larger than it should be, here is how you can find and remove large objects. - -Be warned: this technique is destructive to your commit history. It rewrites every commit object downstream from the earliest tree you have to modify to remove a large file reference. If you do this immediately after an import, before anyone has started to base work on the commit, you’re fine — otherwise, you have to notify all contributors that they must rebase their work onto your new commits. - -To demonstrate, you’ll add a large file into your test repository, remove it in the next commit, find it, and remove it permanently from the repository. First, add a large object to your history: - - $ curl http://kernel.org/pub/software/scm/git/git-1.6.3.1.tar.bz2 > git.tbz2 - $ git add git.tbz2 - $ git commit -am 'added git tarball' - [master 6df7640] added git tarball - 1 files changed, 0 insertions(+), 0 deletions(-) - create mode 100644 git.tbz2 - -Oops — you didn’t want to add a huge tarball to your project. Better get rid of it: - - $ git rm git.tbz2 - rm 'git.tbz2' - $ git commit -m 'oops - removed large tarball' - [master da3f30d] oops - removed large tarball - 1 files changed, 0 insertions(+), 0 deletions(-) - delete mode 100644 git.tbz2 - -Now, `gc` your database and see how much space you’re using: - - $ git gc - Counting objects: 21, done. - Delta compression using 2 threads. - Compressing objects: 100% (16/16), done. - Writing objects: 100% (21/21), done. - Total 21 (delta 3), reused 15 (delta 1) - -You can run the `count-objects` command to quickly see how much space you’re using: - - $ git count-objects -v - count: 4 - size: 16 - in-pack: 21 - packs: 1 - size-pack: 2016 - prune-packable: 0 - garbage: 0 - -The `size-pack` entry is the size of your packfiles in kilobytes, so you’re using 2MB. Before the last commit, you were using closer to 2K — clearly, removing the file from the previous commit didn’t remove it from your history. Every time anyone clones this repository, they will have to clone all 2MB just to get this tiny project, because you accidentally added a big file. Let’s get rid of it. - -First you have to find it. In this case, you already know what file it is. But suppose you didn’t; how would you identify what file or files were taking up so much space? If you run `git gc`, all the objects are in a packfile; you can identify the big objects by running another plumbing command called `git verify-pack` and sorting on the third field in the output, which is file size. You can also pipe it through the `tail` command because you’re only interested in the last few largest files: - - $ git verify-pack -v .git/objects/pack/pack-3f8c0...bb.idx | sort -k 3 -n | tail -3 - e3f094f522629ae358806b17daf78246c27c007b blob 1486 734 4667 - 05408d195263d853f09dca71d55116663690c27c blob 12908 3478 1189 - 7a9eb2fba2b1811321254ac360970fc169ba2330 blob 2056716 2056872 5401 - -The big object is at the bottom: 2MB. To find out what file it is, you’ll use the `rev-list` command, which you used briefly in Chapter 7. If you pass `--objects` to `rev-list`, it lists all the commit SHAs and also the blob SHAs with the file paths associated with them. You can use this to find your blob’s name: - - $ git rev-list --objects --all | grep 7a9eb2fb - 7a9eb2fba2b1811321254ac360970fc169ba2330 git.tbz2 - -Now, you need to remove this file from all trees in your past. You can easily see what commits modified this file: - - $ git log --pretty=oneline -- git.tbz2 - da3f30d019005479c99eb4c3406225613985a1db oops - removed large tarball - 6df764092f3e7c8f5f94cbe08ee5cf42e92a0289 added git tarball - -You must rewrite all the commits downstream from `6df76` to fully remove this file from your Git history. To do so, you use `filter-branch`, which you used in Chapter 6: - - $ git filter-branch --index-filter \ - 'git rm --cached --ignore-unmatch git.tbz2' -- 6df7640^.. - Rewrite 6df764092f3e7c8f5f94cbe08ee5cf42e92a0289 (1/2)rm 'git.tbz2' - Rewrite da3f30d019005479c99eb4c3406225613985a1db (2/2) - Ref 'refs/heads/master' was rewritten - -The `--index-filter` option is similar to the `--tree-filter` option used in Chapter 6, 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. You can accomplish the same task with `--tree-filter` if you want. The `--ignore-unmatch` option to `git rm` tells it not to error out if the pattern you’re trying to remove isn’t there. Finally, you ask `filter-branch` to rewrite your history only from the `6df7640` commit up, because you know that is where this problem started. Otherwise, it will start from the beginning and will unnecessarily take longer. - -Your history no longer contains a reference to that file. However, your reflog and a new set of refs that Git added when you did the `filter-branch` under `.git/refs/original` still do, so you have to remove them and then repack the database. You need to get rid of anything that has a pointer to those old commits before you repack: - - $ rm -Rf .git/refs/original - $ rm -Rf .git/logs/ - $ git gc - Counting objects: 19, done. - Delta compression using 2 threads. - Compressing objects: 100% (14/14), done. - Writing objects: 100% (19/19), done. - Total 19 (delta 3), reused 16 (delta 1) - -Let’s see how much space you saved. - - $ git count-objects -v - count: 8 - size: 2040 - in-pack: 19 - packs: 1 - size-pack: 7 - prune-packable: 0 - garbage: 0 - -The packed repository size is down to 7K, which is much better than 2MB. You can see from the size value that the big object is still in your loose objects, so it’s not gone; but it won’t be transferred on a push or subsequent clone, which is what is important. If you really wanted to, you could remove the object completely by running `git prune --expire`. - -## Summary ## - -You should have a pretty good understanding of what Git does in the background and, to some degree, how it’s implemented. This chapter has covered a number of plumbing commands — commands that are lower level and simpler than the porcelain commands you’ve learned about in the rest of the book. Understanding how Git works at a lower level should make it easier to understand why it’s doing what it’s doing and also to write your own tools and helping scripts to make your specific workflow work for you. - -Git as a content-addressable filesystem is a very powerful tool that you can easily use as more than just a VCS. I hope you can use your newfound knowledge of Git internals to implement your own cool application of this technology and feel more comfortable using Git in more advanced ways. diff --git a/ar/NOTES b/ar/NOTES index 89a94b00d..3ee08459d 100644 --- a/ar/NOTES +++ b/ar/NOTES @@ -4,8 +4,8 @@ فيما يلي قائمة بالمصطلحات الإنكليزية ومحاولتي لتعريبها، يمكنك المشاركة في تعديل هذه المصطلحات وإقتراح الأفضل إن أردت. * نظام إدارة الإصدارات = Version Control System. -* نظم إدارة الإصدارات المحلية = Local Version Control Systems. -* نظم إدارة الإصدارات المركزية = Centralized Version Control Systens. +* أنظمة إدارة الإصدارات المحلية = Local Version Control Systems. +* أنظمة إدارة الإصدارات المركزية = Centralized Version Control Systems. ملاحظة: ستجد الكلمة الإنكليزية الأصلية بعد ترجمتي المقترحة لها في سياق الكتاب أول مرة تظهر فيها الكلمة في كل فصل فقط (أو أكثر حسب الحاجة). diff --git a/by/01-introduction/01-chapter1.markdown b/az/01-introduction/01-chapter1.markdown similarity index 54% rename from by/01-introduction/01-chapter1.markdown rename to az/01-introduction/01-chapter1.markdown index 6a515d61a..d2cea2626 100644 --- a/by/01-introduction/01-chapter1.markdown +++ b/az/01-introduction/01-chapter1.markdown @@ -1,57 +1,57 @@ -# Першыя крокі # +# Başlanğıc # -Гэтая глава прысвечана пачатку працы з Git. Мы пачнем з тлумачэння асноў працы прылад кантролю версій, затым пяройдзем да таго як атрымаць працуючы Git ў сваёй сістэмы і, урэшце, як наладзіць яго так, каб з ім можна было пачаць працаваць. Напрыканцы гэтай главы вы будзеце мець разуменне для чаго наогул прызначаны Git, чаму ім варта карыстацца і мець усе неабходныя наладкі дзеля гэтага. +Bu bölmə size git haqqında başlıca məlumatları çattırmağı hədəfləyir. İşə başlamazdan əvvəl version nəzarət vasitəsinin bəzi fon məlumatlarını açıqlayaraq başlayacağıq, daha sonra Git quraşdırılmanının necə ediləcəyini, ən son olaraq da vasitənin konfiqurasiya və istifadəsini açıqlayacağıq. Bu hissənin sonunda Git'in varlıq səbəbini və niyə onu istifadə etməniz lazım olduğunu anlayacaq, Git'i istifadə etmeye başlamaq üçün quraşdırma bitirmiş olacaqsınız. -## Пра кантроль версій ## +## Versiya Nəzarət Haqqında ## -Што такое кантроль версій і навошта ён патрэбны? Кантроль версій — гэта сістэма, якая запісвае змены, што адбыліся з файлам ці наборам файлаў з цягам часу, так што вы можаце вярнуцца да розных версій пазней. У прыкладах гэтай кнігі мы будзем працаваць з зыходнікамі праграмнага забеспечэння ў якасці файлаў, версіі якіх будуць кантралявацца, але, насамрэч, вы можаце выкарыстоўваць гэтую магчымасць практычна з любым тыпам файла, які існуе на вашым кампутары. +Versiya nəzarəti nədir və nə işə yarayar? Versiya nəzarəti, Bir ya da daha çox fayl üzərində edilən dəyişiklikləri yazan və daha sonra müəyyən bir distributivə geri dönə bilmənizi təmin edən bir sistemdir. Bu kitabdakı nümunələrdə proqram qaynaq kod fayllarının versiya idarəsini edəcəksiniz, nə var ki, əslində versiyası idarəsini demək olar ki hər növdən fayl üçün istifadə edə bilərsiniz. -Калі вы графічны ці web дызайнер і маеце намер захоўваць кожную версію малюнкаў ці слаёў (што вам больш патрэбна), то выкарыстанне сістэмы кантролю версій (СКВ; Version Control System, VCS) гэта вельмі разумны выбар. Гэта дазволіць вам вярнуць файлы да папярэдняга стану, вярнуць весь праект да папярэдняга стану, параўнаць змены паміж рознымі станамі, убачыць хто апошнім змяняў нешта, што можа выклікаць праблемы, хто прапанаваў змену і калі, і шмат іншага. Выкарыстанне СКВ у асноўным значыць, што калі вы сапсавалі нешта ці страцілі файлы, то гэта можна лёгка ўзнавіць. Як дадатак, гэта не запатрабуе вялікіх намаганняў і выдаткаў з вашага боку. +Bir grafik və ya web dizayn tək və bir vizual və ya dizaynın dəyişik versiyalarını qorumaq istəyirsinizsə (ki ehtimalla bunu etmək istəyərsiniz), bir Versiya Nəzarət Sistemi (VNS) istifadə etməniz çox ağıllıca olacaq. VNS, faylların və ya bütün layihənin keçmişdəki müəyyən bir versiyaya daxil olmağa, zaman içində edilən dəyişiklikləri müqayisə etməyinizi, problemə səbəb olan şeydə ən son kimin dəyişiklik etdiyini, müəyyən bir səhvi kimin, nə vaxt sistemə daxil etdiyini və daha başqa bir çox şeyi görə bilməyinizi təmin edər. Digər tərəfdən, VNS istifadə etmək, bir səhv etdikdə və ya bəzi faylları səhvən sildiyiniz də vəziyyəti asanlıqla kompensasiya etmənizə köməkçi olar. Üstəlik, bütün bunlar sizə əhəmiyyətli bir əlavə yük də gətirməz. -### Лакальныя сістэмы кантролю версій ### +### Lokal Sürüm Nəzarət Sistemləri ### -Шмат людзей ў якасці метаду кантролю версій выбірае капіяванне файлаў у іншую тэчку (магчыма, з датай у назве, калі чалавек досыць разумны). Гэты падыход вельмі распаўсюджаны з-за сваёй прастаты, але ён пакідае неверагодна шмат магчымасцяў для памылак. Вельмі лёгка забыцца ў якой тэчцы вы зараз і выпадкова запісаць не ў той файл, ці зкапіяваць зусім не туды, куды вы збіраліся. +Əksəriyyəti faylları bir qovluğa (ağılları başlarındaysa tarix və zaman məlumatını də daxil olmaqla bir qovluğa) kopiyalayaraq versiyas nəzarətini etməyi seçər. Bu yanaşma çox məşhurdur, çünki çox asandır; amma eyni zamanda səhvlərə də ala bildiyinə açıqdır. Hansı qovluqda olduğunuzu unudub səhv fayla yaza ya da istəmədiyiniz faylların üstünə kopiyalama edə bilərsiniz. -Каб развязаць гэтую праблему праграмісты шмат часу таму распрацавлі лакальныя СКВ, якія выкарыстоўваюць простую базу дадзеных каб захоўваць ўсе змены ў файлах, версіі якіх адсочваюцца (гл. Малюнак 1-1). +Bu problemlə baş edə bilmək üçün, proqramçılar uzun zaman əvvəl, fayllardakı bütün dəyişiklikləri versiya nəzarətinə alan sadə bir veri bazasına sahib olan lokal VNS'leri inkişaf etdirdilər (bax Göstərici 1-1). Insert 18333fig0101.png -Малюнак 1-1. Схема лакальнага кантролю версій. +Göstərici 1-1. Lokal Sürüm Nəzarət diaqramı. -Адной з папулярных у той час СКВ была rcs, якая ўсё яшчэ пастаўляецца з вялікай колькасцю кампутараў. Нават папулярная аперацыйная сістэма Mac OS X усталёўвае rcs у складзе пакета Developer Tools. Праца гэтай прылады заснаваная на захаванні на дыску ў спецыяльным фармаце набораў латак (patch) (гэта запісы розніцы паміж дзвума файламі) для кожнай змены файла. Гэта дапамагае вярнуць файл да любога з зафіксаваных станаў, паслядоўна накладыючы латкі адну за адной. +Ən məşhur VNS vasitələrindən biri, bu gün hələ çox kompüterə yüklenmiş olaraq yayılan, RCS adında bir sistem idi. Məşhur Mac OS X əməliyyat sistemi belə, Developer Tools'u yüklediğinizde, RCS əmrini qurmaqdadır. Bu vasitə, iki versiyası arasındakı yamaqları (yəni, fayllar arasındakı fərqləri) xüsusi bir şəkildə diskə yazar; daha sonra, bu yamaqları bir-birinə əlavə, bir faylın müəyyən bir distributivdəki görünüşünü yenidən meydana gətirər. -### Цэнтралізаваныя сістэмы кантролю версій ### +### Mərkəzi Versiya Nəzarət Sistemləri ### -Наступнай сур'ёзнай праблемай, з якой людзі сутыкнуліся была неабходнасць супрацоўнічаць з распрацоўшчыкамі за іншымі кампутарамі. Централізаваныя сістэмы кантролю версій (ЦСКВ) былі распрацаваныя каб развязаць гэтую праблему. Такія сістэмы як CVS, Subversion і Perforce складаюцца з сервера, на якім захоўваюцца ўсе дадзеныя па версіях файлаў, і некаторай колькасці кліенцкіх машын, якія атрымліваюць файлы з сервера. Шмат год такая схема з'яўлялася стандартам кантролю версій (гл. Малюнак 1-2). +İnsanların qarşılaşdığı ikinci böyük problem, başqa sistemlərdəki proqramçılar ilə birlikdə iş ehtiyacından irəli gəlir. Bu problemlə başa çıxa bilmək üçün, Mərkəzi Versiya Nəzarət Sistemləri (MVNS) inkişaf etdirilmişdir. Bu sistemlər, məsələn CVS, Subversion və Perforce, versiyası idarəsinə alınan bütün faylları tutan bir server və bu serverdən faylları seçərək alan (check out) alıcını meydana gələr. Bu üsul, illərcə, versiyası idarəsində standart üsul olaraq qəbul gördü (bax Göstərici 1-2). Insert 18333fig0102.png -Малюнак 1-2. Схема цэнтралізаванага кантролю версій. +Göstərici 1-2. Mərkəzi Versiya Nəzarət diaqramı. -Гэты падыход мае шмат пераваг, асабліва ў параўнанні з лакальнымі СКВ. Напрыклад, усе дакладна ведаюць што асатнія робяць і што наогул адбываецца ў праекце. Адміністратары маюць зручную магчымасць кантролю за тым хто што можа зрабіць. І гэта значна прасцей, чым адміністраванне лакальных баз дадзеных СКВ на кожнай кліенцкай машыне. +Bu üsulun, xüsusilə lokal VNS lere görə, çox sayda üstünlüyü vardır. Məsələn, bir projedeki hər kəs, digərlərinin nə etdiyindən müəyyən ölçüdə xəbərdardır. Sistem idarəçiləri kimin hansı səlahiyyətlərə sahib olacağını olduqca detallı şəkildə təşkil; üstəlik bir MVNS'yi idarə, hər alıcını ayrı-ayrı heyəti olan yerli bazalarını idarə görə çox daha asandır. -Аднак, гэты падыход мае і некаторыя сур'ёзныя мінусы. Самы відавочны з іх — центральны сервер яўляе сабою пункт, крах якога цягне за сабою крах усёй сістэмы. Калі гэты сервер спыніць працу на гадзіну — у гэтую гадзіну ніхто не зможа абмяняцца з супрацоўнікамі вынікамі сваёй працы ці захаваць новую версію таго, над чым ён ці яна зараз працуе. Калі жосткі дыск, на якім змешчаная цэнтральная база дадзеных пашкоджаны, а актуальных рэзервовых копій няма, то вы згубіце абсалютна ўсё: усё гісторыю праекту, за выключэннем тых здымкаў, што карыстальнікі выпадкова мелі на сваіх лакальных кампутарах. Лакальныя СКВ пакутуюць на тую ж праблему: калі ты маеш усю гісторыю пракета толькі ў адным месцы, то ты рызыкуеш згубіць усё. +Nə var ki, bu üsulun də ciddi bəzi çətinlikləri vardır. Ən aşkar çətinlik, mərkəzi serverin işləməməsi vəziyyətində ortaya çıxacaq qırılma nöqtəsi problemidir. Server bir saatlığına çökəcək olsa, o bir saat boyunca istifadəçilərin işlərini sistemə köçürmələri ya da çalışdıqları şeylərin sürümlenmiş surətlərini saxlamaq mümkün olmayacaq. Mərkəzi bazanın sabit diski pozulacaq olsa, ehtiyyat da olması lazım olduğu kimi edilməmişsə, əlinizdəki hər şeyi -projenin, istifadəçilərin kompüterlərində qalan lokal yaddaş kopiyaları (snapshot) xaricindəki bütün tarihçesini- itirərsiniz. Yerli VNS'ler də bu problemdən çəkir -projenin bütün tarixçəsini tək bir yerdə tutduğunuz müddətcə hər şeyi itirmə riskiniz var. -### Размеркаваныя сістэмы кантролю версій ### +### Paylanmış Versiya Nəzarət Sistemləri ### -І вось тут у гульню ўступаюць размеркаваныя сістэмы кантролю версій (РСКВ). У РСКВ (такіх як Git, Mercurial, Bazaar ці Darcs) кліенты не толькі атрымліваюць апошнія здымкі файлаў: яны атрымліваюць поўную копію сховішча. Такім чынам, калі любы з сервераў праз які ідзе абмен вынікамі працы памрэ, то любое з кліенцкіх сховішчаў можа быць зкапіявана на сервер каб аднавіць усю інфармацыю. Кожнае сховішча на кожным з працоўных месцаў насамрэч поўная рэзервовая копія ўсіх дадзеных (гл. Малюнак 1-3). +Bu nöqtədə Paylanmış Versiya Nəzarət Sistemləri (PVNS) dövrəyə girər. Bir PVNS'de (Git, Mercurial, Bazaar ya da Darcs nümunələrində olduğu kimi), müştərilər (istifadəçilər) faylların yalnız ən son yaddaş surətlərini almaqla qalmazlar: proqram hovuzunu (repository) tamamilə yansılalar (kopyalarlar).Beləcə, serverlərdən biri çöksə, və o server üzərindən ortaq iş icra edən sistemlər varsa, alıcını birinin proqram hovuzu serverə geri yüklənərək sistem qurtarıla bilər. Hər seçmə (checkout) əməliyyatı əsasında bütün məlumatın yedeklenmesiyle nəticələnər(bax Göstərici 1-3). Insert 18333fig0103.png -Малюнак 1-3. Схема размеркаванага кантролю версій. +Göstərici 1-3. Paylanmış Versiya Nəzarət diaqramı. -Апроч таго, шмат якія з гэтых сістэм выдатна працуюць з некалькімі аддаленымі сховішчамі, так што вы можаце адначасова па-рознаму узаемадзейнічаць з некалькімі рознымі групамі людзей у межах аднаго праекта. Гэта дазваляе наладжваць розные тыпы паслядоўнасцяў дзеянняў, што немагчыма з цэнтралізаванымі сістэмамі, такімі як іерархічныя мадэлі. +Dahası, bu sistemlerden çoğu birden çok uzak uçbirimdeki yazılım havuzuyla rahatlıkla çalışır, böylece, aynı proje için aynı anda farklı insan topluluklarıyla farklı biçimlerde ortak çalışmalar yürütebilirsiniz. Bu, birden çok iş akışı ile çalışabilmenizi sağlar, ki bu merkezi sistemlerde (hiyerarşik modeller gibi) mümkün değildir. -## Кароткая гісторыя Git ## +## A Short History of Git ## -Як і шмат іншых вялікіх рэчаў у жыцці, Git пачынаўся з стваральнага разбурэння і палымяных спрэчак. Ядро Linux — праграмны праект з адкрытымі зыходнікамі даволі вялікага аб'ёму. На пряцягу большай часткі перыяду існавання ядра Linux змены ў ім распаўсюджваліся у выглядзе патчаў і архіваваных файлаў. У 2002 годзе праект распрацоўкі ядра Linux пачаў карыстацца BitKeeper — прапрыетарнай РСКВ +As with many great things in life, Git began with a bit of creative destruction and fiery controversy. The Linux kernel is an open source software project of fairly large scope. For most of the lifetime of the Linux kernel maintenance (1991–2002), changes to the software were passed around as patches and archived files. In 2002, the Linux kernel project began using a proprietary DVCS system called BitKeeper. -У 2005 годзе адносіны паміж суполкай распрацоўшчыкаў ядра Linux і камерцыйнай кампаніяй, што распрацоўвала BitKeeper сапсаваліся і бясплатна карыстацца гэтай утылітай стала немагчыма. Гэта запатрабавала ад суполкі распрацоўшчыкаў Linux (і, ў прыватнасці, Лінуса Торвальдса (Linus Torvalds), стваральніка Linux'а) ствараць іх уласную сістэму, заснаваную на некаторых з урокаў, якія яны вынеслі для сябе з досведу карыстання BitKeeper. Некаторыя з мэтаў новай сітэмы ніжэй: +In 2005, the relationship between the community that developed the Linux kernel and the commercial company that developed BitKeeper broke down, and the tool’s free-of-charge status was revoked. 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. Some of the goals of the new system were as follows: -* Хуткасць -* Просты дызайн -* Моцная падтрымка нелінейнай распрацоўкі (сотні паралельных галін) -* Цалкам размеркаваная -* Магчымасць эфектыўна працаваць з вялікімі праектамі, кшталту ядра Linux (хуткасць і памер дадзеных) +* 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) -З часу свайго з'яўлення ў 2005 годзе Git развіваўся і сталеў каб быць лёгкім у выкарыстанні і пры гэтым захоўваць гэтыя першапачатковыя якасці. Ён неверагодна хуткі, вельмі эфектыўны ў працы з вялікімі праектамі і мае неверагодную сістэму кіравання галінамі для нелінейных праектаў (гл. главу 3). +Since its birth in 2005, Git has evolved and matured to be easy to use and yet retain these initial qualities. It’s incredibly fast, it’s very efficient with large projects, and it has an incredible branching system for non-linear development (See Chapter 3). ## Git Basics ## @@ -93,7 +93,7 @@ You will see these hash values all over the place in Git because it uses them so When you do actions in Git, nearly all of them only add data to the Git database. It is very difficult to get the system to do anything that is not undoable or to make it erase data in any way. As in any VCS, you can lose or mess up changes you haven’t committed yet; but after you commit a snapshot into Git, it is very difficult to lose, especially if you regularly push your database to another repository. -This makes using Git a joy because we know we can experiment without the danger of severely screwing things up. For a more in-depth look at how Git stores its data and how you can recover data that seems lost, see “Under the Covers” in Chapter 9. +This makes using Git a joy because we know we can experiment without the danger of severely screwing things up. For a more in-depth look at how Git stores its data and how you can recover data that seems lost, see Chapter 9. ### The Three States ### @@ -112,9 +112,9 @@ The staging area is a simple file, generally contained in your Git directory, th The basic Git workflow goes something like this: -1. You modify files in your working directory. -2. You stage the files, adding snapshots of them to your staging area. -3. You do a commit, which takes the files as they are in the staging area and stores that snapshot permanently to your Git directory. +1. You modify files in your working directory. +2. You stage the files, adding snapshots of them to your staging area. +3. You do a commit, which takes the files as they are in the staging area and stores that snapshot permanently to your Git directory. If a particular version of a file is in the git directory, it’s considered committed. If it’s modified but has been added to the staging area, it is staged. And if it was changed since it was checked out but has not been staged, it is modified. In Chapter 2, you’ll learn more about these states and how you can either take advantage of them or skip the staged part entirely. @@ -140,8 +140,8 @@ When you have all the necessary dependencies, you can go ahead and grab the late Then, compile and install: - $ tar -zxf git-1.6.0.5.tar.gz - $ cd git-1.6.0.5 + $ tar -zxf git-1.7.2.2.tar.gz + $ cd git-1.7.2.2 $ make prefix=/usr/local all $ sudo make prefix=/usr/local install @@ -157,13 +157,13 @@ If you want to install Git on Linux via a binary installer, you can generally do Or if you’re on a Debian-based distribution like Ubuntu, try apt-get: - $ apt-get install git-core + $ apt-get install git ### Installing on Mac ### -There are two easy ways to install Git on a Mac. The easiest is to use the graphical Git installer, which you can download from the Google Code page (see Figure 1-7): +There are two easy ways to install Git on a Mac. The easiest is to use the graphical Git installer, which you can download from the SourceForge page (see Figure 1-7): - http://code.google.com/p/git-osx-installer + http://sourceforge.net/projects/git-osx-installer/ Insert 18333fig0107.png Figure 1-7. Git OS X installer. @@ -176,9 +176,9 @@ You don’t have to add all the extras, but you’ll probably want to include +s ### Installing on Windows ### -Installing Git on Windows is very easy. The msysGit project has one of the easier installation procedures. Simply download the installer exe file from the Google Code page, and run it: +Installing Git on Windows is very easy. The msysGit project has one of the easier installation procedures. Simply download the installer exe file from the GitHub page, and run it: - http://code.google.com/p/msysgit + http://msysgit.github.com/ After it’s installed, you have both a command-line version (including an SSH client that will come in handy later) and the standard GUI. diff --git a/az/02-git-basics/01-chapter2.markdown b/az/02-git-basics/01-chapter2.markdown new file mode 100644 index 000000000..7f405674a --- /dev/null +++ b/az/02-git-basics/01-chapter2.markdown @@ -0,0 +1,1127 @@ +# Git Basics # + +If you can read only one chapter to get going with Git, this is it. This chapter covers every basic command you need to do the vast majority of the things you’ll eventually spend your time doing with Git. By the end of the chapter, you should be able to configure and initialize a repository, begin and stop tracking files, and stage and commit changes. We’ll also show you how to set up Git to ignore certain files and file patterns, how to undo mistakes quickly and easily, how to browse the history of your project and view changes between commits, and how to push and pull from remote repositories. + +## Getting a Git Repository ## + +You can get a Git project using two main approaches. The first takes an existing project or directory and imports it into Git. The second clones an existing Git repository from another server. + +### Initializing a Repository in an Existing Directory ### + +If you’re starting to track an existing project in Git, you need to go to the project’s directory and type + + $ git init + +This creates a new subdirectory named `.git` that contains all of your necessary repository files — a Git repository skeleton. At this point, nothing in your project is tracked yet. (See *Chapter 9* for more information about exactly what files are contained in the `.git` directory you just created.) + +If you want to start version-controlling existing files (as opposed to an empty directory), you should probably begin tracking those files and do an initial commit. You can accomplish that with a few `git add` commands that specify the files you want to track, followed by a commit: + + $ git add *.c + $ git add README + $ git commit -m 'initial project version' + +We’ll go over what these commands do in just a minute. At this point, you have a Git repository with tracked files and an initial commit. + +### Cloning an Existing Repository ### + +If you want to get a copy of an existing Git repository — for example, a project you’d like to contribute to — the command you need is `git clone`. If you’re familiar with other VCS systems such as Subversion, you’ll notice that the command is `clone` and not `checkout`. This is an important distinction — Git receives a copy of nearly all data that the server has. Every version of every file for the history of the project is pulled down when you run `git clone`. In fact, if your server disk gets corrupted, you can use any of the clones on any client to set the server back to the state it was in when it was cloned (you may lose some server-side hooks and such, but all the versioned data would be there — see *Chapter 4* for more details). + +You clone a repository with `git clone [url]`. For example, if you want to clone the Ruby Git library called Grit, you can do so like this: + + $ git clone git://github.com/schacon/grit.git + +That creates a directory named `grit`, initializes a `.git` directory inside it, pulls down all the data for that repository, and checks out a working copy of the latest version. If you go into the new `grit` directory, you’ll see the project files in there, ready to be worked on or used. If you want to clone the repository into a directory named something other than grit, you can specify that as the next command-line option: + + $ git clone git://github.com/schacon/grit.git mygrit + +That command does the same thing as the previous one, but the target directory is called `mygrit`. + +Git has a number of different transfer protocols you can use. The previous example uses the `git://` protocol, but you may also see `http(s)://` or `user@server:/path.git`, which uses the SSH transfer protocol. *Chapter 4* will introduce all of the available options the server can set up to access your Git repository and the pros and cons of each. + +## Recording Changes to the Repository ## + +You have a bona fide Git repository and a checkout or working copy of the files for that project. You need to make some changes and commit snapshots of those changes into your repository each time the project reaches a state you want to record. + +Remember that each file in your working directory can be in one of two states: *tracked* or *untracked*. *Tracked* files are files that were in the last snapshot; they can be *unmodified*, *modified*, or *staged*. *Untracked* files are everything else — any files in your working directory that were not in your last snapshot and are not in your staging area. When you first clone a repository, all of your files will be tracked and unmodified because you just checked them out and haven’t edited anything. + +As you edit files, Git sees them as modified, because you’ve changed them since your last commit. You *stage* these modified files and then commit all your staged changes, and the cycle repeats. This lifecycle is illustrated in Figure 2-1. + +Insert 18333fig0201.png +Figure 2-1. The lifecycle of the status of your files. + +### Checking the Status of Your Files ### + +The main tool you use to determine which files are in which state is the `git status` command. If you run this command directly after a clone, you should see something like this: + + $ git status + # On branch master + nothing to commit, working directory clean + +This means you have a clean working directory — in other words, there are no tracked and modified files. Git also doesn’t see any untracked files, or they would be listed here. Finally, the command tells you which branch you’re on. For now, that is always `master`, which is the default; you won’t worry about it here. The next chapter will go over branches and references in detail. + +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: + + $ vim README + $ git status + # On branch master + # Untracked files: + # (use "git add ..." to include in what will be committed) + # + # README + nothing added to commit but untracked files present (use "git add" to track) + +You can see that your new `README` file is untracked, because it’s under the “Untracked files” heading in your status output. Untracked basically means that Git sees a file you didn’t have in the previous snapshot (commit); Git won’t start including it in your commit snapshots until you explicitly tell it to do so. It does this so you don’t accidentally begin including generated binary files or other files that you did not mean to include. You do want to start including README, so let’s start tracking the file. + +### Tracking New Files ### + +In order to begin tracking a new file, you use the command `git add`. To begin tracking the `README` file, you can run this: + + $ git add README + +If you run your status command again, you can see that your `README` file is now tracked and staged: + + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # + +You can tell that it’s staged because it’s under the “Changes to be committed” heading. If you commit at this point, the version of the file at the time you ran `git add` is what will be in the historical snapshot. You may recall that when you ran `git init` earlier, you then ran `git add (files)` — that was to begin tracking files in your directory. The `git add` command takes a path name for either a file or a directory; if it’s a directory, the command adds all the files in that directory recursively. + +### Staging Modified Files ### + +Let’s change a file that was already tracked. If you change a previously tracked file called `benchmarks.rb` and then run your `status` command again, you get something that looks like this: + + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # + # Changes not staged for commit: + # (use "git add ..." to update what will be committed) + # + # modified: benchmarks.rb + # + +The `benchmarks.rb` file appears under a section named “Changes not staged for commit” — which means that a file that is tracked has been modified in the working directory but not yet staged. To stage it, you run the `git add` command (it’s a multipurpose command — you use it to begin tracking new files, to stage files, and to do other things like marking merge-conflicted files as resolved). Let’s run `git add` now to stage the `benchmarks.rb` file, and then run `git status` again: + + $ git add benchmarks.rb + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # modified: benchmarks.rb + # + +Both files are staged and will go into your next commit. At this point, suppose you remember one little change that you want to make in `benchmarks.rb` before you commit it. You open it again and make that change, and you’re ready to commit. However, let’s run `git status` one more time: + + $ vim benchmarks.rb + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # modified: benchmarks.rb + # + # Changes not staged for commit: + # (use "git add ..." to update what will be committed) + # + # modified: benchmarks.rb + # + +What the heck? Now `benchmarks.rb` is listed as both staged and unstaged. How is that possible? It turns out that Git stages a file exactly as it is when you run the `git add` command. If you commit now, the version of `benchmarks.rb` as it was when you last ran the `git add` command is how it will go into the commit, not the version of the file as it looks in your working directory when you run `git commit`. If you modify a file after you run `git add`, you have to run `git add` again to stage the latest version of the file: + + $ git add benchmarks.rb + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # modified: benchmarks.rb + # + +### Ignoring Files ### + +Often, you’ll have a class of files that you don’t want Git to automatically add or even show you as being untracked. These are generally automatically generated files such as log files or files produced by your build system. In such cases, you can create a file listing patterns to match them named `.gitignore`. Here is an example `.gitignore` file: + + $ cat .gitignore + *.[oa] + *~ + +The first line tells Git to ignore any files ending in `.o` or `.a` — *object* and *archive* files that may be the product of building your code. The second line tells Git to ignore all files that end with a tilde (`~`), which is used by many text editors such as Emacs to mark temporary files. You may also include a `log`, `tmp`, or `pid` directory; automatically generated documentation; and so on. Setting up a `.gitignore` file before you get going is generally a good idea so you don’t accidentally commit files that you really don’t want in your Git repository. + +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. +* 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 in the range (in this case 0 through 9) . + +Here is another example `.gitignore` file: + + # a comment - this is ignored + # no .a files + *.a + # but do track lib.a, even though you're ignoring .a files above + !lib.a + # only ignore the root TODO file, not subdir/TODO + /TODO + # ignore all files in the build/ directory + build/ + # ignore doc/notes.txt, but not doc/server/arch.txt + doc/*.txt + +### Viewing Your Staged and Unstaged Changes ### + +If the `git status` command is too vague for you — you want to know exactly what you changed, not just which files were changed — you can use the `git diff` command. We’ll cover `git diff` in more detail later; but you’ll probably use it most often to answer these two questions: What have you changed but not yet staged? And what have you staged that you are about to commit? Although `git status` answers those questions very generally, `git diff` shows you the exact lines added and removed — the patch, as it were. + +Let’s say you edit and stage the `README` file again and then edit the `benchmarks.rb` file without staging it. If you run your `status` command, you once again see something like this: + + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # + # Changes not staged for commit: + # (use "git add ..." to update what will be committed) + # + # modified: benchmarks.rb + # + +To see what you’ve changed but not yet staged, type `git diff` with no other arguments: + + $ git diff + diff --git a/benchmarks.rb b/benchmarks.rb + index 3cb747f..da65585 100644 + --- a/benchmarks.rb + +++ b/benchmarks.rb + @@ -36,6 +36,10 @@ def main + @commit.parents[0].parents[0].parents[0] + end + + + run_code(x, 'commits 1') do + + git.commits.size + + end + + + run_code(x, 'commits 2') do + log = git.commits('master', 15) + log.size + +That command compares what is in your working directory with what is in your staging area. The result tells you the changes you’ve made that you haven’t yet staged. + +If you want to see what you’ve staged that will go into your next commit, you can use `git diff --cached`. (In Git versions 1.6.1 and later, you can also use `git diff --staged`, which may be easier to remember.) This command compares your staged changes to your last commit: + + $ git diff --cached + diff --git a/README b/README + new file mode 100644 + index 0000000..03902a1 + --- /dev/null + +++ b/README2 + @@ -0,0 +1,5 @@ + +grit + + by Tom Preston-Werner, Chris Wanstrath + + http://github.com/mojombo/grit + + + +Grit is a Ruby library for extracting information from a Git repository + +It’s important to note that `git diff` by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. This can be confusing, because if you’ve staged all of your changes, `git diff` will give you no output. + +For another example, if you stage the `benchmarks.rb` file and then edit it, you can use `git diff` to see the changes in the file that are staged and the changes that are unstaged: + + $ git add benchmarks.rb + $ echo '# test line' >> benchmarks.rb + $ git status + # On branch master + # + # Changes to be committed: + # + # modified: benchmarks.rb + # + # Changes not staged for commit: + # + # modified: benchmarks.rb + # + +Now you can use `git diff` to see what is still unstaged + + $ git diff + diff --git a/benchmarks.rb b/benchmarks.rb + index e445e28..86b2f7c 100644 + --- a/benchmarks.rb + +++ b/benchmarks.rb + @@ -127,3 +127,4 @@ end + main() + + ##pp Grit::GitRuby.cache_client.stats + +# test line + +and `git diff --cached` to see what you’ve staged so far: + + $ git diff --cached + diff --git a/benchmarks.rb b/benchmarks.rb + index 3cb747f..e445e28 100644 + --- a/benchmarks.rb + +++ b/benchmarks.rb + @@ -36,6 +36,10 @@ def main + @commit.parents[0].parents[0].parents[0] + end + + + run_code(x, 'commits 1') do + + git.commits.size + + end + + + run_code(x, 'commits 2') do + log = git.commits('master', 15) + log.size + +### Committing Your Changes ### + +Now that your staging area is set up the way you want it, you can commit your changes. Remember that anything that is still unstaged — any files you have created or modified that you haven’t run `git add` on since you edited them — won’t go into this commit. They will stay as modified files on your disk. +In this case, the last time you ran `git status`, you saw that everything was staged, so you’re ready to commit your changes. The simplest way to commit is to type `git commit`: + + $ git commit + +Doing so launches your editor of choice. (This is set by your shell’s `$EDITOR` environment variable — usually vim or emacs, although you can configure it with whatever you want using the `git config --global core.editor` command as you saw in *Chapter 1*). + +The editor displays the following text (this example is a Vim screen): + + # Please enter the commit message for your changes. Lines starting + # with '#' will be ignored, and an empty message aborts the commit. + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # modified: benchmarks.rb + ~ + ~ + ~ + ".git/COMMIT_EDITMSG" 10L, 283C + +You can see that the default commit message contains the latest output of the `git status` command commented out and one empty line on top. You can remove these comments and type your commit message, or you can leave them there to help you remember what you’re committing. (For an even more explicit reminder of what you’ve modified, you can pass the `-v` option to `git commit`. Doing so also puts the diff of your change in the editor so you can see exactly what you did.) When you exit the editor, Git creates your commit with that commit message (with the comments and diff stripped out). + +Alternatively, you can type your commit message inline with the `commit` command by specifying it after a `-m` flag, like this: + + $ git commit -m "Story 182: Fix benchmarks for speed" + [master]: created 463dc4f: "Fix benchmarks for speed" + 2 files changed, 3 insertions(+), 0 deletions(-) + create mode 100644 README + +Now you’ve created your first commit! You can see that the commit has given you some output about itself: which branch you committed to (`master`), what SHA-1 checksum the commit has (`463dc4f`), how many files were changed, and statistics about lines added and removed in the commit. + +Remember that the commit records the snapshot you set up in your staging area. Anything you didn’t stage is still sitting there modified; you can do another commit to add it to your history. Every time you perform a commit, you’re recording a snapshot of your project that you can revert to or compare to later. + +### Skipping the Staging Area ### + +Although it can be amazingly useful for crafting commits exactly how you want them, the staging area is sometimes a bit more complex than you need in your workflow. If you want to skip the staging area, Git provides a simple shortcut. Providing the `-a` option to the `git commit` command makes Git automatically stage every file that is already tracked before doing the commit, letting you skip the `git add` part: + + $ git status + # On branch master + # + # Changes not staged for commit: + # + # modified: benchmarks.rb + # + $ git commit -a -m 'added new benchmarks' + [master 83e38c7] added new benchmarks + 1 files changed, 5 insertions(+), 0 deletions(-) + +Notice how you don’t have to run `git add` on the `benchmarks.rb` file in this case before you commit. + +### Removing Files ### + +To remove a file from Git, you have to remove it from your tracked files (more accurately, remove it from your staging area) and then commit. The `git rm` command does that and also removes the file from your working directory so you don’t see it as an untracked file next time around. + +If you simply remove the file from your working directory, it shows up under the “Changes not staged for commit” (that is, _unstaged_) area of your `git status` output: + + $ rm grit.gemspec + $ git status + # On branch master + # + # Changes not staged for commit: + # (use "git add/rm ..." to update what will be committed) + # + # deleted: grit.gemspec + # + +Then, if you run `git rm`, it stages the file’s removal: + + $ git rm grit.gemspec + rm 'grit.gemspec' + $ git status + # On branch master + # + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # deleted: grit.gemspec + # + +The next time you commit, the file will be gone and no longer tracked. If you modified the file and added it to the index already, you must force the removal with the `-f` option. This is a safety feature to prevent accidental removal of data that hasn’t yet been recorded in a snapshot and that can’t be recovered from Git. + +Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. In other words, you may want to keep the file on your hard drive but not have Git track it anymore. This is particularly useful if you forgot to add something to your `.gitignore` file and accidentally added it, like a large log file or a bunch of `.a` compiled files. To do this, use the `--cached` option: + + $ git rm --cached readme.txt + +You can pass files, directories, and file-glob patterns to the `git rm` command. That means you can do things such as + + $ git rm log/\*.log + +Note the backslash (`\`) in front of the `*`. This is necessary because Git does its own filename expansion in addition to your shell’s filename expansion. This command removes all files that have the `.log` extension in the `log/` directory. Or, you can do something like this: + + $ git rm \*~ + +This command removes all files that end with `~`. + +### Moving Files ### + +Unlike many other VCS systems, Git doesn’t explicitly track file movement. If you rename a file in Git, no metadata is stored in Git that tells it you renamed the file. However, Git is pretty smart about figuring that out after the fact — we’ll deal with detecting file movement a bit later. + +Thus it’s a bit confusing that Git has a `mv` command. If you want to rename a file in Git, you can run something like + + $ git mv file_from file_to + +and it works fine. In fact, if you run something like this and look at the status, you’ll see that Git considers it a renamed file: + + $ git mv README.txt README + $ git status + # On branch master + # Your branch is ahead of 'origin/master' by 1 commit. + # + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # renamed: README.txt -> README + # + +However, this is equivalent to running something like this: + + $ mv README.txt README + $ git rm README.txt + $ 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 `mv` is one command instead of three — it’s a convenience function. More important, you can use any tool you like to rename a file, and address the add/rm later, before you commit. + +## Viewing the Commit History ## + +After you have created several commits, or if you have cloned a repository with an existing commit history, you’ll probably want to look back to see what has happened. The most basic and powerful tool to do this is the `git log` command. + +These examples use a very simple project called `simplegit` that I often use for demonstrations. To get the project, run + + git clone git://github.com/schacon/simplegit-progit.git + +When you run `git log` in this project, you should get output that looks something like this: + + $ git log + commit ca82a6dff817ec66f44342007202690a93763949 + Author: Scott Chacon + Date: Mon Mar 17 21:52:11 2008 -0700 + + changed the version number + + commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 + Author: Scott Chacon + Date: Sat Mar 15 16:40:33 2008 -0700 + + removed unnecessary test code + + commit a11bef06a3f659402fe7563abf99ad00de2209e6 + Author: Scott Chacon + Date: Sat Mar 15 10:31:28 2008 -0700 + + first commit + +By default, with no arguments, `git log` lists the commits made in that repository in reverse chronological order. That is, the most recent commits show up first. As you can see, this command lists each commit with its SHA-1 checksum, the author’s name and e-mail, the date written, and the commit message. + +A huge number and variety of options to the `git log` command are available to show you exactly what you’re looking for. Here, we’ll show you some of the most-used options. + +One of the more helpful options is `-p`, which shows the diff introduced in each commit. You can also use `-2`, which limits the output to only the last two entries: + + $ git log -p -2 + commit ca82a6dff817ec66f44342007202690a93763949 + Author: Scott Chacon + Date: Mon Mar 17 21:52:11 2008 -0700 + + changed the version number + + diff --git a/Rakefile b/Rakefile + index a874b73..8f94139 100644 + --- a/Rakefile + +++ b/Rakefile + @@ -5,7 +5,7 @@ require 'rake/gempackagetask' + spec = Gem::Specification.new do |s| + - s.version = "0.1.0" + + s.version = "0.1.1" + s.author = "Scott Chacon" + + commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 + Author: Scott Chacon + Date: Sat Mar 15 16:40:33 2008 -0700 + + removed unnecessary test code + + diff --git a/lib/simplegit.rb b/lib/simplegit.rb + index a0a60ae..47c6340 100644 + --- a/lib/simplegit.rb + +++ b/lib/simplegit.rb + @@ -18,8 +18,3 @@ class SimpleGit + end + + end + - + -if $0 == __FILE__ + - git = SimpleGit.new + - puts git.show + -end + \ No newline at end of file + +This option displays the same information but with a diff directly following each entry. This is very helpful for code review or to quickly browse what happened during a series of commits that a collaborator has added. +You can also use a series of summarizing options with `git log`. For example, if you want to see some abbreviated stats for each commit, you can use the `--stat` option: + + $ git log --stat + commit ca82a6dff817ec66f44342007202690a93763949 + Author: Scott Chacon + Date: Mon Mar 17 21:52:11 2008 -0700 + + changed the version number + + Rakefile | 2 +- + 1 files changed, 1 insertions(+), 1 deletions(-) + + commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 + Author: Scott Chacon + Date: Sat Mar 15 16:40:33 2008 -0700 + + removed unnecessary test code + + lib/simplegit.rb | 5 ----- + 1 files changed, 0 insertions(+), 5 deletions(-) + + commit a11bef06a3f659402fe7563abf99ad00de2209e6 + Author: Scott Chacon + Date: Sat Mar 15 10:31:28 2008 -0700 + + first commit + + README | 6 ++++++ + Rakefile | 23 +++++++++++++++++++++++ + lib/simplegit.rb | 25 +++++++++++++++++++++++++ + 3 files changed, 54 insertions(+), 0 deletions(-) + +As you can see, the `--stat` option prints below each commit entry a list of modified files, how many files were changed, and how many lines in those files were added and removed. It also puts a summary of the information at the end. +Another really useful option is `--pretty`. This option changes the log output to formats other than the default. A few prebuilt options are available for you to use. The `oneline` option prints each commit on a single line, which is useful if you’re looking at a lot of commits. In addition, the `short`, `full`, and `fuller` options show the output in roughly the same format but with less or more information, respectively: + + $ git log --pretty=oneline + ca82a6dff817ec66f44342007202690a93763949 changed the version number + 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 removed unnecessary test code + a11bef06a3f659402fe7563abf99ad00de2209e6 first commit + +The most interesting option is `format`, which allows you to specify your own log output format. This is especially useful when you’re generating output for machine parsing — because you specify the format explicitly, you know it won’t change with updates to Git: + + $ git log --pretty=format:"%h - %an, %ar : %s" + ca82a6d - Scott Chacon, 11 months ago : changed the version number + 085bb3b - Scott Chacon, 11 months ago : removed unnecessary test code + a11bef0 - Scott Chacon, 11 months ago : first commit + +Table 2-1 lists some of the more useful options that format takes. + + Option Description of Output + %H Commit hash + %h Abbreviated commit hash + %T Tree hash + %t Abbreviated tree hash + %P Parent hashes + %p Abbreviated parent hashes + %an Author name + %ae Author e-mail + %ad Author date (format respects the --date= option) + %ar Author date, relative + %cn Committer name + %ce Committer email + %cd Committer date + %cr Committer date, relative + %s Subject + +You may be wondering what the difference is between _author_ and _committer_. The _author_ is the person who originally wrote the patch, whereas the _committer_ is the person who last applied the patch. So, if you send in a patch to a project and one of the core members applies the patch, both of you get credit — you as the author and the core member as the committer. We’ll cover this distinction a bit more in *Chapter 5*. + +The `oneline` and `format` options are particularly useful with another `log` option called `--graph`. This option adds a nice little ASCII graph showing your branch and merge history, which we can see our copy of the Grit project repository: + + $ git log --pretty=format:"%h %s" --graph + * 2d3acf9 ignore errors from SIGCHLD on trap + * 5e3ee11 Merge branch 'master' of git://github.com/dustin/grit + |\ + | * 420eac9 Added a method for getting the current branch. + * | 30e367c timeout code and tests + * | 5a09431 add timeout protection to grit + * | e1193f8 support for heads with slashes in them + |/ + * d6016bc require time for xmlschema + * 11d191e Merge branch 'defunkt' into local + +Those are only some simple output-formatting options to `git log` — there are many more. Table 2-2 lists the options we’ve covered so far and some other common formatting options that may be useful, along with how they change the output of the `log` command. + + 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. + --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. Options include oneline, short, full, fuller, and format (where you specify your own format). + +### Limiting Log Output ### + +In addition to output-formatting options, `git log` takes a number of useful limiting options — that is, options that let you show only a subset of commits. You’ve seen one such option already — the `-2` option, which show only the last two commits. In fact, you can do `-`, where `n` is any integer to show the last `n` commits. In reality, you’re unlikely to use that often, because Git by default pipes all output through a pager so you see only one page of log output at a time. + +However, the time-limiting options such as `--since` and `--until` are very useful. For example, this command gets the list of commits made in the last two weeks: + + $ git log --since=2.weeks + +This command works with lots of formats — you can specify a specific date (“2008-01-15”) or a relative date such as “2 years 1 day 3 minutes ago”. + +You can also filter the list to commits that match some search criteria. The `--author` option allows you to filter on a specific author, and the `--grep` option lets you search for keywords in the commit messages. (Note that if you want to specify both author and grep options, you have to add `--all-match` or the command will match commits with either.) + +The last really useful option to pass to `git log` as a filter is a path. If you specify a directory or file name, you can limit the log output to commits that introduced a change to those files. This is always the last option and is generally preceded by double dashes (`--`) to separate the paths from the options. + +In Table 2-3 we’ll list these and a few other common options for your reference. + + Option Description + -(n) 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. + +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 were not merges, you can run something like this: + + $ git log --pretty="%h - %s" --author=gitster --since="2008-10-01" \ + --before="2008-11-01" --no-merges -- t/ + 5610e3b - Fix testcase failure when extended attribute + acd3b9e - Enhance hold_lock_file_for_{update,append}() + f563754 - demonstrate breakage of detached checkout wi + d1a43f2 - reset --hard/read-tree --reset -u: remove un + 51a94af - Fix "checkout --track -b newbranch" on detac + b0ad11e - pull: allow "git pull origin $something:$cur + +Of the nearly 20,000 commits in the Git source code history, this command shows the 6 that match those criteria. + +### Using a GUI to Visualize History ### + +If you like to use a more graphical tool to visualize your commit history, you may want to take a look at a Tcl/Tk program called `gitk` that is distributed with Git. Gitk is basically a visual `git log` tool, and it accepts nearly all the filtering options that `git log` does. If you type `gitk` on the command line in your project, you should see something like Figure 2-2. + +Insert 18333fig0202.png +Figure 2-2. The gitk history visualizer. + +You can see the commit history in the top half of the window along with a nice ancestry graph. The diff viewer in the bottom half of the window shows you the changes introduced at any commit you click. + +## Undoing Things ## + +At any stage, you may want to undo something. Here, we’ll review a few basic tools for undoing changes that you’ve made. Be careful, because you can’t always revert some of these undos. This is one of the few areas in Git where you may lose some work if you do it wrong. + +### Changing Your Last Commit ### + +One of the common undos takes place when you commit too early and possibly forget to add some files, or you mess up your commit message. If you want to try that commit again, you can run commit with the `--amend` option: + + $ git commit --amend + +This command takes your staging area and uses it for the commit. If you’ve made no changes since your last commit (for instance, you run this command immediately after your previous commit), then your snapshot will look exactly the same and all you’ll change is your commit message. + +The same commit-message editor fires up, but it already contains the message of your previous commit. You can edit the message the same as always, but it overwrites your previous commit. + +As an example, if you commit and then realize you forgot to stage the changes in a file you wanted to add to this commit, you can do something like this: + + $ git commit -m 'initial commit' + $ git add forgotten_file + $ git commit --amend + +After these three commands, you end up with a single commit — the second commit replaces the results of the first. + +### Unstaging a Staged File ### + +The next two sections demonstrate how to wrangle your staging area and working directory changes. The nice part is that the command you use to determine the state of those two areas also reminds you how to undo changes to them. For example, let’s say you’ve changed two files and want to commit them as two separate changes, but you accidentally type `git add *` and stage them both. How can you unstage one of the two? The `git status` command reminds you: + + $ git add . + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # modified: README.txt + # modified: benchmarks.rb + # + +Right below the “Changes to be committed” text, it says "use `git reset HEAD ...` to unstage". So, let’s use that advice to unstage the `benchmarks.rb` file: + + $ git reset HEAD benchmarks.rb + benchmarks.rb: locally modified + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # modified: README.txt + # + # Changes not staged for commit: + # (use "git add ..." to update what will be committed) + # (use "git checkout -- ..." to discard changes in working directory) + # + # modified: benchmarks.rb + # + +The command is a bit strange, but it works. The `benchmarks.rb` file is modified but once again unstaged. + +### Unmodifying a Modified File ### + +What if you realize that you don’t want to keep your changes to the `benchmarks.rb` file? How can you easily unmodify it — revert it back to what it looked like when you last committed (or initially cloned, or however you got it into your working directory)? Luckily, `git status` tells you how to do that, too. In the last example output, the unstaged area looks like this: + + # Changes not staged for commit: + # (use "git add ..." to update what will be committed) + # (use "git checkout -- ..." to discard changes in working directory) + # + # modified: benchmarks.rb + # + +It tells you pretty explicitly how to discard the changes you’ve made (at least, the newer versions of Git, 1.6.1 and later, do this — if you have an older version, we highly recommend upgrading it to get some of these nicer usability features). Let’s do what it says: + + $ git checkout -- benchmarks.rb + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # modified: README.txt + # + +You can see that the changes have been reverted. You should also realize that this is a dangerous command: any changes you made to that file are gone — you just copied another file over it. Don’t ever use this command unless you absolutely know that you don’t want the file. If you just need to get it out of the way, we’ll go over stashing and branching in the next chapter; these are generally better ways to go. + +Remember, anything that is committed in Git can almost always be recovered. Even commits that were on branches that were deleted or commits that were overwritten with an `--amend` commit can be recovered (see *Chapter 9* for data recovery). However, anything you lose that was never committed is likely never to be seen again. + +## Working with Remotes ## + +To be able to collaborate on any Git project, you need to know how to manage your remote repositories. Remote repositories are versions of your project that are hosted on the Internet or network somewhere. You can have several of them, each of which generally is either read-only or read/write for you. Collaborating with others involves managing these remote repositories and pushing and pulling data to and from them when you need to share work. +Managing remote repositories includes knowing how to add remote repositories, remove remotes that are no longer valid, manage various remote branches and define them as being tracked or not, and more. In this section, we’ll cover these remote-management skills. + +### Showing Your Remotes ### + +To see which remote servers you have configured, you can run the `git remote` command. It lists the shortnames of each remote handle you’ve specified. If you’ve cloned your repository, you should at least see *origin* — that is the default name Git gives to the server you cloned from: + + $ git clone git://github.com/schacon/ticgit.git + Initialized empty Git repository in /private/tmp/ticgit/.git/ + remote: Counting objects: 595, done. + remote: Compressing objects: 100% (269/269), done. + remote: Total 595 (delta 255), reused 589 (delta 253) + Receiving objects: 100% (595/595), 73.31 KiB | 1 KiB/s, done. + Resolving deltas: 100% (255/255), done. + $ cd ticgit + $ git remote + origin + +You can also specify `-v`, which shows you the URL that Git has stored for the shortname to be expanded to: + + $ git remote -v + origin git://github.com/schacon/ticgit.git (fetch) + origin git://github.com/schacon/ticgit.git (push) + +If you have more than one remote, the command lists them all. For example, my Grit repository looks something like this. + + $ cd grit + $ git remote -v + bakkdoor git://github.com/bakkdoor/grit.git + cho45 git://github.com/cho45/grit.git + defunkt git://github.com/defunkt/grit.git + koke git://github.com/koke/grit.git + origin git@github.com:mojombo/grit.git + +This means we can pull contributions from any of these users pretty easily. But notice that only the origin remote is an SSH URL, so it’s the only one I can push to (we’ll cover why this is in *Chapter 4*). + +### Adding Remote Repositories ### + +I’ve mentioned and given some demonstrations of adding remote repositories in previous sections, but here is how to do it explicitly. To add a new remote Git repository as a shortname you can reference easily, run `git remote add [shortname] [url]`: + + $ git remote + origin + $ git remote add pb git://github.com/paulboone/ticgit.git + $ git remote -v + origin git://github.com/schacon/ticgit.git + pb git://github.com/paulboone/ticgit.git + +Now you can use the string `pb` on the command line in lieu 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: + + $ git fetch pb + remote: Counting objects: 58, done. + remote: Compressing objects: 100% (41/41), done. + remote: Total 44 (delta 24), reused 1 (delta 0) + Unpacking objects: 100% (44/44), done. + From git://github.com/paulboone/ticgit + * [new branch] master -> pb/master + * [new branch] ticgit -> pb/ticgit + +Paul’s master branch is accessible locally as `pb/master` — you can merge it into one of your branches, or you can check out a local branch at that point if you want to inspect it. + +### Fetching and Pulling from Your Remotes ### + +As you just saw, to get data from your remote projects, you can run: + + $ git fetch [remote-name] + +The command goes out to that remote project and pulls down all the data from that remote project that you don’t have yet. After you do this, you should have references to all the branches from that remote, which you can merge in or inspect at any time. (We’ll go over what branches are and how to use them in much more detail in *Chapter 3*.) + +If you clone a repository, the command automatically adds that remote repository under the name *origin*. So, `git fetch origin` fetches any new work that has been pushed to that server since you cloned (or last fetched from) it. It’s important to note that the `fetch` command pulls the data to your local repository — it doesn’t automatically merge it with any of your work or modify what you’re currently working on. You have to merge it manually into your work when you’re ready. + +If you have a branch set up to track a remote branch (see the next section and *Chapter 3* for more information), you can use the `git pull` command to automatically fetch and then merge a remote branch into your current branch. This may be an easier or more comfortable workflow for you; and by default, the `git clone` command automatically sets up your local master branch to track the remote master branch on the server you cloned from (assuming the remote has a master branch). Running `git pull` generally fetches data from the server you originally cloned from and automatically tries to merge it into the code you’re currently working on. + +### Pushing to Your Remotes ### + +When you have your project at a point that you want to share, you have to push it upstream. The command for this is simple: `git push [remote-name] [branch-name]`. If you want to push your master branch to your `origin` server (again, cloning generally sets up both of those names for you automatically), then you can run this to push your work back up to the server: + + $ git push origin master + +This command works only if you cloned from a server to which you have write access and if nobody has pushed in the meantime. If you and someone else clone at the same time and they push upstream and then you push upstream, your push will rightly be rejected. You’ll have to pull down their work first and incorporate it into yours before you’ll be allowed to push. See *Chapter 3* for more detailed information on how to push to remote servers. + +### Inspecting a Remote ### + +If you want to see more information about a particular remote, you can use the `git remote show [remote-name]` command. If you run this command with a particular shortname, such as `origin`, you get something like this: + + $ git remote show origin + * remote origin + URL: git://github.com/schacon/ticgit.git + Remote branch merged with 'git pull' while on branch master + master + Tracked remote branches + master + ticgit + +It lists the URL for the remote repository as well as the tracking branch information. The command helpfully tells you that if you’re on the master branch and you run `git pull`, it will automatically merge in the master branch on the remote after it fetches all the remote references. It also lists all the remote references it has pulled down. + +That is a simple example you’re likely to encounter. When you’re using Git more heavily, however, you may see much more information from `git remote show`: + + $ git remote show origin + * remote origin + URL: git@github.com:defunkt/github.git + Remote branch merged with 'git pull' while on branch issues + issues + Remote branch merged with 'git pull' while on branch master + master + New remote branches (next fetch will store in remotes/origin) + caching + Stale tracking branches (use 'git remote prune') + libwalker + walker2 + Tracked remote branches + acl + apiv2 + dashboard2 + issues + master + postgres + Local branch pushed with 'git push' + master:master + +This command shows which branch is automatically pushed when you run `git push` on certain branches. It also shows you which remote branches on the server you don’t yet have, which remote branches you have that have been removed from the server, and multiple branches that are automatically merged when you run `git pull`. + +### Removing and Renaming Remotes ### + +If you want to rename a reference, in newer versions of Git you can run `git remote rename` to change a remote’s shortname. For instance, if you want to rename `pb` to `paul`, you can do so with `git remote rename`: + + $ git remote rename pb paul + $ git remote + origin + paul + +It’s worth mentioning that this changes your remote branch names, too. What used to be referenced at `pb/master` is now at `paul/master`. + +If you want to remove a reference for some reason — you’ve moved the server or are no longer using a particular mirror, or perhaps a contributor isn’t contributing anymore — you can use `git remote rm`: + + $ git remote rm paul + $ git remote + origin + +## Tagging ## + +Like most VCSs, Git has the ability to tag specific points in history as being important. Generally, people use this functionality to mark release points (`v1.0`, and so on). In this section, you’ll learn how to list the available tags, how to create new tags, and what the different types of tags are. + +### Listing Your Tags ### + +Listing the available tags in Git is straightforward. Just type `git tag`: + + $ git tag + v0.1 + v1.3 + +This command lists the tags in alphabetical order; the order in which they appear has no real importance. + +You can also search for tags with a particular pattern. The Git source repo, for instance, contains more than 240 tags. If you’re only interested in looking at the 1.4.2 series, you can run this: + + $ git tag -l 'v1.4.2.*' + v1.4.2.1 + v1.4.2.2 + v1.4.2.3 + v1.4.2.4 + +### Creating Tags ### + +Git uses two main types of tags: lightweight and annotated. A lightweight tag is very much like a branch that doesn’t change — it’s just a pointer to a specific commit. Annotated tags, however, are stored as full objects in the Git database. They’re checksummed; contain the tagger name, e-mail, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG). It’s generally recommended that you create annotated tags so you can have all this information; but if you want a temporary tag or for some reason don’t want to keep the other information, lightweight tags are available too. + +### Annotated Tags ### + +Creating an annotated tag in Git is simple. The easiest way is to specify `-a` when you run the `tag` command: + + $ git tag -a v1.4 -m 'my version 1.4' + $ git tag + v0.1 + v1.3 + v1.4 + +The `-m` specifies a tagging message, which is stored with the tag. If you don’t specify a message for an annotated tag, Git launches your editor so you can type it in. + +You can see the tag data along with the commit that was tagged by using the `git show` command: + + $ git show v1.4 + tag v1.4 + Tagger: Scott Chacon + Date: Mon Feb 9 14:45:11 2009 -0800 + + my version 1.4 + commit 15027957951b64cf874c3557a0f3547bd83b3ff6 + Merge: 4a447f7... a6b4c97... + Author: Scott Chacon + Date: Sun Feb 8 19:02:46 2009 -0800 + + Merge branch 'experiment' + +That shows the tagger information, the date the commit was tagged, and the annotation message before showing the commit information. + +### Signed Tags ### + +You can also sign your tags with GPG, assuming you have a private key. All you have to do is use `-s` instead of `-a`: + + $ git tag -s v1.5 -m 'my signed 1.5 tag' + You need a passphrase to unlock the secret key for + user: "Scott Chacon " + 1024-bit DSA key, ID F721C45A, created 2009-02-09 + +If you run `git show` on that tag, you can see your GPG signature attached to it: + + $ git show v1.5 + tag v1.5 + Tagger: Scott Chacon + Date: Mon Feb 9 15:22:20 2009 -0800 + + my signed 1.5 tag + -----BEGIN PGP SIGNATURE----- + Version: GnuPG v1.4.8 (Darwin) + + iEYEABECAAYFAkmQurIACgkQON3DxfchxFr5cACeIMN+ZxLKggJQf0QYiQBwgySN + Ki0An2JeAVUCAiJ7Ox6ZEtK+NvZAj82/ + =WryJ + -----END PGP SIGNATURE----- + commit 15027957951b64cf874c3557a0f3547bd83b3ff6 + Merge: 4a447f7... a6b4c97... + Author: Scott Chacon + Date: Sun Feb 8 19:02:46 2009 -0800 + + Merge branch 'experiment' + +A bit later, you’ll learn how to verify signed tags. + +### Lightweight Tags ### + +Another way to tag commits is with a lightweight tag. This is basically the commit checksum stored in a file — no other information is kept. To create a lightweight tag, don’t supply the `-a`, `-s`, or `-m` option: + + $ git tag v1.4-lw + $ git tag + v0.1 + v1.3 + v1.4 + v1.4-lw + v1.5 + +This time, if you run `git show` on the tag, you don’t see the extra tag information. The command just shows the commit: + + $ git show v1.4-lw + commit 15027957951b64cf874c3557a0f3547bd83b3ff6 + Merge: 4a447f7... a6b4c97... + Author: Scott Chacon + Date: Sun Feb 8 19:02:46 2009 -0800 + + Merge branch 'experiment' + +### Verifying Tags ### + +To verify a signed tag, you use `git tag -v [tag-name]`. This command uses GPG to verify the signature. You need the signer’s public key in your keyring for this to work properly: + + $ git tag -v v1.4.2.1 + object 883653babd8ee7ea23e6a5c392bb739348b1eb61 + type commit + tag v1.4.2.1 + tagger Junio C Hamano 1158138501 -0700 + + GIT 1.4.2.1 + + Minor fixes since 1.4.2, including git-mv and git-http with alternates. + gpg: Signature made Wed Sep 13 02:08:25 2006 PDT using DSA key ID F3119B9A + gpg: Good signature from "Junio C Hamano " + gpg: aka "[jpeg image of size 1513]" + Primary key fingerprint: 3565 2A26 2040 E066 C9A7 4A7D C0C6 D9A4 F311 9B9A + +If you don’t have the signer’s public key, you get something like this instead: + + gpg: Signature made Wed Sep 13 02:08:25 2006 PDT using DSA key ID F3119B9A + gpg: Can't check signature: public key not found + error: could not verify the tag 'v1.4.2.1' + +### Tagging Later ### + +You can also tag commits after you’ve moved past them. Suppose your commit history looks like this: + + $ git log --pretty=oneline + 15027957951b64cf874c3557a0f3547bd83b3ff6 Merge branch 'experiment' + a6b4c97498bd301d84096da251c98a07c7723e65 beginning write support + 0d52aaab4479697da7686c15f77a3d64d9165190 one more thing + 6d52a271eda8725415634dd79daabbc4d9b6008e Merge branch 'experiment' + 0b7434d86859cc7b8c3d5e1dddfed66ff742fcbc added a commit function + 4682c3261057305bdd616e23b64b0857d832627b added a todo file + 166ae0c4d3f420721acbb115cc33848dfcc2121a started write support + 9fceb02d0ae598e95dc970b74767f19372d61af8 updated rakefile + 964f16d36dfccde844893cac5b347e7b3d44abbc commit the todo + 8a5cbc430f1a9c3d00faaeffd07798508422908a updated readme + +Now, suppose you forgot to tag the project at `v1.2`, which was at the "updated rakefile" commit. You can add it after the fact. To tag that commit, you specify the commit checksum (or part of it) at the end of the command: + + $ git tag -a v1.2 9fceb02 + +You can see that you’ve tagged the commit: + + $ git tag + v0.1 + v1.2 + v1.3 + v1.4 + v1.4-lw + v1.5 + + $ git show v1.2 + tag v1.2 + Tagger: Scott Chacon + Date: Mon Feb 9 15:32:16 2009 -0800 + + version 1.2 + commit 9fceb02d0ae598e95dc970b74767f19372d61af8 + Author: Magnus Chacon + Date: Sun Apr 27 20:43:35 2008 -0700 + + updated rakefile + ... + +### Sharing Tags ### + +By default, the `git push` command doesn’t transfer tags to remote servers. You will have to explicitly push tags to a shared server after you have created them. This process is just like sharing remote branches — you can run `git push origin [tagname]`. + + $ git push origin v1.5 + Counting objects: 50, done. + Compressing objects: 100% (38/38), done. + Writing objects: 100% (44/44), 4.56 KiB, done. + Total 44 (delta 18), reused 8 (delta 1) + To git@github.com:schacon/simplegit.git + * [new tag] v1.5 -> v1.5 + +If you have a lot of tags that you want to push up at once, you can also use the `--tags` option to the `git push` command. This will transfer all of your tags to the remote server that are not already there. + + $ git push origin --tags + Counting objects: 50, done. + Compressing objects: 100% (38/38), done. + Writing objects: 100% (44/44), 4.56 KiB, done. + Total 44 (delta 18), reused 8 (delta 1) + To git@github.com:schacon/simplegit.git + * [new tag] v0.1 -> v0.1 + * [new tag] v1.2 -> v1.2 + * [new tag] v1.4 -> v1.4 + * [new tag] v1.4-lw -> v1.4-lw + * [new tag] v1.5 -> v1.5 + +Now, when someone else clones or pulls from your repository, they will get all your tags as well. + +## Tips and Tricks ## + +Before we finish this chapter on basic Git, a few little tips and tricks may make your Git experience a bit simpler, easier, or more familiar. Many people use Git without using any of these tips, and we won’t refer to them or assume you’ve used them later in the book; but you should probably know how to do them. + +### Auto-Completion ### + +If you use the Bash shell, Git comes with a nice auto-completion script you can enable. Download the Git source code, and look in the `contrib/completion` directory; there should be a file called `git-completion.bash`. Copy this file to your home directory, and add this to your `.bashrc` file: + + source ~/.git-completion.bash + +If you want to set up Git to automatically have Bash shell completion for all users, copy this script to the `/opt/local/etc/bash_completion.d` directory on Mac systems or to the `/etc/bash_completion.d/` directory on Linux systems. This is a directory of scripts that Bash will automatically load to provide shell completions. + +If you’re using Windows with Git Bash, which is the default when installing Git on Windows with msysGit, auto-completion should be preconfigured. + +Press the Tab key when you’re writing a Git command, and it should return a set of suggestions for you to pick from: + + $ git co + commit config + +In this case, typing `git co` and then pressing the Tab key twice suggests commit and config. Adding `m` completes `git commit` automatically. + +This also works with options, which is probably more useful. For instance, if you’re running a `git log` command and can’t remember one of the options, you can start typing it and press Tab to see what matches: + + $ git log --s + --shortstat --since= --src-prefix= --stat --summary + +That’s a pretty nice trick and may save you some time and documentation reading. + +### Git Aliases ### + +Git doesn’t infer your command if you type it in partially. If you don’t want to type the entire text of each of the Git commands, you can easily set up an alias for each command using `git config`. Here are a couple of examples you may want to set up: + + $ git config --global alias.co checkout + $ git config --global alias.br branch + $ git config --global alias.ci commit + $ git config --global alias.st status + +This means that, for example, instead of typing `git commit`, you just need to type `git ci`. As you go on using Git, you’ll probably use other commands frequently as well; in this case, don’t hesitate to create new aliases. + +This technique can also be very useful in creating commands that you think should exist. For example, to correct the usability problem you encountered with unstaging a file, you can add your own unstage alias to Git: + + $ git config --global alias.unstage 'reset HEAD --' + +This makes the following two commands equivalent: + + $ git unstage fileA + $ git reset HEAD fileA + +This seems a bit clearer. It’s also common to add a `last` command, like this: + + $ git config --global alias.last 'log -1 HEAD' + +This way, you can see the last commit easily: + + $ git last + commit 66938dae3329c7aebe598c2246a8e6af90d04646 + Author: Josh Goebel + Date: Tue Aug 26 19:48:51 2008 +0800 + + test for current head + + Signed-off-by: Scott Chacon + +As you can tell, Git simply replaces the new command with whatever you alias it to. However, maybe you want to run an external command, rather than a Git subcommand. In that case, you start the command with a `!` character. This is useful if you write your own tools that work with a Git repository. We can demonstrate by aliasing `git visual` to run `gitk`: + + $ git config --global alias.visual '!gitk' + +## Summary ## + +At this point, you can do all the basic local Git operations — creating or cloning a repository, making changes, staging and committing those changes, and viewing the history of all the changes the repository has been through. Next, we’ll cover Git’s killer feature: its branching model. diff --git a/th/03-git-branching/01-chapter3.markdown b/az/03-git-branching/01-chapter3.markdown similarity index 94% rename from th/03-git-branching/01-chapter3.markdown rename to az/03-git-branching/01-chapter3.markdown index 445cdd300..75f7c859c 100644 --- a/th/03-git-branching/01-chapter3.markdown +++ b/az/03-git-branching/01-chapter3.markdown @@ -2,7 +2,7 @@ Nearly every VCS has some form of branching support. Branching means you diverge from the main line of development and continue to do work without messing with that main line. In many VCS tools, this is a somewhat expensive process, often requiring you to create a new copy of your source code directory, which can take a long time for large projects. -Some people refer to the branching model in Git as its “killer feature,” and it certainly sets Git apart in the VCS community. Why is it so special? The way Git branches is incredibly lightweight, making branching operations nearly instantaneous and switching back and forth between branches generally just as fast. Unlike many other VCSs, Git encourages a workflow that branches and merges often, even multiple times in a day. Understanding and mastering this feature gives you a powerful and unique tool and can literally change the way that you develop. +Some people refer to the branching model in Git as its “killer feature” , and it certainly sets Git apart in the VCS community. Why is it so special? The way Git branches is incredibly lightweight, making branching operations nearly instantaneous and switching back and forth between branches generally just as fast. Unlike many other VCSs, Git encourages a workflow that branches and merges often, even multiple times in a day. Understanding and mastering this feature gives you a powerful and unique tool and can literally change the way that you develop. ## What a Branch Is ## @@ -27,7 +27,7 @@ If you make some changes and commit again, the next commit stores a pointer to t Insert 18333fig0302.png Figure 3-2. Git object data for multiple commits. -A branch in Git is simply a lightweight movable pointer to one of these commits. The default branch name in Git is master. As you initially make commits, you’re given a master branch that points to the last commit you made. Every time you commit, it moves forward automatically. +A branch in Git is simply a lightweight movable pointer to one of these commits. The default branch name in Git is master. As you initially make commits, you’re given a `master` branch that points to the last commit you made. Every time you commit, it moves forward automatically. Insert 18333fig0303.png Figure 3-3. Branch pointing into the commit data’s history. @@ -65,7 +65,7 @@ Figure 3-7 illustrates the result. Insert 18333fig0307.png Figure 3-7. The branch that HEAD points to moves forward with each commit. -This is interesting, because now your testing branch has moved forward, but your master branch still points to the commit you were on when you ran `git checkout` to switch branches. Let’s switch back to the master branch: +This is interesting, because now your testing branch has moved forward, but your `master` branch still points to the commit you were on when you ran `git checkout` to switch branches. Let’s switch back to the `master` branch: $ git checkout master @@ -74,7 +74,7 @@ Figure 3-8 shows the result. Insert 18333fig0308.png Figure 3-8. HEAD moves to another branch on a checkout. -That command did two things. It moved the HEAD pointer back to point to the master branch, and it reverted the files in your working directory back to the snapshot that master points to. This also means the changes you make from this point forward will diverge from an older version of the project. It essentially rewinds the work you’ve done in your testing branch temporarily so you can go in a different direction. +That command did two things. It moved the HEAD pointer back to point to the `master` branch, and it reverted the files in your working directory back to the snapshot that `master` points to. This also means the changes you make from this point forward will diverge from an older version of the project. It essentially rewinds the work you’ve done in your testing branch temporarily so you can go in a different direction. Let’s make a few changes and commit again: @@ -96,16 +96,16 @@ Let’s see why you should do so. Let’s go through a simple example of branching and merging with a workflow that you might use in the real world. You’ll follow these steps: -1. Do work on a web site. -2. Create a branch for a new story you’re working on. -3. Do some work in that branch. +1. Do work on a web site. +2. Create a branch for a new story you’re working on. +3. Do some work in that branch. At this stage, you’ll receive a call that another issue is critical and you need a hotfix. You’ll do the following: -1. Revert back to your production branch. -2. Create a branch to add the hotfix. -3. After it’s tested, merge the hotfix branch, and push to production. -4. Switch back to your original story and continue working. +1. Revert back to your production branch. +2. Create a branch to add the hotfix. +3. After it’s tested, merge the hotfix branch, and push to production. +4. Switch back to your original story and continue working. ### Basic Branching ### @@ -233,7 +233,7 @@ Git hasn’t automatically created a new merge commit. It has paused the process [master*]$ git status index.html: needs merge # On branch master - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # (use "git checkout -- ..." to discard changes in working directory) # @@ -308,14 +308,14 @@ The `git branch` command does more than just create and delete branches. If you * master testing -Notice the `*` character that prefixes the `master` branch: it indicates the branch that you currently have checked out. This means that if you commit at this point, the `master` branch will be moved forward with your new work. To see the last commit on each branch, you can run `git branch –v`: +Notice the `*` character that prefixes the `master` branch: it indicates the branch that you currently have checked out. This means that if you commit at this point, the `master` branch will be moved forward with your new work. To see the last commit on each branch, you can run `git branch -v`: $ git branch -v iss53 93b412c fix javascript issue * master 7a98805 Merge branch 'iss53' testing 782fd34 add scott to the author list in the readmes -Another useful option to figure out what state your branches are in is to filter this list to branches that you have or have not yet merged into the branch you’re currently on. The useful `--merged` and `--no-merged` options have been available in Git since version 1.5.6 for this purpose. To see which branches are already merged into the branch you’re on, you can run `git branch –merged`: +Another useful option to figure out what state your branches are in is to filter this list to branches that you have or have not yet merged into the branch you’re currently on. The useful `--merged` and `--no-merged` options have been available in Git since version 1.5.6 for this purpose. To see which branches are already merged into the branch you’re on, you can run `git branch --merged`: $ git branch --merged iss53 @@ -403,7 +403,7 @@ To demonstrate having multiple remote servers and what remote branches for those Insert 18333fig0325.png Figure 3-25. Adding another server as a remote. -Now, you can run `git fetch teamone` to fetch everything server has that you don’t have yet. Because that server is a subset of the data your `origin` server has right now, Git fetches no data but sets a remote branch called `teamone/master` to point to the commit that `teamone` has as its `master` branch (see Figure 3-26). +Now, you can run `git fetch teamone` to fetch everything the remote `teamone` server has that you don’t have yet. Because that server is a subset of the data your `origin` server has right now, Git fetches no data but sets a remote branch called `teamone/master` to point to the commit that `teamone` has as its `master` branch (see Figure 3-26). Insert 18333fig0326.png Figure 3-26. You get a reference to teamone’s master branch position locally. @@ -446,7 +446,7 @@ This gives you a local branch that you can work on that starts where `origin/ser ### Tracking Branches ### -Checking out a local branch from a remote branch automatically creates what is called a _tracking branch_. Tracking branches are local branches that have a direct relationship to a remote branch. If you’re on a tracking branch and type git push, Git automatically knows which server and branch to push to. Also, running `git pull` while on one of these branches fetches all the remote references and then automatically merges in the corresponding remote branch. +Checking out a local branch from a remote branch automatically creates what is called a _tracking branch_. Tracking branches are local branches that have a direct relationship to a remote branch. If you’re on a tracking branch and type `git push`, Git automatically knows which server and branch to push to. Also, running `git pull` while on one of these branches fetches all the remote references and then automatically merges in the corresponding remote branch. When you clone a repository, it generally automatically creates a `master` branch that tracks `origin/master`. That’s why `git push` and `git pull` work out of the box with no other arguments. However, you can set up other tracking branches if you wish — ones that don’t track branches on `origin` and don’t track the `master` branch. The simple case is the example you just saw, running `git checkout -b [branch] [remotename]/[branch]`. If you have Git version 1.6.2 or later, you can also use the `--track` shorthand: @@ -507,7 +507,7 @@ At this point, you can go back to the master branch and do a fast-forward merge Insert 18333fig0330.png Figure 3-30. Fast-forwarding the master branch. -Now, the snapshot pointed to by C3 is exactly the same as the one that was pointed to by C5 in the merge example. There is no difference in the end product of the integration, but rebasing makes for a cleaner history. If you examine the log of a rebased branch, it looks like a linear history: it appears that all the work happened in series, even when it originally happened in parallel. +Now, the snapshot pointed to by C3' is exactly the same as the one that was pointed to by C5 in the merge example. There is no difference in the end product of the integration, but rebasing makes for a cleaner history. If you examine the log of a rebased branch, it looks like a linear history: it appears that all the work happened in series, even when it originally happened in parallel. Often, you’ll do this to make sure your commits apply cleanly on a remote branch — perhaps in a project to which you’re trying to contribute but that you don’t maintain. In this case, you’d do your work in a branch and then rebase your work onto `origin/master` when you were ready to submit your patches to the main project. That way, the maintainer doesn’t have to do any integration work — just a fast-forward or a clean apply. diff --git a/mk/04-git-server/01-chapter4.markdown b/az/04-git-server/01-chapter4.markdown similarity index 87% rename from mk/04-git-server/01-chapter4.markdown rename to az/04-git-server/01-chapter4.markdown index 0672af486..c51b6a74d 100644 --- a/mk/04-git-server/01-chapter4.markdown +++ b/az/04-git-server/01-chapter4.markdown @@ -52,9 +52,9 @@ Probably the most common transport protocol for Git is SSH. This is because SSH To clone a Git repository over SSH, you can specify ssh:// URL like this: - $ git clone ssh://user@server:project.git + $ git clone ssh://user@server/project.git -Or you can not specify a protocol — Git assumes SSH if you aren’t explicit: +Or you can use the shorter scp-like syntax for SSH protocol: $ git clone user@server:project.git @@ -70,7 +70,7 @@ The negative aspect of SSH is that you can’t serve anonymous access of your re ### The Git Protocol ### -Next is 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. In order for a repository to be served over the Git protocol, you must create the `git-export-daemon-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. You can enable push access; but given the lack of authentication, if you turn on push access, anyone on the internet who finds your project’s URL could push to your project. Suffice it to say that this is rare. +Next is 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. In order for a repository to be served over the Git protocol, you must create the `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. You can enable push access; but given the lack of authentication, if you turn on push access, anyone on the internet who finds your project’s URL could push to your project. Suffice it to say that this is rare. #### The Pros #### @@ -335,7 +335,7 @@ If you want to run the web interface on a server all the time for your team or f $ git clone git://git.kernel.org/pub/scm/git/git.git $ cd git/ $ make GITWEB_PROJECTROOT="/opt/git" \ - prefix=/usr gitweb/gitweb.cgi + prefix=/usr gitweb $ sudo cp -Rf gitweb /var/www/ Notice that you have to tell the command where to find your Git repositories with the `GITWEB_PROJECTROOT` variable. Now, you need to make Apache use CGI for that script, for which you can add a VirtualHost: @@ -369,7 +369,7 @@ Gitosis requires some Python tools, so first you have to install the Python setu Next, you clone and install Gitosis from the project’s main site: - $ git clone git://eagain.net/gitosis.git + $ git clone https://github.com/tv42/gitosis.git $ cd gitosis $ sudo python setup.py install @@ -505,46 +505,40 @@ If you have any issues, it may be useful to add `loglevel=DEBUG` under the `[git ## Gitolite ## -Git has started to become very popular in corporate environments, which tend to have some additional requirements in terms of access control. Gitolite was created to help with those requirements. +This section serves as a quick introduction to gitolite, and provides basic installation and setup instructions. It cannot, however, replace the enormous amount of [documentation][gltoc] that gitolite comes with. There may also be occasional changes to this section itself, so you may also want to look at the latest version [here][gldpg]. -Gitolite allows you to specify permissions not just by repository (like Gitosis does), but also by branch or tag names within each repository. That is, you can specify that certain people (or groups of people) can only push certain "refs" (branches or tags) but not others. +[gldpg]: http://sitaramc.github.com/gitolite/progit.html +[gltoc]: http://sitaramc.github.com/gitolite/master-toc.html -### Installing ### - -Installing Gitolite is very easy, even if you don't read the extensive documentation that comes with it. You need an account on a Unix server of some kind (various Linux flavours, and Solaris 10, have been tested), with git, perl, and an openssh compatible ssh server installed. In the examples below, we will use the `gitolite` account on a host called `gitserver`. - -Curiously, Gitolite is installed by running a script *on the workstation*, so your workstation must have a bash shell available. Even the bash that comes with msysgit will do, in case you're wondering. +Gitolite is an authorisation layer on top of git, relying on sshd or httpd for authentication. (Recap: authentication is identifying who the user is, authorisation is deciding if he is allowed to do what he is attempting to). -You start by obtaining public key based access to your server, so that you can log in from your workstation to the server without getting a password prompt. The following method works on Linux; for other workstation OSs you may have to do this manually. We assume you already had a key pair generated using `ssh-keygen`. +Gitolite allows you to specify permissions not just by repository, but also by branch or tag names within each repository. That is, you can specify that certain people (or groups of people) can only push certain "refs" (branches or tags) but not others. - $ ssh-copy-id -i ~/.ssh/id_rsa gitolite@gitserver - -This will ask you for the password to the gitolite account, and then set up public key access. This is **essential** for the install script, so check to make sure you can run a command without getting a password prompt: +### Installing ### - $ ssh gitolite@gitserver pwd - /home/gitolite +Installing Gitolite is very easy, even if you don't read the extensive documentation that comes with it. You need an account on a Unix server of some kind. You do not need root access, assuming git, perl, and an openssh compatible ssh server are already installed. In the examples below, we will use the `git` account on a host called `gitserver`. -Next, you clone Gitolite from the project's main site and run the "easy install" script (the third argument is your name as you would like it to appear in the resulting gitolite-admin repository): +Gitolite is somewhat unusual as far as "server" software goes -- access is via ssh, and so every userid on the server is a potential "gitolite host". We will describe the simplest install method in this article; for the other methods please see the documentation. - $ git clone git://github.com/sitaramc/gitolite - $ cd gitolite/src - $ ./gl-easy-install -q gitolite gitserver sitaram +To begin, create a user called `git` on your server and login to this user. Copy your ssh pubkey (a file called `~/.ssh/id_rsa.pub` if you did a plain `ssh-keygen` with all the defaults) from your workstation, renaming it to `YourName.pub`. Then run these commands: -And you're done! Gitolite has now been installed on the server, and you now have a brand new repository called `gitolite-admin` in the home directory of your workstation. You administer your gitolite setup by making changes to this repository and pushing (just like Gitosis). + git clone git://github.com/sitaramc/gitolite + gitolite/install -ln + # assumes $HOME/bin exists and is in your $PATH + gitolite setup -pk $HOME/YourName.pub + # for example, I would run 'gitolite setup -pk $HOME/sitaram.pub' -[By the way, *upgrading* gitolite is also done the same way. Also, if you're interested, run the script without any arguments to get a usage message.] +Finally, back on your workstation, run `git clone git@server:gitolite-admin`. -That last command does produce a fair amount of output, which might be interesting to read. Also, the first time you run this, a new keypair is created; you will have to choose a passphrase or hit enter for none. Why a second keypair is needed, and how it is used, is explained in the "ssh troubleshooting" document that comes with Gitolite. (Hey the documentation has to be good for *something*!) +And you're done! Gitolite has now been installed on the server, and you now have a brand new repository called `gitolite-admin` in your workstation. You administer your gitolite setup by making changes to this repository and pushing. ### Customising the Install ### -While the default, quick, install works for most people, there are some ways to customise the install if you need to. Firstly, there are two other branches that you may be interested in installing, instead of "master". The "wildrepos" branch allows you to specify repositories by wildcards (regular expressions) in the configuration file; an extremely powerful feature that we will not be covering in this article. And if your server side git is older than 1.5.6 or so, you should use the "oldgits" branch. - -Finally, if you omit the `-q` argument, you get a "verbose" mode install -- detailed information on what the install is doing at each step. The verbose mode also allows you to change certain server-side parameters, such as the location of the actual repositories, by editing an "rc" file that the server uses. This "rc" file is liberally commented so you should be able to make any changes you need quite easily, save it, and continue. +While the default, quick, install works for most people, there are some ways to customise the install if you need to. Some changes can be made simply by editing the rc file, but if that is not sufficient, there's documentation on customising gitolite. ### Config File and Access Control Rules ### -So once the install is done, you switch to the `gitolite-admin` repository (placed in your HOME directory) and poke around to see what you got: +Once the install is done, you switch to the `gitolite-admin` clone you just made on your workstation, and poke around to see what you got: $ cd ~/gitolite-admin/ $ ls @@ -553,8 +547,6 @@ So once the install is done, you switch to the `gitolite-admin` repository (plac conf/gitolite.conf keydir/sitaram.pub $ cat conf/gitolite.conf - #gitolite conf - # please see conf/example.conf for details on syntax and features repo gitolite-admin RW+ = sitaram @@ -562,9 +554,11 @@ So once the install is done, you switch to the `gitolite-admin` repository (plac repo testing RW+ = @all -Notice that "sitaram" (the last argument in the `gl-easy-install` command you gave earlier) has read-write permissions on the `gitolite-admin` repository as well as a public key file of the same name. +Notice that "sitaram" (the name of the pubkey in the gl-setup command you used earlier) has read-write permissions on the `gitolite-admin` repository as well as a public key file of the same name. -The config file syntax for Gitolite is *quite* different from Gitosis. Again, this is liberally documented in `conf/example.conf`, so we'll only mention some highlights here. +Adding users is easy. To add a user called "alice", obtain her public key, name it "alice.pub", and put it in the "keydir" directory of the clone of the gitolite-admin repo you just made on your workstation. Add, commit, and push the change, and the user has been added. + +The config file syntax for gitolite is well documented, so we'll only mention some highlights here. You can group users or repos for convenience. The group names are just like macros; when defining them, it doesn't even matter whether they are projects or users; that distinction is only made when you *use* the "macro". @@ -597,53 +591,68 @@ That rule will just get added to the ruleset for the `gitolite` repository. At this point you might be wondering how the access control rules are actually applied, so let's go over that briefly. -There are two levels of access control in gitolite. The first is at the repository level; if you have read (or write) access to *any* ref in the repository, then you have read (or write) access to the repository. This is the only access control that Gitosis had. +There are two levels of access control in gitolite. The first is at the repository level; if you have read (or write) access to *any* ref in the repository, then you have read (or write) access to the repository. The second level, applicable only to "write" access, is by branch or tag within a repository. The username, the access being attempted (`W` or `+`), and the refname being updated are known. The access rules are checked in order of appearance in the config file, looking for a match for this combination (but remember that the refname is regex-matched, not merely string-matched). If a match is found, the push succeeds. A fallthrough results in access being denied. -### Advanced Access Control -- "deny" rules ### +### Advanced Access Control with "deny" rules ### -As you can see, permissions can be one of `R`, `RW`, or `RW+`. There is another permission available: `-`, standing for "deny". This gives you a lot more power, at the expense of some complexity, because now fallthrough is not the *only* way for access to be denied, and so the *order of the rules now matters*! +So far, we've only seen permissions to be one of `R`, `RW`, or `RW+`. However, gitolite allows another permission: `-`, standing for "deny". This gives you a lot more power, at the expense of some complexity, because now fallthrough is not the *only* way for access to be denied, so the *order of the rules now matters*! -Let us say, in the situation above, we want engineers to be able to rewind any branch *except* master and integ. Here's how: +Let us say, in the situation above, we want engineers to be able to rewind any branch *except* master and integ. Here's how to do that: RW master integ = @engineers - master integ = @engineers RW+ = @engineers -Again, you simply follow the rules top down until you hit a match for your access mode, *or* a deny. Non-rewind push to master or integ is allowed by the first rule. A rewind push to those refs does not match the first rule, drops down to the second, and is therefore denied. Any push (rewind or non-rewind) to refs other than master or integ won't match the first two rules anyway, and the third rule allows it. - -If that sounds complicated, you may want to play with it to increase your understanding. Also, most of the time you don't need "deny" rules anyway, so you can choose to just avoid them if you prefer. +Again, you simply follow the rules top down until you hit a match for your access mode, or a deny. Non-rewind push to master or integ is allowed by the first rule. A rewind push to those refs does not match the first rule, drops down to the second, and is therefore denied. Any push (rewind or non-rewind) to refs other than master or integ won't match the first two rules anyway, and the third rule allows it. -### Other Features ### +### Restricting pushes by files changed ### -We'll round off this discussion with a bunch of other features, all of which are described in great detail in the "faqs, tips, etc" document. +In addition to restricting what branches a user can push changes to, you can also restrict what files they are allowed to touch. For example, perhaps the Makefile (or some other program) is really not supposed to be changed by just anyone, because a lot of things depend on it or would break if the changes are not done *just right*. You can tell gitolite: -Gitolite logs all successful accesses. If you were somewhat relaxed about giving people rewind permissions (`RW+`) and some kid blew away "master", the log file is a life saver, in terms of easily and quickly finding the SHA that got hosed. + repo foo + RW = @junior_devs @senior_devs -One extremely useful convenience feature in gitolite is support for git installed outside the normal `$PATH` (this is more common than you think; some corporate environments or even some hosting providers refuse to install things system-wide and you end up putting them in your own directories). Normally, you are forced to make the *client-side* git aware of this non-standard location of the git binaries in some way. With gitolite, just choose a verbose install and set `$GIT_PATH` in the "rc" files. No client-side changes are required after that :-) + - VREF/NAME/Makefile = @junior_devs -Another convenient feature is what happens when you try and just ssh to the server. Older versions of gitolite used to complain about the `SSH_ORIGINAL_COMMAND` environment variable being empty (see the ssh documentation if interested). Now Gitolite comes up with something like this: +User who are migrating from the older gitolite should note that there is a significant change in behaviour with regard to this feature; please see the migration guide for details. - hello sitaram, the gitolite version here is v0.90-9-g91e1e9f - you have the following permissions: - R anu-wsd - R entrans - R W git-notes - R W gitolite - R W gitolite-admin - R indic_web_input - R shreelipi_converter +### Personal Branches ### -For really large installations, you can delegate responsibility for groups of repositories to various people and have them manage those pieces independently. This reduces the load on the main admin, and makes him less of a bottleneck. This feature has its own documentation file in the `doc/` directory. - -Finally, Gitolite also has a feature called "personal branches" (or rather, "personal branch namespace") that can be very useful in a corporate environment. +Gitolite also has a feature called "personal branches" (or rather, "personal branch namespace") that can be very useful in a corporate environment. A lot of code exchange in the git world happens by "please pull" requests. In a corporate environment, however, unauthenticated access is a no-no, and a developer workstation cannot do authentication, so you have to push to the central server and ask someone to pull from there. This would normally cause the same branch name clutter as in a centralised VCS, plus setting up permissions for this becomes a chore for the admin. -Gitolite lets you define a "personal" or "scratch" namespace prefix for each developer (for example, `refs/personal//*`), with full permissions for that dev only, and read access for everyone else. Just choose a verbose install and set the `$PERSONAL` variable in the "rc" file to `refs/personal`. That's all; it's pretty much fire and forget as far as the admin is concerned, even if there is constant churn in the project team composition. +Gitolite lets you define a "personal" or "scratch" namespace prefix for each developer (for example, `refs/personal//*`); please see the documentation for details. + +### "Wildcard" repositories ### + +Gitolite allows you to specify repositories with wildcards (actually perl regexes), like, for example `assignments/s[0-9][0-9]/a[0-9][0-9]`, to pick a random example. It allows you to assign a new permission mode ("C") which allows users to create repositories based on such wild cards, automatically assigns ownership to the specific user who created it, allows him/her to hand out R and RW permissions to other users to collaborate, etc. Again, please see the documentation for details. + +### Other Features ### + +We'll round off this discussion with a sampling of other features, all of which, and many more, are described in great detail in the documentation. + +**Logging**: Gitolite logs all successful accesses. If you were somewhat relaxed about giving people rewind permissions (`RW+`) and some kid blew away "master", the log file is a life saver, in terms of easily and quickly finding the SHA that got hosed. + +**Access rights reporting**: Another convenient feature is what happens when you try and just ssh to the server. Gitolite shows you what repos you have access to, and what that access may be. Here's an example: + + hello sitaram, this is git@git running gitolite3 v3.01-18-g9609868 on git 1.7.4.4 + + R anu-wsd + R entrans + R W git-notes + R W gitolite + R W gitolite-admin + R indic_web_input + R shreelipi_converter + +**Delegation**: For really large installations, you can delegate responsibility for groups of repositories to various people and have them manage those pieces independently. This reduces the load on the main admin, and makes him less of a bottleneck. + +**Mirroring**: Gitolite can help you maintain multiple mirrors, and switch between them easily if the primary server goes down. ## Git Daemon ## @@ -672,7 +681,7 @@ you put this script: /opt/git/ respawn -For security reasons, it is strongly encouraged to have this daemon run as a user with read-only permissions to the repositories – you can easily do this by creating a new user 'git-ro' and running the daemon as them. For the sake of simplicity we’ll simply run it as the same 'git' user that Gitosis is running as. +For security reasons, it is strongly encouraged to have this daemon run as a user with read-only permissions to the repositories — you can easily do this by creating a new user 'git-ro' and running the daemon as them. For the sake of simplicity we’ll simply run it as the same 'git' user that Gitosis is running as. When you restart your machine, your Git daemon will start automatically and respawn if it goes down. To get it running without having to reboot, you can run this: @@ -713,9 +722,9 @@ Now, if you commit and push the project, GitWeb will automatically start showing 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. -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: +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 following page: - http://git.or.cz/gitwiki/GitHosting + https://git.wiki.kernel.org/index.php/GitHosting Because we can’t cover all of them, and because I happen to work at one of them, we’ll use this section to walk through setting up an account and creating a new project at GitHub. This will give you an idea of what is involved. @@ -729,7 +738,7 @@ GitHub is also a commercial company that charges for accounts that maintain priv ### Setting Up a User Account ### -The first thing you need to do is set up a free user account. If you visit the Pricing and Signup page at `http://github.com/plans` and click the "Sign Up" button on the Free account (see figure 4-2), you’re taken to the signup page. +The first thing you need to do is set up a free user account. If you visit the "Plans and pricing" page at `https://github.com/pricing` and click the "Sign Up" button on the Free account (see figure 4-2), you’re taken to the signup page. Insert 18333fig0402.png Figure 4-2. The GitHub plan page. diff --git a/th/05-distributed-git/01-chapter5.markdown b/az/05-distributed-git/01-chapter5.markdown similarity index 95% rename from th/05-distributed-git/01-chapter5.markdown rename to az/05-distributed-git/01-chapter5.markdown index 78bd49dd0..f86238665 100644 --- a/th/05-distributed-git/01-chapter5.markdown +++ b/az/05-distributed-git/01-chapter5.markdown @@ -12,7 +12,7 @@ Unlike Centralized Version Control Systems (CVCSs), the distributed nature of Gi In centralized systems, there is generally a single collaboration model—the centralized workflow. One central hub, or repository, can accept code, and everyone synchronizes their work to it. A number of developers are nodes — consumers of that hub — and synchronize to that one place (see Figure 5-1). -Insert 18333fig0501.png +Insert 18333fig0501.png Figure 5-1. Centralized workflow. This means that if two developers clone from the hub and both make changes, the first developer to push their changes back up can do so with no problems. The second developer must merge in the first one’s work before pushing changes up, so as not to overwrite the first developer’s changes. This concept is true in Git as it is in Subversion (or any CVCS), and this model works perfectly in Git. @@ -24,14 +24,14 @@ This workflow is attractive to a lot of people because it’s a paradigm that ma Because Git allows you to have multiple remote repositories, it’s possible to have a workflow where each developer has write access to their own public repository and read access to everyone else’s. This scenario often includes a canonical repository that represents the "official" project. To contribute to that project, you create your own public clone of the project and push your changes to it. Then, you can send a request to the maintainer of the main project to pull in your changes. They can add your repository as a remote, test your changes locally, merge them into their branch, and push back to their repository. The process works as follow (see Figure 5-2): -1. The project maintainer pushes to their public repository. -2. A contributor clones that repository and makes changes. -3. The contributor pushes to their own public copy. -4. The contributor sends the maintainer an e-mail asking them to pull changes. -5. The maintainer adds the contributor’s repo as a remote and merges locally. -6. The maintainer pushes merged changes to the main repository. +1. The project maintainer pushes to their public repository. +2. A contributor clones that repository and makes changes. +3. The contributor pushes to their own public copy. +4. The contributor sends the maintainer an e-mail asking them to pull changes. +5. The maintainer adds the contributor’s repo as a remote and merges locally. +6. The maintainer pushes merged changes to the main repository. -Insert 18333fig0502.png +Insert 18333fig0502.png Figure 5-2. Integration-manager workflow. This is a very common workflow with sites like GitHub, where it’s easy to fork a project and push your changes into your fork for everyone to see. One of the main advantages of this approach is that you can continue to work, and the maintainer of the main repository can pull in your changes at any time. Contributors don’t have to wait for the project to incorporate their changes — each party can work at their own pace. @@ -40,12 +40,12 @@ This is a very common workflow with sites like GitHub, where it’s easy to fork This is a variant of a multiple-repository workflow. It’s generally used by huge projects with hundreds of collaborators; one famous example is the Linux kernel. Various integration managers are in charge of certain parts of the repository; they’re called lieutenants. All the lieutenants have one integration manager known as the benevolent dictator. The benevolent dictator’s repository serves as the reference repository from which all the collaborators need to pull. The process works like this (see Figure 5-3): -1. Regular developers work on their topic branch and rebase their work on top of master. The master branch is that of the dictator. -2. Lieutenants merge the developers’ topic branches into their master branch. -3. The dictator merges the lieutenants’ master branches into the dictator’s master branch. -4. The dictator pushes their master to the reference repository so the other developers can rebase on it. +1. Regular developers work on their topic branch and rebase their work on top of master. The master branch is that of the dictator. +2. Lieutenants merge the developers’ topic branches into their master branch. +3. The dictator merges the lieutenants’ master branches into the dictator’s master branch. +4. The dictator pushes their master to the reference repository so the other developers can rebase on it. -Insert 18333fig0503.png +Insert 18333fig0503.png Figure 5-3. Benevolent dictator workflow. This kind of workflow isn’t common but can be useful in very big projects or in highly hierarchical environments, because as it allows the project leader (the dictator) to delegate much of the work and collect large subsets of code at multiple points before integrating them. @@ -119,7 +119,7 @@ Let’s see what it might look like when two developers start to work together w Initialized empty Git repository in /home/john/simplegit/.git/ ... $ cd simplegit/ - $ vim lib/simplegit.rb + $ vim lib/simplegit.rb $ git commit -am 'removed invalid default value' [master 738ee87] removed invalid default value 1 files changed, 1 insertions(+), 1 deletions(-) @@ -131,7 +131,7 @@ The second developer, Jessica, does the same thing — clones the repository and Initialized empty Git repository in /home/jessica/simplegit/.git/ ... $ cd simplegit/ - $ vim TODO + $ vim TODO $ git commit -am 'add reset task' [master fbff5bc] add reset task 1 files changed, 1 insertions(+), 0 deletions(-) @@ -161,7 +161,7 @@ John isn’t allowed to push because Jessica has pushed in the meantime. This is At this point, John’s local repository looks something like Figure 5-4. -Insert 18333fig0504.png +Insert 18333fig0504.png Figure 5-4. John’s initial repository. John has a reference to the changes Jessica pushed up, but he has to merge them into his own work before he is allowed to push: @@ -173,7 +173,7 @@ John has a reference to the changes Jessica pushed up, but he has to merge them The merge goes smoothly — John’s commit history now looks like Figure 5-5. -Insert 18333fig0505.png +Insert 18333fig0505.png Figure 5-5. John’s repository after merging origin/master. Now, John can test his code to make sure it still works properly, and then he can push his new merged work up to the server: @@ -185,12 +185,12 @@ Now, John can test his code to make sure it still works properly, and then he ca Finally, John’s commit history looks like Figure 5-6. -Insert 18333fig0506.png +Insert 18333fig0506.png Figure 5-6. John’s history after pushing to the origin server. In the meantime, Jessica has been working on a topic branch. She’s created a topic branch called `issue54` and done three commits on that branch. She hasn’t fetched John’s changes yet, so her commit history looks like Figure 5-7. -Insert 18333fig0507.png +Insert 18333fig0507.png Figure 5-7. Jessica’s initial commit history. Jessica wants to sync up with John, so she fetches: @@ -203,7 +203,7 @@ Jessica wants to sync up with John, so she fetches: That pulls down the work John has pushed up in the meantime. Jessica’s history now looks like Figure 5-8. -Insert 18333fig0508.png +Insert 18333fig0508.png Figure 5-8. Jessica’s history after fetching John’s changes. Jessica thinks her topic branch is ready, but she wants to know what she has to merge her work into so that she can push. She runs `git log` to find out: @@ -230,7 +230,7 @@ She can merge either `origin/master` or `issue54` first — they’re both upstr lib/simplegit.rb | 6 +++++- 2 files changed, 6 insertions(+), 1 deletions(-) -No problems occur; as you can see it, was a simple fast-forward. Now Jessica merges in John’s work (`origin/master`): +No problems occur; as you can see it was a simple fast-forward. Now Jessica merges in John’s work (`origin/master`): $ git merge origin/master Auto-merging lib/simplegit.rb @@ -240,7 +240,7 @@ No problems occur; as you can see it, was a simple fast-forward. Now Jessica mer Everything merges cleanly, and Jessica’s history looks like Figure 5-9. -Insert 18333fig0509.png +Insert 18333fig0509.png Figure 5-9. Jessica’s history after merging John’s changes. Now `origin/master` is reachable from Jessica’s `master` branch, so she should be able to successfully push (assuming John hasn’t pushed again in the meantime): @@ -252,12 +252,12 @@ Now `origin/master` is reachable from Jessica’s `master` branch, so she should Each developer has committed a few times and merged each other’s work successfully; see Figure 5-10. -Insert 18333fig0510.png +Insert 18333fig0510.png Figure 5-10. Jessica’s history after pushing all changes back to the server. That is one of the simplest workflows. You work for a while, generally in a topic branch, and merge into your master branch when it’s ready to be integrated. When you want to share that work, you merge it into your own master branch, then fetch and merge `origin/master` if it has changed, and finally push to the `master` branch on the server. The general sequence is something like that shown in Figure 5-11. -Insert 18333fig0511.png +Insert 18333fig0511.png Figure 5-11. General sequence of events for a simple multiple-developer Git workflow. ### Private Managed Team ### @@ -303,7 +303,7 @@ Now, Jessica makes a couple of commits on the `featureB` branch: Jessica’s repository looks like Figure 5-12. -Insert 18333fig0512.png +Insert 18333fig0512.png Figure 5-12. Jessica’s initial commit history. She’s ready to push up her work, but gets an e-mail from Josie that a branch with some initial work on it was already pushed to the server as `featureBee`. Jessica first needs to merge those changes in with her own before she can push to the server. She can then fetch Josie’s changes down with `git fetch`: @@ -359,26 +359,26 @@ Finally, she merges John’s work into her own `featureA` branch: Jessica wants to tweak something, so she commits again and then pushes this back up to the server: $ git commit -am 'small tweak' - [featureA ed774b3] small tweak + [featureA 774b3ed] small tweak 1 files changed, 1 insertions(+), 1 deletions(-) $ git push origin featureA ... To jessica@githost:simplegit.git - 3300904..ed774b3 featureA -> featureA + 3300904..774b3ed featureA -> featureA Jessica’s commit history now looks something like Figure 5-13. -Insert 18333fig0513.png +Insert 18333fig0513.png Figure 5-13. Jessica’s history after committing on a feature branch. Jessica, Josie, and John inform the integrators that the `featureA` and `featureBee` branches on the server are ready for integration into the mainline. After they integrate these branches into the mainline, a fetch will bring down the new merge commits, making the commit history look like Figure 5-14. -Insert 18333fig0514.png +Insert 18333fig0514.png Figure 5-14. Jessica’s history after merging both her topic branches. Many groups switch to Git because of this ability to have multiple teams working in parallel, merging the different lines of work late in the process. The ability of smaller subgroups of a team to collaborate via remote branches without necessarily having to involve or impede the entire team is a huge benefit of Git. The sequence for the workflow you saw here is something like Figure 5-15. -Insert 18333fig0515.png +Insert 18333fig0515.png Figure 5-15. Basic sequence of this managed-team workflow. ### Public Small Project ### @@ -438,21 +438,21 @@ On a project for which you’re not the maintainer, it’s generally easier to h Now, each of your topics is contained within a silo — similar to a patch queue — that you can rewrite, rebase, and modify without the topics interfering or interdepending on each other as in Figure 5-16. -Insert 18333fig0516.png +Insert 18333fig0516.png Figure 5-16. Initial commit history with featureB work. Let’s say the project maintainer has pulled in a bunch of other patches and tried your first branch, but it no longer cleanly merges. In this case, you can try to rebase that branch on top of `origin/master`, resolve the conflicts for the maintainer, and then resubmit your changes: $ git checkout featureA $ git rebase origin/master - $ git push –f myfork featureA + $ git push -f myfork featureA This rewrites your history to now look like Figure 5-17. -Insert 18333fig0517.png +Insert 18333fig0517.png Figure 5-17. Commit history after featureA work. -Because you rebased the branch, you have to specify the `–f` to your push command in order to be able to replace the `featureA` branch on the server with a commit that isn’t a descendant of it. An alternative would be to push this new work to a different branch on the server (perhaps called `featureAv2`). +Because you rebased the branch, you have to specify the `-f` to your push command in order to be able to replace the `featureA` branch on the server with a commit that isn’t a descendant of it. An alternative would be to push this new work to a different branch on the server (perhaps called `featureAv2`). Let’s look at one more possible scenario: the maintainer has looked at work in your second branch and likes the concept but would like you to change an implementation detail. You’ll also take this opportunity to move the work to be based off the project’s current `master` branch. You start a new branch based off the current `origin/master` branch, squash the `featureB` changes there, resolve any conflicts, make the implementation change, and then push that up as a new branch: @@ -466,7 +466,7 @@ The `--squash` option takes all the work on the merged branch and squashes it in Now you can send the maintainer a message that you’ve made the requested changes and they can find those changes in your `featureBv2` branch (see Figure 5-18). -Insert 18333fig0518.png +Insert 18333fig0518.png Figure 5-18. Commit history after featureBv2 work. ### Public Large Project ### @@ -481,7 +481,7 @@ The workflow is similar to the previous use case — you create topic branches f $ (work) $ git commit -Now you have two commits that you want to send to the mailing list. You use `git format-patch` to generate the mbox-formatted files that you can e-mail to the list — it turns each commit into an e-mail message with the first line of the commit message as the subject and the rest of the message plus the patch that the commit introduces as the body. The nice thing about this is that applying a patch from an e-mail generated with `format-patch` preserves all the commit information properly, as you’ll see more of in the next section when you apply these commits: +Now you have two commits that you want to send to the mailing list. You use `git format-patch` to generate the mbox-formatted files that you can e-mail to the list — it turns each commit into an e-mail message with the first line of the commit message as the subject and the rest of the message plus the patch that the commit introduces as the body. The nice thing about this is that applying a patch from an e-mail generated with `format-patch` preserves all the commit information properly, as you’ll see more of in the next section when you apply these patches: $ git format-patch -M origin/master 0001-add-limit-to-log-function.patch @@ -489,7 +489,7 @@ Now you have two commits that you want to send to the mailing list. You use `git The `format-patch` command prints out the names of the patch files it creates. The `-M` switch tells Git to look for renames. The files end up looking like this: - $ cat 0001-add-limit-to-log-function.patch + $ cat 0001-add-limit-to-log-function.patch From 330090432754092d704da8e76ca5c05c198e71a8 Mon Sep 17 00:00:00 2001 From: Jessica Smith Date: Sun, 6 Apr 2008 10:17:23 -0700 @@ -514,10 +514,10 @@ The `format-patch` command prints out the names of the patch files it creates. T end def ls_tree(treeish = 'master') - -- + -- 1.6.2.rc1.20.g8c5b.dirty -You can also edit these patch files to add more information for the e-mail list that you don’t want to show up in the commit message. If you add text between the `--` line and the beginning of the patch (the `lib/simplegit.rb` line), then developers can read it; but applying the patch excludes it. +You can also edit these patch files to add more information for the e-mail list that you don’t want to show up in the commit message. If you add text between the `---` line and the beginning of the patch (the `lib/simplegit.rb` line), then developers can read it; but applying the patch excludes it. To e-mail this to a mailing list, you can either paste the file into your e-mail program or send it via a command-line program. Pasting the text often causes formatting issues, especially with "smarter" clients that don’t preserve newlines and other whitespace appropriately. Luckily, Git provides a tool to help you send properly formatted patches via IMAP, which may be easier for you. I’ll demonstrate how to send a patch via Gmail, which happens to be the e-mail agent I use; you can read detailed instructions for a number of mail programs at the end of the aforementioned `Documentation/SubmittingPatches` file in the Git source code. @@ -537,14 +537,14 @@ When that is set up, you can use `git send-email` to place the patch series in t $ git send-email *.patch 0001-added-limit-to-log-function.patch 0002-changed-log-output-to-30-from-25.patch - Who should the emails appear to be from? [Jessica Smith ] + Who should the emails appear to be from? [Jessica Smith ] Emails will be sent from: Jessica Smith Who should the emails be sent to? jessica@example.com Message-ID to be used as In-Reply-To for the first email? y Then, Git spits out a bunch of log information looking something like this for each patch you’re sending: - (mbox) Adding cc: Jessica Smith from + (mbox) Adding cc: Jessica Smith from \line 'From: Jessica Smith ' OK. Log says: Sendmail: /usr/sbin/sendmail -i jessica@example.com @@ -571,12 +571,12 @@ In addition to knowing how to effectively contribute to a project, you’ll like ### Working in Topic Branches ### -When you’re thinking of integrating new work, it’s generally a good idea to try it out in a topic branch — a temporary branch specifically made to try out that new work. This way, it’s easy to tweak a patch individually and leave it if it’s not working until you have time to come back to it. If you create a simple branch name based on the theme of the work you’re going to try, such as `ruby_client` or something similarly descriptive, you can easily remember it if you have to abandon it for a while and come back later. The maintainer of the Git project tends to namespace these branches as well — such as `sc/ruby_client`, where `sc` is short for the person who contributed the work. +When you’re thinking of integrating new work, it’s generally a good idea to try it out in a topic branch — a temporary branch specifically made to try out that new work. This way, it’s easy to tweak a patch individually and leave it if it’s not working until you have time to come back to it. If you create a simple branch name based on the theme of the work you’re going to try, such as `ruby_client` or something similarly descriptive, you can easily remember it if you have to abandon it for a while and come back later. The maintainer of the Git project tends to namespace these branches as well — such as `sc/ruby_client`, where `sc` is short for the person who contributed the work. As you’ll remember, you can create the branch based off your master branch like this: $ git branch sc/ruby_client master -Or, if you want to also switch to it immediately, you can use the `checkout -b` option: +Or, if you want to also switch to it immediately, you can use the `checkout -b` command: $ git checkout -b sc/ruby_client master @@ -596,7 +596,7 @@ This modifies the files in your working directory. It’s almost identical to ru You can also use git apply to see if a patch applies cleanly before you try actually applying it — you can run `git apply --check` with the patch: - $ git apply --check 0001-seeing-if-this-helps-the-gem.patch + $ git apply --check 0001-seeing-if-this-helps-the-gem.patch error: patch failed: ticgit.gemspec:1 error: ticgit.gemspec: patch does not apply @@ -615,11 +615,11 @@ To apply a patch generated by `format-patch`, you use `git am`. Technically, `gi Limit log functionality to the first 20 -This is the beginning of the output of the format-patch command that you saw in the previous section. This is also a valid mbox e-mail format. If someone has e-mailed you the patch properly using git send-email, and you download that into an mbox format, then you can point git am to that mbox file, and it will start applying all the patches it sees. If you run a mail client that can save several e-mails out in mbox format, you can save entire patch series into a file and then use git am to apply them one at a time. +This is the beginning of the output of the format-patch command that you saw in the previous section. This is also a valid mbox e-mail format. If someone has e-mailed you the patch properly using git send-email, and you download that into an mbox format, then you can point git am to that mbox file, and it will start applying all the patches it sees. If you run a mail client that can save several e-mails out in mbox format, you can save entire patch series into a file and then use git am to apply them one at a time. However, if someone uploaded a patch file generated via `format-patch` to a ticketing system or something similar, you can save the file locally and then pass that file saved on your disk to `git am` to apply it: - $ git am 0001-limit-log-function.patch + $ git am 0001-limit-log-function.patch Applying: add limit to log function You can see that it applied cleanly and automatically created the new commit for you. The author information is taken from the e-mail’s `From` and `Date` headers, and the message of the commit is taken from the `Subject` and body (before the patch) of the e-mail. For example, if this patch was applied from the mbox example I just showed, the commit generated would look something like this: @@ -635,11 +635,11 @@ You can see that it applied cleanly and automatically created the new commit for Limit log functionality to the first 20 -The `Commit` information indicates the person who applied the patch and the time it was applied. The `Author` information is the individual who originally created the patch and when it was originally created. +The `Commit` information indicates the person who applied the patch and the time it was applied. The `Author` information is the individual who originally created the patch and when it was originally created. But it’s possible that the patch won’t apply cleanly. Perhaps your main branch has diverged too far from the branch the patch was built from, or the patch depends on another patch you haven’t applied yet. In that case, the `git am` process will fail and ask you what you want to do: - $ git am 0001-seeing-if-this-helps-the-gem.patch + $ git am 0001-seeing-if-this-helps-the-gem.patch Applying: seeing if this helps the gem error: patch failed: ticgit.gemspec:1 error: ticgit.gemspec: patch does not apply @@ -651,13 +651,13 @@ But it’s possible that the patch won’t apply cleanly. Perhaps your main bran This command puts conflict markers in any files it has issues with, much like a conflicted merge or rebase operation. You solve this issue much the same way — edit the file to resolve the conflict, stage the new file, and then run `git am --resolved` to continue to the next patch: $ (fix the file) - $ git add ticgit.gemspec + $ git add ticgit.gemspec $ git am --resolved Applying: seeing if this helps the gem If you want Git to try a bit more intelligently to resolve the conflict, you can pass a `-3` option to it, which makes Git attempt a three-way merge. This option isn’t on by default because it doesn’t work if the commit the patch says it was based on isn’t in your repository. If you do have that commit — if the patch was based on a public commit — then the `-3` option is generally much smarter about applying a conflicting patch: - $ git am -3 0001-seeing-if-this-helps-the-gem.patch + $ git am -3 0001-seeing-if-this-helps-the-gem.patch Applying: seeing if this helps the gem error: patch failed: ticgit.gemspec:1 error: ticgit.gemspec: patch does not apply @@ -674,7 +674,7 @@ If you’re applying a number of patches from an mbox, you can also run the `am` -------------------------- seeing if this helps the gem -------------------------- - Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all + Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all This is nice if you have a number of patches saved, because you can view the patch first if you don’t remember what it is, or not apply the patch if you’ve already done so. @@ -738,7 +738,7 @@ Technically, you can do that by explicitly figuring out the common ancestor and $ git merge-base contrib master 36c7dba2c95e6bbb78dfa822519ecfec6e1ca649 - $ git diff 36c7db + $ git diff 36c7db However, that isn’t convenient, so Git provides another shorthand for doing the same thing: the triple-dot syntax. In the context of the `diff` command, you can put three periods after another branch to do a `diff` between the last commit of the branch you’re on and its common ancestor with another branch: @@ -754,7 +754,7 @@ When all the work in your topic branch is ready to be integrated into a more mai One simple workflow merges your work into your `master` branch. In this scenario, you have a `master` branch that contains basically stable code. When you have work in a topic branch that you’ve done or that someone has contributed and you’ve verified, you merge it into your master branch, delete the topic branch, and then continue the process. If we have a repository with work in two branches named `ruby_client` and `php_client` that looks like Figure 5-19 and merge `ruby_client` first and then `php_client` next, then your history will end up looking like Figure 5-20. -Insert 18333fig0519.png +Insert 18333fig0519.png Figure 5-19. History with several topic branches. Insert 18333fig0520.png @@ -764,13 +764,13 @@ That is probably the simplest workflow, but it’s problematic if you’re deali If you have more developers or a larger project, you’ll probably want to use at least a two-phase merge cycle. In this scenario, you have two long-running branches, `master` and `develop`, in which you determine that `master` is updated only when a very stable release is cut and all new code is integrated into the `develop` branch. You regularly push both of these branches to the public repository. Each time you have a new topic branch to merge in (Figure 5-21), you merge it into `develop` (Figure 5-22); then, when you tag a release, you fast-forward `master` to wherever the now-stable `develop` branch is (Figure 5-23). -Insert 18333fig0521.png +Insert 18333fig0521.png Figure 5-21. Before a topic branch merge. -Insert 18333fig0522.png +Insert 18333fig0522.png Figure 5-22. After a topic branch merge. -Insert 18333fig0523.png +Insert 18333fig0523.png Figure 5-23. After a topic branch 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 stuff. @@ -780,12 +780,12 @@ You can also continue this concept, having an integrate branch where all the wor The Git project has four long-running branches: `master`, `next`, and `pu` (proposed updates) for new work, and `maint` for maintenance backports. When new work is introduced by contributors, it’s collected into topic branches in the maintainer’s repository in a manner similar to what I’ve described (see Figure 5-24). At this point, the topics are evaluated to determine whether they’re safe and ready for consumption or whether they need more work. If they’re safe, they’re merged into `next`, and that branch is pushed up so everyone can try the topics integrated together. -Insert 18333fig0524.png +Insert 18333fig0524.png Figure 5-24. Managing a complex series of parallel contributed topic branches. If the topics still need work, they’re merged into `pu` instead. When it’s determined that they’re totally stable, the topics are re-merged into `master` and are then rebuilt from the topics that were in `next` but didn’t yet graduate to `master`. This means `master` almost always moves forward, `next` is rebased occasionally, and `pu` is rebased even more often (see Figure 5-25). -Insert 18333fig0525.png +Insert 18333fig0525.png Figure 5-25. Merging contributed topic branches into long-term integration branches. When a topic branch has finally been merged into `master`, it’s removed from the repository. 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. @@ -796,7 +796,7 @@ Other maintainers prefer to rebase or cherry-pick contributed work on top of the The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like Figure 5-26. -Insert 18333fig0526.png +Insert 18333fig0526.png Figure 5-26. Example history before a cherry pick. If you want to pull commit `e43a6` into your master branch, you can run @@ -808,7 +808,7 @@ If you want to pull commit `e43a6` into your master branch, you can run This pulls the same change introduced in `e43a6`, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like Figure 5-27. -Insert 18333fig0527.png +Insert 18333fig0527.png Figure 5-27. History after cherry-picking a commit on a topic branch. Now you can remove your topic branch and drop the commits you didn’t want to pull in. diff --git a/ar/06-git-tools/01-chapter6.markdown b/az/06-git-tools/01-chapter6.markdown similarity index 98% rename from ar/06-git-tools/01-chapter6.markdown rename to az/06-git-tools/01-chapter6.markdown index 696bc28b9..ccf9797c0 100644 --- a/ar/06-git-tools/01-chapter6.markdown +++ b/az/06-git-tools/01-chapter6.markdown @@ -57,9 +57,9 @@ Generally, eight to ten characters are more than enough to be unique within a pr A lot of people become concerned at some point that they will, by random happenstance, have two objects in their repository that hash to the same SHA-1 value. What then? -If you do happen to commit an object that hashes to the same SHA-1 value as a previous object in your repository, GIt will see the previous object already in your Git database and assume it was already written. If you try to check out that object again at some point, you’ll always get the data of the first object. +If you do happen to commit an object that hashes to the same SHA-1 value as a previous object in your repository, Git will see the previous object already in your Git database and assume it was already written. If you try to check out that object again at some point, you’ll always get the data of the first object. -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. That’s 1,200 times the number of grains of sand on the earth. +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. 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 (1 million Git objects) and pushing it into one enormous Git repository, it would take 5 years until that repository contained enough objects to have a 50% probability of a single SHA-1 object collision. 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. @@ -422,7 +422,7 @@ To demonstrate, you’ll go into your project and start working on a couple of f # # modified: index.html # - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # # modified: lib/simplegit.rb @@ -440,7 +440,7 @@ Your working directory is clean: $ git status # On branch master - nothing to commit (working directory clean) + nothing to commit, working directory clean At this point, you can easily switch branches and do work elsewhere; your changes are stored on your stack. To see which stashes you’ve stored, you can use `git stash list`: @@ -453,7 +453,7 @@ In this case, two stashes were done previously, so you have access to three diff $ git stash apply # On branch master - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # # modified: index.html @@ -471,7 +471,7 @@ The changes to your files were reapplied, but the file you staged before wasn’ # # modified: index.html # - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # # modified: lib/simplegit.rb @@ -490,7 +490,7 @@ You can also run `git stash pop` to apply the stash and then immediately drop it ### Un-applying a Stash ### -In some use case scenarios you might want to apply stashed changes, do some work, but then un-apply those changes that originally came form the stash. Git does not provide such a `stash unapply` command, but it is possible to achieve the effect by simply retrieving the patch associated with a stash and applying it in reverse: +In some use case scenarios you might want to apply stashed changes, do some work, but then un-apply those changes that originally came from the stash. Git does not provide such a `stash unapply` command, but it is possible to achieve the effect by simply retrieving the patch associated with a stash and applying it in reverse: $ git stash show -p stash@{0} | git apply -R @@ -501,7 +501,7 @@ Again, if you don’t specify a stash, Git assumes the most recent stash: You may want to create an alias and effectively add a `stash-unapply` command to your git. For example: $ git config --global alias.stash-unapply '!git stash show -p | git apply -R' - $ git stash + $ git stash apply $ #... work work work $ git stash-unapply @@ -517,7 +517,7 @@ If you stash some work, leave it there for a while, and continue on the branch f # # modified: index.html # - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # # modified: lib/simplegit.rb @@ -625,7 +625,7 @@ to this: 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. -### Squashing a Commit ### +### 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. The script puts helpful instructions in the rebase message: @@ -700,7 +700,7 @@ This occurs fairly commonly. Someone accidentally commits a huge binary file wit Rewrite 6b9b3cf04e7c5686a9cb838c3f36a8cb6a0fc2bd (21/21) Ref 'refs/heads/master' was rewritten -The `--tree-filter` option runs the specified command after each checkout of the project and then recommits the results. In this case, you remove a file called passwords.txt from every snapshot, whether it exists or not. If you want to remove all accidentally committed editor backup files, you can run something like `git filter-branch --tree-filter 'rm -f *~' HEAD`. +The `--tree-filter` option runs the specified command after each checkout of the project and then recommits the results. In this case, you remove a file called passwords.txt from every snapshot, whether it exists or not. If you want to remove all accidentally committed editor backup files, you can run something like `git filter-branch --tree-filter "find * -type f -name '*~' -delete" HEAD`. You’ll be able to watch Git rewriting trees and commits and then move the branch pointer at the end. It’s generally a good idea to do this in a testing branch and then hard-reset your master branch after you’ve determined the outcome is what you really want. To run `filter-branch` on all your branches, you can pass `--all` to the command. @@ -941,7 +941,7 @@ Now your `rack` subdirectory is at the exact state it was in when you committed 1 files changed, 1 insertions(+), 1 deletions(-) [master*]$ git status # On branch master - # Changed but not updated: + # Changes not staged for commit: # (use "git add ..." to update what will be committed) # (use "git checkout -- ..." to discard changes in working directory) # @@ -997,7 +997,7 @@ A good way to do this in Git is to make each of the subfolders a separate Git re ### Issues with Submodules ### -Using submodules isn’t without hiccups, however. First, you must be relatively careful when working in the submodule directory. When you run `git submodule update`, it checks out the specific version of the project, but not within a branch. This is called having a detached head — it means the HEAD file points directly to a commit, not to a symbolic reference. The issue is that you generally don’t want to work in a detached head environment, because it’s easy to lose changes. If you do an initial `submodule update`, commit in that submodule directory without creating a branch to work in, and then run `git submodule update` again from the superproject without committing in the meantime, Git will overwrite your changes without telling you. Technically you won’t lose the work, but you won’t have a branch pointing to it, so it will be somewhat difficult to retrieve. +Using submodules isn’t without hiccups, however. First, you must be relatively careful when working in the submodule directory. When you run `git submodule update`, it checks out the specific version of the project, but not within a branch. This is called having a detached HEAD — it means the HEAD file points directly to a commit, not to a symbolic reference. The issue is that you generally don’t want to work in a detached HEAD environment, because it’s easy to lose changes. If you do an initial `submodule update`, commit in that submodule directory without creating a branch to work in, and then run `git submodule update` again from the superproject without committing in the meantime, Git will overwrite your changes without telling you. Technically you won’t lose the work, but you won’t have a branch pointing to it, so it will be somewhat difficult to retrieve. To avoid this issue, create a branch when you work in a submodule directory with `git checkout -b work` or something equivalent. When you do the submodule update a second time, it will still revert your work, but at least you have a pointer to get back to. @@ -1095,7 +1095,7 @@ Now you have the root of the Rack project in your `rack_branch` branch and your $ ls README -You want to pull the Rack project into your `master` project as a subdirectory. You can do that in Git with `git read-tree`. You’ll learn more about `read-tree` and its friends in Chapter 9, but for now know that it reads the root tree of one branch into your current staging area and working directory. You just switched back to your `master` branch, and you pull the `rack` branch into the `rack` subdirectory of your `master` branch of your main project: +You want to pull the Rack project into your `master` project as a subdirectory. You can do that in Git with `git read-tree`. You’ll learn more about `read-tree` and its friends in Chapter 9, but for now know that it reads the root tree of one branch into your current staging area and working directory. You just switched back to your `master` branch, and you pull the `rack_branch` branch into the `rack` subdirectory of your `master` branch of your main project: $ git read-tree --prefix=rack/ -u rack_branch diff --git a/ar/07-customizing-git/01-chapter7.markdown b/az/07-customizing-git/01-chapter7.markdown similarity index 93% rename from ar/07-customizing-git/01-chapter7.markdown rename to az/07-customizing-git/01-chapter7.markdown index 528e88b11..c2bb85fc1 100644 --- a/ar/07-customizing-git/01-chapter7.markdown +++ b/az/07-customizing-git/01-chapter7.markdown @@ -75,7 +75,7 @@ The core.pager setting determines what pager is used when Git pages output such $ 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 page the entire output of all commands, no matter how long it is. #### user.signingkey #### @@ -136,13 +136,13 @@ See the `git config` manpage for all the subsettings you can configure, if you w ### External Merge and Diff Tools ### -Although Git has an internal implementation of diff, which is what you’ve been using, you can set up an external tool instead. You can also set up a graphical merge conflict–resolution tool instead of having to resolve conflicts manually. I’ll demonstrate setting up the Perforce Visual Merge Tool (P4Merge) to do your diffs and merge resolutions, because it’s a nice graphical tool and it’s free. +Although Git has an internal implementation of diff, which is what you’ve been using, you can set up an external tool instead. You can also set up a graphical merge conflict-resolution tool instead of having to resolve conflicts manually. I’ll demonstrate setting up the Perforce Visual Merge Tool (P4Merge) to do your diffs and merge resolutions, because it’s a nice graphical tool and it’s free. If you want to try this out, P4Merge works on all major platforms, so you should be able to do so. I’ll use path names in the examples that work on Mac and Linux systems; for Windows, you’ll have to change `/usr/local/bin` to an executable path in your environment. You can download P4Merge here: - http://www.perforce.com/perforce/downloads/component.html + http://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools To begin, you’ll set up external wrapper scripts to run your commands. I’ll use the Mac 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: @@ -178,7 +178,7 @@ or you can edit your `~/.gitconfig` file to add these lines: [merge] tool = extMerge [mergetool "extMerge"] - cmd = extMerge "$BASE" "$LOCAL" "$REMOTE" "$MERGED" + cmd = extMerge \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\" trustExitCode = false [diff] external = extDiff @@ -251,7 +251,7 @@ Or you can have Git try to automatically fix the issue before applying the patch $ git apply --whitespace=fix -These options apply to the git rebase option as well. If you’ve committed whitespace issues but haven’t yet pushed upstream, you can run a `rebase` with the `--whitespace=fix` option to have Git automatically fix whitespace issues as it’s rewriting the patches. +These options apply to the `git rebase` command as well. If you’ve committed whitespace issues but haven’t yet pushed upstream, you can run a `rebase` with the `--whitespace=fix` option to have Git automatically fix whitespace issues as it’s rewriting the patches. ### Server Configuration ### @@ -309,6 +309,8 @@ Now, Git won’t try to convert or fix CRLF issues; nor will it try to compute o In the 1.6 series of Git, you can use the Git attributes functionality to effectively diff binary files. You do this by telling Git how to convert your binary data to a text format that can be compared via the normal diff. +##### MS Word files ##### + Because this is a pretty cool and not widely known feature, I’ll go over a few examples. First, you’ll use this technique to solve one of the most annoying problems known to humanity: version-controlling Word documents. Everyone knows that Word is the most horrific editor around; but, oddly, everyone 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: $ git diff @@ -324,6 +326,13 @@ This tells Git that any file that matches this pattern (.doc) should use the "wo $ git config diff.word.textconv strings +This command adds a section to your `.git/config` that looks like this: + + [diff "word"] + textconv = strings + +Side note: There are different kinds of `.doc` files. Some use an UTF-16 encoding or other "codepages" and `strings` won't find anything useful in there. Your mileage may vary. + Now Git knows that if it tries to do a diff between two snapshots, and any of the files end in `.doc`, it should run those files through the "word" filter, which is defined as the `strings` program. This effectively makes nice text-based versions of your Word files before attempting to diff them. Here’s an example. I put Chapter 1 of this book into Git, added some text to a paragraph, and saved the document. Then, I ran `git diff` to see what changed: @@ -343,7 +352,60 @@ Here’s an example. I put Chapter 1 of this book into Git, added some text to a Git successfully and succinctly tells me that I added the string "Let’s see if this works", which is correct. It’s not perfect — it adds a bunch of random stuff at the end — but it certainly works. If you can find or write a Word-to-plain-text converter that works well enough, that solution will likely be incredibly effective. However, `strings` is available on most Mac and Linux systems, so it may be a good first try to do this with many binary formats. -Another interesting problem you can solve this way involves diffing image files. One way to do this is to run JPEG files through a filter that extracts their EXIF information — metadata that is recorded with most image formats. If you download and install the `exiftool` program, you can use it to convert your images into text about the metadata, so at least the diff will show you a textual representation of any changes that happened: +##### OpenDocument Text files ##### + +The same approach that we used for MS Word files (`*.doc`) can be used for OpenDocument Text files (`*.odt`) created by OpenOffice.org. + +Add the following line to your `.gitattributes` file: + + *.odt diff=odt + +Now set up the `odt` diff filter in `.git/config`: + + [diff "odt"] + binary = true + textconv = /usr/local/bin/odt-to-txt + +OpenDocument files are actually zip'ped directories containing multiple files (the content in an XML format, stylesheets, images, etc.). We'll need to write a script to extract the content and return it as plain text. Create a file `/usr/local/bin/odt-to-txt` (you are free to put it into a different directory) with the following content: + + #! /usr/bin/env perl + # Simplistic OpenDocument Text (.odt) to plain text converter. + # Author: Philipp Kempgen + + if (! defined($ARGV[0])) { + print STDERR "No filename given!\n"; + print STDERR "Usage: $0 filename\n"; + exit 1; + } + + my $content = ''; + open my $fh, '-|', 'unzip', '-qq', '-p', $ARGV[0], 'content.xml' or die $!; + { + local $/ = undef; # slurp mode + $content = <$fh>; + } + close $fh; + $_ = $content; + s/]*>//g; # remove spans + s/]*>/\n\n***** /g; # headers + s/]*>\s*]*>/\n -- /g; # list items + s/]*>/\n\n/g; # lists + s/]*>/\n /g; # paragraphs + s/<[^>]+>//g; # remove all XML tags + s/\n{2,}/\n\n/g; # remove multiple blank lines + s/\A\n+//; # remove leading blank lines + print "\n", $_, "\n\n"; + +And make it executable + + chmod +x /usr/local/bin/odt-to-txt + +Now `git diff` will be able to tell you what changed in `.odt` files. + + +##### Image files ##### + +Another interesting problem you can solve this way involves diffing image files. One way to do this is to run PNG files through a filter that extracts their EXIF information — metadata that is recorded with most image formats. If you download and install the `exiftool` program, you can use it to convert your images into text about the metadata, so at least the diff will show you a textual representation of any changes that happened: $ echo '*.png diff=exif' >> .gitattributes $ git config diff.exif.textconv exiftool @@ -382,14 +444,14 @@ First, you can inject the SHA-1 checksum of a blob into an `$Id$` field in the f The next time you check out this file, Git injects the SHA of the blob: - $ rm text.txt - $ git checkout -- text.txt + $ rm test.txt + $ git checkout -- test.txt $ cat test.txt $Id: 42812b7653c7b88933f8a9d6cad0ca16714b9bb3 $ However, that result is of limited use. If you’ve used keyword substitution in CVS or Subversion, you can include a datestamp — the SHA isn’t all that helpful, because it’s fairly random and you can’t tell if one SHA is older or newer than another. -It turns out that you can write your own filters for doing substitutions in files on commit/checkout. These are the "clean" and "smudge" filters. In the `.gitattributes` file, you can set a filter for particular paths and then set up scripts that will process files just before they’re committed ("clean", see Figure 7-2) and just before they’re checked out ("smudge", see Figure 7-3). These filters can be set to do all sorts of fun things. +It turns out that you can write your own filters for doing substitutions in files on commit/checkout. These are the "clean" and "smudge" filters. In the `.gitattributes` file, you can set a filter for particular paths and then set up scripts that will process files just before they’re checked out ("smudge", see Figure 7-2) and just before they’re committed ("clean", see Figure 7-3). These filters can be set to do all sorts of fun things. Insert 18333fig0702.png Figure 7-2. The “smudge” filter is run on checkout. @@ -401,7 +463,7 @@ The original commit message for this functionality gives a simple example of run *.c filter=indent -Then, tell Git what the "indent"" filter does on smudge and clean: +Then, tell Git what the "indent" filter does on smudge and clean: $ git config --global filter.indent.clean indent $ git config --global filter.indent.smudge cat @@ -492,7 +554,7 @@ To enable a hook script, put a file in the `hooks` subdirectory of your Git dire ### Client-Side Hooks ### -There are a lot of client-side hooks. This section splits them into committing-workflow hooks, e-mail–workflow scripts, and the rest of the client-side scripts. +There are a lot of client-side hooks. This section splits them into committing-workflow hooks, e-mail-workflow scripts, and the rest of the client-side scripts. #### Committing-Workflow Hooks #### @@ -508,7 +570,7 @@ The committing-workflow client-side scripts can be used in just about any workfl #### E-mail Workflow Hooks #### -You can set up three client-side hooks for an e-mail–based workflow. They’re all invoked by the `git am` command, so if you aren’t using that command in your workflow, you can safely skip to the next section. If you’re taking patches over e-mail prepared by `git format-patch`, then some of these may be helpful to you. +You can set up three client-side hooks for an e-mail-based workflow. They’re all invoked by the `git am` command, so if you aren’t using that command in your workflow, you can safely skip to the next section. If you’re taking patches over e-mail prepared by `git format-patch`, then some of these may be helpful to you. The first hook that is run is `applypatch-msg`. It takes a single argument: the name of the temporary file that contains the proposed commit message. Git aborts the patch if this script exits non-zero. You can use this to make sure a commit message is properly formatted or to normalize the message by having the script edit it in place. @@ -672,8 +734,8 @@ If you use the ACL structure returned from the `get_acl_access_data` method and next if path.size == 0 has_file_access = false access[$user].each do |access_path| - if !access_path # user has access to everything - || (path.index(access_path) == 0) # access to this path + if !access_path || # user has access to everything + (path.index(access_path) == 0) # access to this path has_file_access = true end end @@ -709,7 +771,7 @@ The logic for checking this is to see if any commits are reachable from the olde check_fast_forward -Everything is set up. If you run `chmod u+x .git/hooks/update`, which is the file you into which you should have put all this code, and then try to push a non-fast-forwarded reference, you get something like this: +Everything is set up. If you run `chmod u+x .git/hooks/update`, which is the file into which you should have put all this code, and then try to push a non-fast-forward reference, you'll get something like this: $ git push -f origin master Counting objects: 5, done. @@ -719,7 +781,7 @@ Everything is set up. If you run `chmod u+x .git/hooks/update`, which is the fil Unpacking objects: 100% (3/3), done. Enforcing Policies... (refs/heads/master) (8338c5) (c5b616) - [POLICY] Cannot push a non-fast-forward reference + [POLICY] Cannot push a non fast-forward reference error: hooks/update exited with error code 1 error: hook declined to update refs/heads/master To git@gitserver:project.git @@ -729,7 +791,7 @@ Everything is set up. If you run `chmod u+x .git/hooks/update`, which is the fil There are a couple of interesting things here. First, you see this where the hook starts running. Enforcing Policies... - (refs/heads/master) (fb8c72) (c56860) + (refs/heads/master) (8338c5) (c5b616) Notice that you printed that out to stdout at the very beginning of your update script. It’s important to note that anything your script prints to stdout will be transferred to the client. diff --git a/th/08-git-and-other-scms/01-chapter8.markdown b/az/08-git-and-other-scms/01-chapter8.markdown similarity index 98% rename from th/08-git-and-other-scms/01-chapter8.markdown rename to az/08-git-and-other-scms/01-chapter8.markdown index f9abf256b..e21879ba3 100644 --- a/th/08-git-and-other-scms/01-chapter8.markdown +++ b/az/08-git-and-other-scms/01-chapter8.markdown @@ -20,7 +20,7 @@ Don’t rewrite your history and try to push again, and don’t push to a parall ### Setting Up ### -To demonstrate this functionality, you need a typical SVN repository that you have write access to. If you want to copy these examples, you’ll have to make a writeable copy of my test repository. In order to do that easily, you can use a tool called `svnsync` that comes with more recent versions of Subversion — it should be distributed with at least 1.4. For these tests, I created a new Subversion repository on Google code that was a partial copy of the `protobuf` project, which is a tool that encodes structured data for network transmission. +To demonstrate this functionality, you need a typical SVN repository that you have write access to. If you want to copy these examples, you’ll have to make a writeable copy of my test repository. In order to do that easily, you can use a tool called `svnsync` that comes with more recent versions of Subversion — it should be distributed with at least 1.4. For these tests, I created a new Subversion repository on SourceForge that was a partial copy of the `protobuf` project, which is a tool that encodes structured data for network transmission. To follow along, you first need to create a new local Subversion repository: @@ -362,7 +362,8 @@ However, the import isn’t perfect; and because it will take so long, you may a To get a list of the author names that SVN uses, you can run this: - $ svn log --xml | grep author | sort -u | perl -pe 's/.>(.?)<./$1 = /' + $ svn log ^/ --xml | grep -P "^(.*?)<\/author>/$1 = /' > users.txt That gives you the log output in XML format — you can look for the authors, create a unique list, and then strip out the XML. (Obviously this only works on a machine with `grep`, `sort`, and `perl` installed.) Then, redirect that output into your users.txt file so you can add the equivalent Git user data next to each entry. @@ -405,7 +406,11 @@ Next, move the rest of the references under `refs/remotes` to be local branches: $ cp -Rf .git/refs/remotes/* .git/refs/heads/ $ rm -Rf .git/refs/remotes -Now all the old branches are real Git branches and all the old tags are real Git tags. The last thing to do is add your new Git server as a remote and push to it. Because you want all your branches and tags to go up, you can run this: +Now all the old branches are real Git branches and all the old tags are real Git tags. The last thing to do is add your new Git server as a remote and push to it. Here is an example of adding your server as a remote: + + $ git remote add origin git@my-git-server:myrepository.git + +Because you want all your branches and tags to go up, you can now run this: $ git push origin --all @@ -597,7 +602,7 @@ The last thing you need to do is to return the current mark so it can be passed return mark -NOTE: If you are running on Windows you'll need to make sure that you add one extra step. As metioned before, Windows uses CRLF for new line characters while git fast-import expects only LF. To get around this problem and make git fast-import happy, you need to tell ruby to use LF instead of CRLF: +NOTE: If you are running on Windows you'll need to make sure that you add one extra step. As mentioned before, Windows uses CRLF for new line characters while git fast-import expects only LF. To get around this problem and make git fast-import happy, you need to tell ruby to use LF instead of CRLF: $stdout.binmode diff --git a/mk/09-git-internals/01-chapter9.markdown b/az/09-git-internals/01-chapter9.markdown similarity index 99% rename from mk/09-git-internals/01-chapter9.markdown rename to az/09-git-internals/01-chapter9.markdown index 917e1c170..2ee361578 100644 --- a/mk/09-git-internals/01-chapter9.markdown +++ b/az/09-git-internals/01-chapter9.markdown @@ -27,7 +27,7 @@ When you run `git init` in a new or existing directory, Git creates the `.git` d objects/ refs/ -You may see some other files in there, but this is a fresh `git init` repository — it’s what you see by default. The `branches` directory isn’t used by newer Git versions, and the `description` file is only used by the GitWeb program, so don’t worry about those. The `config` file contains your project-specific configuration options, and the `info` directory keeps a global exclude file for ignored patterns that you don’t want to track in a .gitignore file. The `hooks` directory contains your client- or server-side hook scripts, which are discussed in detail in Chapter 6. +You may see some other files in there, but this is a fresh `git init` repository — it’s what you see by default. The `branches` directory isn’t used by newer Git versions, and the `description` file is only used by the GitWeb program, so don’t worry about those. The `config` file contains your project-specific configuration options, and the `info` directory keeps a global exclude file for ignored patterns that you don’t want to track in a .gitignore file. The `hooks` directory contains your client- or server-side hook scripts, which are discussed in detail in Chapter 7. This leaves four important entries: the `HEAD` and `index` files and the `objects` and `refs` directories. These are the core parts of Git. The `objects` directory stores all the content for your database, the `refs` directory stores pointers into commit objects in that data (branches), the `HEAD` file points to the branch you currently have checked out, and the `index` file is where Git stores your staging area information. You’ll now look at each of these sections in detail to see how Git operates. @@ -371,7 +371,7 @@ As discussed in Chapter 2, there are two types of tags: annotated and lightweigh That is all a lightweight tag is — a branch that never moves. An annotated tag is more complex, however. If you create an annotated tag, Git creates a tag object and then writes a reference to point to it rather than directly to the commit. You can see this by creating an annotated tag (`-a` specifies that it’s an annotated tag): - $ git tag -a v1.1 1a410efbd13591db07496601ebc7a059dd55cfe9 –m 'test tag' + $ git tag -a v1.1 1a410efbd13591db07496601ebc7a059dd55cfe9 -m 'test tag' Here’s the object SHA-1 value it created: @@ -392,7 +392,7 @@ Notice that the object entry points to the commit SHA-1 value that you tagged. A $ git cat-file blob junio-gpg-pub -in the Git source code. The Linux kernel also has a non-commit-pointing tag object — the first tag created points to the initial tree of the import of the source code. +in the Git source code repository. The Linux kernel repository also has a non-commit-pointing tag object — the first tag created points to the initial tree of the import of the source code. ### Remotes ### @@ -510,9 +510,9 @@ How does Git do this? When Git packs objects, it looks for files that are named 484a59275031909e19aadb7c92262719cfcdf19a commit 226 153 169 83baae61804e65cc73a7201a7252750c76066a30 blob 10 19 5362 9585191f37f7b0fb9444f35a9bf50de191beadc2 tag 136 127 5476 - 9bc1dc421dcd51b4ac296e3e5b6e2a99cf44391e blob 7 18 5193 1 - 05408d195263d853f09dca71d55116663690c27c \ - ab1afef80fac8e34258ff41fc1b867c702daa24b commit 232 157 12 + 9bc1dc421dcd51b4ac296e3e5b6e2a99cf44391e blob 7 18 5193 1 \ + 05408d195263d853f09dca71d55116663690c27c + ab1afef80fac8e34258ff41fc1b867c702daa24b commit 232 157 12 cac0cab538b970a37ea1e769cbbde608743bc96d commit 226 154 473 d8329fc1cc938780ffdd9f94e0d364e0ea74f579 tree 36 46 5316 e3f094f522629ae358806b17daf78246c27c007b blob 1486 734 4352 @@ -857,7 +857,7 @@ It looks like the bottom commit is the one you lost, so you can recover it by cr Cool — now you have a branch named `recover-branch` that is where your `master` branch used to be, making the first two commits reachable again. Next, suppose your loss was for some reason not in the reflog — you can simulate that by removing `recover-branch` and deleting the reflog. Now the first two commits aren’t reachable by anything: - $ git branch –D recover-branch + $ git branch -D recover-branch $ rm -Rf .git/logs/ Because the reflog data is kept in the `.git/logs/` directory, you effectively have no reflog. How can you recover that commit at this point? One way is to use the `git fsck` utility, which checks your database for integrity. If you run it with the `--full` option, it shows you all objects that aren’t pointed to by another object: @@ -932,7 +932,7 @@ The big object is at the bottom: 2MB. To find out what file it is, you’ll use Now, you need to remove this file from all trees in your past. You can easily see what commits modified this file: - $ git log --pretty=oneline -- git.tbz2 + $ git log --pretty=oneline --branches -- git.tbz2 da3f30d019005479c99eb4c3406225613985a1db oops - removed large tarball 6df764092f3e7c8f5f94cbe08ee5cf42e92a0289 added git tarball diff --git a/be/01-introduction/01-chapter1.markdown b/be/01-introduction/01-chapter1.markdown new file mode 100644 index 000000000..604f912e2 --- /dev/null +++ b/be/01-introduction/01-chapter1.markdown @@ -0,0 +1,257 @@ +# Першыя крокі # + +Гэтая глава прысвечана пачатку працы з Git. Мы пачнем з тлумачэння асноў працы прылад кантролю версій, затым пяройдзем да таго як атрымаць працуючы Git ў сваёй сістэме і, урэшце, як наладзіць яго так, каб з ім можна было пачаць працаваць. Напрыканцы гэтай главы вы будзеце мець разуменне для чаго наогул прызначаны Git, чаму ім варта карыстацца і мець усе неабходныя наладкі дзеля гэтага. + +## Пра кантроль версій ## + +Што такое кантроль версій і навошта ён патрэбны? Кантроль версій — гэта сістэма, якая запісвае змены, што адбыліся з файлам ці наборам файлаў з цягам часу, так што вы можаце вярнуцца да розных версій пазней. У прыкладах гэтай кнігі мы будзем працаваць з зыходнікамі праграмнага забеспечэння ў якасці файлаў, версіі якіх будуць кантралявацца, але, насамрэч, вы можаце выкарыстоўваць гэтую магчымасць практычна з любым тыпам файла, які існуе на вашым кампутары. + +Калі вы графічны ці web дызайнер і маеце намер захоўваць кожную версію малюнкаў ці слаёў (што вам больш патрэбна), то выкарыстанне сістэмы кантролю версій (СКВ; Version Control System, VCS) гэта вельмі разумны выбар. Гэта дазволіць вам вярнуць файлы да папярэдняга стану, вярнуць увесь праект да папярэдняга стану, параўнаць змены паміж рознымі станамі, убачыць хто апошнім змяняў нешта, што можа выклікаць праблемы, хто прапанаваў змену і калі, і шмат іншага. Выкарыстанне СКВ у асноўным значыць, што калі вы сапсавалі нешта ці страцілі файлы, то гэта можна лёгка ўзнавіць. Як дадатак, гэта не запатрабуе вялікіх намаганняў і выдаткаў з вашага боку. + +### Лакальныя сістэмы кантролю версій ### + +Шмат людзей ў якасці метаду кантролю версій выбірае капіяванне файлаў у іншую тэчку (магчыма, з датай у назве, калі чалавек досыць разумны). Гэты падыход вельмі распаўсюджаны з-за сваёй прастаты, але ён пакідае неверагодна шмат магчымасцяў для памылак. Вельмі лёгка забыцца ў якой тэчцы вы зараз і выпадкова запісаць не ў той файл, ці зкапіяваць зусім не туды, куды вы збіраліся. + +Каб развязаць гэтую праблему праграмісты шмат часу таму распрацавлі лакальныя СКВ, якія выкарыстоўваюць простую базу дадзеных каб захоўваць ўсе змены ў файлах, версіі якіх адсочваюцца (гл. Малюнак 1-1). + +Insert 18333fig0101.png +Малюнак 1-1. Схема лакальнага кантролю версій. + +Адной з папулярных у той час СКВ была rcs, якая ўсё яшчэ пастаўляецца з вялікай колькасцю кампутараў. Нават папулярная аперацыйная сістэма Mac OS X усталёўвае rcs у складзе пакета Developer Tools. Праца гэтай прылады заснаваная на захаванні на дыску ў спецыяльным фармаце набораў латак (patch) (гэта запісы розніцы паміж дзьвума файламі) для кожнай змены файла. Гэта дапамагае вярнуць файл да любога з зафіксаваных станаў, паслядоўна накладыючы латкі адну за адной. + +### Цэнтралізаваныя сістэмы кантролю версій ### + +Наступнай сур'ёзнай праблемай, з якой людзі сутыкнуліся была неабходнасць супрацоўнічаць з распрацоўшчыкамі за іншымі кампутарамі. Централізаваныя сістэмы кантролю версій (ЦСКВ) былі распрацаваныя каб развязаць гэтую праблему. Такія сістэмы як CVS, Subversion і Perforce складаюцца з сервера, на якім захоўваюцца ўсе дадзеныя па версіях файлаў, і некаторай колькасці кліенцкіх машын, якія атрымліваюць файлы з сервера. Шмат год такая схема з'яўлялася стандартам кантролю версій (гл. Малюнак 1-2). + +Insert 18333fig0102.png +Малюнак 1-2. Схема цэнтралізаванага кантролю версій. + +Гэты падыход мае шмат пераваг, асабліва ў параўнанні з лакальнымі СКВ. Напрыклад, усе дакладна ведаюць што асатнія робяць і што наогул адбываецца ў праекце. Адміністратары маюць зручную магчымасць кантролю за тым хто што можа зрабіць. І гэта значна прасцей, чым адміністраванне лакальных баз дадзеных СКВ на кожнай кліенцкай машыне. + +Аднак, гэты падыход мае і некаторыя сур'ёзныя мінусы. Самы відавочны з іх — центральны сервер яўляе сабою пункт, крах якога цягне за сабою крах усёй сістэмы. Калі гэты сервер спыніць працу на гадзіну — у гэтую гадзіну ніхто не зможа абмяняцца з супрацоўнікамі вынікамі сваёй працы ці захаваць новую версію таго, над чым ён ці яна зараз працуе. Калі жосткі дыск, на якім змешчаная цэнтральная база дадзеных пашкоджаны, а актуальных рэзервовых копій няма, то вы згубіце абсалютна ўсё: усю гісторыю праекту, за выключэннем тых здымкаў, што карыстальнікі выпадкова мелі на сваіх лакальных кампутарах. Лакальныя СКВ пакутуюць на тую ж праблему: калі ты маеш усю гісторыю праекта толькі ў адным месцы, то ты рызыкуеш згубіць усё. + +### Размеркаваныя сістэмы кантролю версій ### + +І вось тут у гульню ўступаюць размеркаваныя сістэмы кантролю версій (РСКВ). У РСКВ (такіх як Git, Mercurial, Bazaar ці Darcs) кліенты не толькі атрымліваюць апошнія здымкі файлаў: яны атрымліваюць поўную копію сховішча. Такім чынам, калі любы з сервераў праз які ідзе абмен вынікамі працы памрэ, то любое з кліенцкіх сховішчаў можа быць зкапіявана на сервер каб аднавіць усю інфармацыю. Кожнае сховішча на кожным з працоўных месцаў насамрэч поўная рэзервовая копія ўсіх дадзеных (гл. Малюнак 1-3). + +Insert 18333fig0103.png +Малюнак 1-3. Схема размеркаванага кантролю версій. + +Апроч таго, шмат якія з гэтых сістэм выдатна працуюць з некалькімі аддаленымі сховішчамі, так што вы можаце адначасова па-рознаму узаемадзейнічаць з некалькімі рознымі групамі людзей у межах аднаго праекта. Гэта дазваляе наладжваць розные тыпы паслядоўнасцяў дзеянняў, што немагчыма з цэнтралізаванымі сістэмамі, такімі як іерархічныя мадэлі. + +## Кароткая гісторыя Git ## + +Як і шмат іншых вялікіх рэчаў у жыцці, Git пачынаўся з стваральнага разбурэння і палымяных спрэчак. Ядро Linux — праграмны праект з адкрытымі зыходнікамі даволі вялікага аб'ёму. На пряцягу большай часткі перыяду існавання ядра Linux змены ў ім распаўсюджваліся у выглядзе патчаў і архіваваных файлаў. У 2002 годзе праект распрацоўкі ядра Linux пачаў карыстацца BitKeeper — прапрыетарнай РСКВ + +У 2005 годзе адносіны паміж суполкай распрацоўшчыкаў ядра Linux і камерцыйнай кампаніяй, што распрацоўвала BitKeeper сапсаваліся і бясплатна карыстацца гэтай утылітай стала немагчыма. Гэта запатрабавала ад суполкі распрацоўшчыкаў Linux (і, ў прыватнасці, Лінуса Торвальдса (Linus Torvalds), стваральніка Linux'а) стварыць іх уласную сістэму, заснаваную на некаторых з урокаў, якія яны вынеслі для сябе з досведу карыстання BitKeeper. Некаторыя з мэтаў новай сітэмы ніжэй: + +* Хуткасць +* Просты дызайн +* Моцная падтрымка нелінейнай распрацоўкі (сотні паралельных галін) +* Цалкам размеркаваная +* Магчымасць эфектыўна працаваць з вялікімі праектамі, кшталту ядра Linux (хуткасць і памер дадзеных) + +З часу свайго з'яўлення ў 2005 годзе Git развіваўся і сталеў каб быць лёгкім у выкарыстанні і пры гэтым захоўваць гэтыя першапачатковыя якасці. Ён неверагодна хуткі, вельмі эфектыўны ў працы з вялікімі праектамі і мае неверагодную сістэму кіравання галінамі для нелінейных праектаў (гл. главу 3). + +## Асновы Git ## + +Такім чынам, што ж такое Git, калі ў двух словах? Гета вельмі важны для засваення раздзел, таму што калі вы зразумееце што такое Git і фундаментальныя асновы таго як ён працуе, то эфектыўнае выкарыстанне Git можа стаць значна больш простым для вас. Пад час вывучэння Git пастарайцеся не абапірацца на ўспаміны пра іншыя СКВ, кшталту Subversion і Perforce, гэта дапаможа пазбегнуць памылак і разгубленасці пад час выкарыстання гэтай прылады. Git захоўвае інфармацыю і успрымае яе вельмі непадобна на іншыя сістэмы, нават не гледзячы на даволі блізкае падабенства карыстальніцкага інтэрфейсу. Разуменне гэтых адрозненняў дапаможа прадухіліць памылкі і разгубленасць пад час работы з Git. + +### Здымкі, а не адрозненні ### + +Асноўнае адрозненне Git ад любой іншай СКВ (уключаючы Subversion і кампанію) — тое як Git ўяўляе сабе дадзеныя, якіе захоўвае. Канцэптуальна, большасць іншых сістэм захоўвае інфармацыю ў выглядзе набор змяненнеў. Гэтыя сістэмы (CVS, Subversion, Perforce, Bazaar і гэтак далей) ставяцца да інфармацыі, якую яны захозваюць, як да набора адрозненняў для кожнага з файлаў у параўнанні з папярэднім станам, як гэта паказана на Малюнку 1-4. + +Insert 18333fig0104.png +Малюнак 1-4. Іншыя сістэмы звычайна захоўваюць дадзеныя ў выглядзе набора зменаў для базавай версіі кожнага файла. + +Git ўспрымае данныя ў сховішчы інакш. Замест таго, каб успрымаць іх як наборы зменаў, Git ставіцца да дадзеных хутчэй як да набора здымкаў стану невялікай файлавай стэмы. Кожны раз, калі вы захоўваеце дадзеныя вашага праекду ў Git, ён па-сутнасці, робіць здымак таго, як вашыя файлы выглядаюць ў гэты момант і спасылку на гэты здымак. Для павышэння эфектыўнасці, калі файл не змяняўся, то Git не захоўвае яго яшчэ раз, а проста робіць спасылку на яго папярэдні стан, які ўжо быў захаваны. Гіт успрымае дадзеныя больш падобна на тое, што паказана на Малюнку 1-5. + +Insert 18333fig0105.png +Малюнак 1-5. Git захоўвае дадзеныя як здымкі стану праекта пэўнага часу. + +Гэта вельмі сур'ёзна адрознівае Git ад практычна ўсіх іншых СКВ. Гэта вымушае Git пераглядзець амаль усе аспекты кіравання версіямі, якія большасць іншых сістэм узялі з сістэм папярэдняга пакалення. Гэта робіць Git больш падобным на невялікую файлавую сістэму з неверагодна магутнымі прыладамі, створанымі каб працаваць павер яе, чым на звычайную СКВ. Некаторыя з пераваг, які дае такі падыход да захоўвання дадзеных, мы разгледзім ў Раздзеле 3, пад час вывучэння працы з галінамі. + +### Практычна ўсе аперацыі выконваюцца лакальна ### + +Большасць аперацый у Git патрабуюць для працы толькі лакальныя файлы і рэсурсы, бо звычайна інфармацыя з іншых кампутараў у сетцы не патрэбныя. Калі вы карысталіся ЦСКВ, дзе большасць аперацый маюць дадатковыя затрымкі, звязаныя з працай праз сець, то гэты аспект Git прымусіць думаць, што богі хуткасці блаславілі гэтую сістэмы неверагоднымі здольнасцямі. Большасць аперацый выглядае практычна імгненнымі, паколькі ўся гісторыя праекта захоўваецца непасрэдна на вашым лакальным дыску. + +Напрыклад, каб паглядзець гісторыю праекта Git не трэба звяртацца да сервера, каб атрымаць гісторыю і адлюстраваць яе для вас — можна проста прачытаць яе непасрэдна з вашай лакальнай базы дадзеных. Гэта значыць, што вы убачыце гісторыю праекта практычна імгненна. Калі вы захацелі ўбачыць розніцу паміж бягучай версіяй файла і той, што была месяц таму, Git можа праглядзець файл месячнай даўніны і вылічыць розніцу паміж версіямі лакальна, замест таго капрасіць у сервера зрабіць гэта, альбо выцягваць старую версію з сервера і потым зноўку ж вылічваць розніцу лакальна. + +Да таго ж, гэта значыць што вельмі няшмат чаго нельга зрабіць калі вы па-за сеткай ці VPN. Калі вы ў самалёце ці ў цягніку і хочаце крыху папрацаваць, то вы можаце захоўваць праект ў СКВ (ці рабіць каміты, як яшчэ кажуць) без аніякіх праблем і перашкод ажно пакуль не з'явіцца сетка, з дапамогай якой вы зможаць выгрузіць змены. Калі вы прыйшлі дадому не і здолелі наладзіць VPN, вы ўсё яшчэ ў стане працаваць. У многіх іншых сістэмах вельмі цяжка, калі наогул магчыма рабіць так. У Perforce, напрыклад, вы няшмат што можаць зрабіць, калі няма сувязі з серверам, а ў Subversion і CVS вы можаце рэдактаваць файлы, але не будзеце ў стане захаваць змены ў сваю базу дадзеных (паколькі сувязі з базай дадзеных няма). Можа гэта і не выглядае вялікім дасягненнем, але вы будзеце здзіўленыя, убачыўшы наколькі гэта можа змяніць справу. + +### Git падтрымлівае цэласнасць ### + +Для ўсяго ў Git'е вылічваецца кантрольная сума перад тым, як захаваць і затым гэтая кантрольная сума выкарыстоўваецца як спалылка на аб'ект. Гэта значыць, што немагчыма змяніць змест якога-небудзь файла ці тэчкі, каб Git не даведаўся пра гэта. Гэты функцыянал убудаваны ў Git на самых нізкіх узроўнях і з'яўляецца неад'емнай часткай яго філасофіі. Вы не можаце згубіць інфармацыю пры перадачы ці атрыманні пашкоджаннага файла без таго, габ Git не змог выявіць гэтага. + +Механізм, які выкарыстоўвае Git для вылічэнне кантрольнай сумы называецца SHA-1 хэш. Гэта страка з 40 знакаў, складаючаяся з шастнадцацірычных знакаў (0-9 і a-f) і вылічваецца па зместу файла ці тэчкі, знаходзячыхся ў Git'е. SHA-1 хэш выглядае прыкладна так: + + 24b9da6552252987aa493b52f8696cd6d3b00373 + +Вы будзеце бачыць гэтыя хэшы паўсюль у Git'е тамушта ён выкарыстоўвае іх так шмат. Фактычна, Git захоўвае ўсё не па імені, у базе дадзеных адрасацыя адбываецца па значэнні хэша кантэнту. + +### Git як правіла, толькі дадае дадзеныя ### + +Калі вы робіце дзеянні ў Git, амаль усе з іх толькі дадаюць дадзеныя ў базу дадзеных. Вельмі цяжка як-небуць прымусіць сістэму зрабіць нешта, што немагчыма адмяніць або прымусіць яе сцерці дадзеныя. Як і ў любой СКВ, вы можаце страціць або сапсаваць змены, якія вы яшчэ не зафіксавалі; але пасля таго як вы зафіксавалі здымак ў Git, вельмі цяжка страціць, асабліва калі вы рэгулярна змяшчаеце вашу базу дадзеных на іншы рэпазітар. + +Гэта робіць працу з Git радасцю, таму што мы ведаем, што можам эксперыментаваць без небяспекі моцна сапсаваць становішча. Для больш глыбокага погляд на тое, як Git захоўвае свае дадзеныя і як вы можаце аднавіць дадзеныя, якія здаюцца страчанымі, глядзіце "Пад вокладкай" у главе 9. + +### Тры станы ### + +Цяпер, звярніце ўвагу. Гэта галоўнае, што вам трэба памятаць аб Git, калі вы хочаце, каб астатак вашага навучальнага працэсу прайшоў гладка. У Git ёсць тры асноўныя станы, у якіх вашы файлы могуць знаходзіцца: зафіксаваны, зменены, і падрыхтаваныя. Зафіксаваны значыць, што дадзеныя бяспечна захаваны ў вашу лакальную базу дадзеных. Зменены значыць, што вы змянілі файл, але яшчэ не зафіксавалі ў вашай базе дадзеных. Падрыхтаваны значыць, што вы адзначылі зменены файл для ўключэння ў наступны каміт. + +Такім чынам ёсць тры часткі у праекце з выкарыстаннем Git: каталог Git (the Git directory), працоўны катлог (the working directory), і вобласць падрыхтаваных файлаў (the staging area). + +Insert 18333fig0106.png +Малюнак 1-6. Працоўны каталог (the working directory), вобласць падрыхтаваных файлаў(the staging area), і каталог Git(the Git directory). + +У каталозе Git захоўваюцца метаданныя і аб'екты базы дадзеных вашага праекту. Гэта найбольшая важная частка Git, і гэта менавіта тое, што капіруецца, калі вы кланіруеце рэпазітар з другога кампутара. + +Працоўны каталог - гэта копія пэўная версіі праекта. Гэтыя файлы вымаюцца з сціснутай базы дадзеных у каталогу Git і размяшчаюцца на дыску, каб вы карысталіся імі ці змянялі. + +Вобласць падрыхтаваных файлаў - гэта проста файл, звычайна змешчаны у каталогу Git, які захоўвае інфармацыю аб тым, што будзе выкарастана ў наступным каміце. Яго часам называюць індэксам, але становіцца стандартам называць яго вобласцю падрыхтаваных файлаў. + +Стандартня праца з Git выглядае прыкладна так: + +1. Вы змяняеце файлы ў вашым працоўным каталогу. +2. Вы падрыхтоўваеце файлы, дабаўляючы іх здымак у вашу вобласць падрыхтаваных файлаў. +3. Вы робіце каміт(фіксуеце), у выніку чаго здымак з вобласці падрыхтаваных файлаў захоўваецца ў вашым каталогу Git. + +Калі бягучая версія файла супадае с той, што ў каталогу Git, файл знаходзіцца ў зафіксаваным стане. Калі файл зменены, але толькі дададзены ў вобласць падрыхтаваных файлаў, такі файл знаходзіцца ў падрыхтаваным стане. І калі файл был зменены пасля выгрузкі с базы дадзеных, але не дадзены ў вобласць падрыхтаваных файлаў, ён знаходзіцца ў змененым стане. У главе 2 вы даведаецеся больш аб гэтых станах і як выкарыстаць іх перавагі ці прапусціць частку падрытоўкі ўвогуле. + +## Усталёўка Git ## + +Давайце пачнем выкарыстоўваць Git. Першае, што вам трэба зрабіць - гэта ўсталяваць яго.Вы можаце зрабіць гэта двумя спосабамі; ёсць два асноўных - усталяваць з зыходных файлаў ці ўсталяваць існуючы пакет для вашай платформы. + +### Усталёўка з зыходных файлаў ### + +Калі ў вас ёсць магчымасць, звычайна лепша ўсталяваць Git з зыходных файлаў, таму што вы атрымаеце найноўшую версію. Кожная версія Git звычайна ўключае карысныя паляпшэнні ітэрфейса карытсальніка, таму ўсталёўка з зыходных файлаў - найлепшы шлях, калі вы не маеце праблем з кампіляцыяй праграм з зыходных фалаў. Таксама многія дыстрыбутывы Linux змяшчаюць вельмі старыя пакеты; такім чынам толькі калі вы не выкарыстоўваеце вельмы свежы дыстрыбутыў ці вы на эксперэментальнай ветцы, усталёўка з зыходных файлаў - лепшы выбар. + +Каб усталяваць Git, вам неабходна мець наступныя бібліятэкі, ад якіх Git залежыць: curl, zlib, openssl, expat, і libiconv. На прыклад, калі вы карыстаецеся сістэмай, якая змяшчае yum (як Fedora) ці apt-get (як сістэмы заснаваныя на Denian), вы можаце выкарыстаць адну з наступных каманд для ўсталёўкі ўсіх залежнасцей: + + $ yum install curl-devel expat-devel gettext-devel \ + openssl-devel zlib-devel + + $ apt-get install libcurl4-gnutls-dev libexpat1-dev gettext \ + libz-dev libssl-dev + +Калі ў вас ёсць усе неабходныя залежнасці, вы можаце ісці далей і спампаваць найноўшы здымак з вэб сайту Git: + + http://git-scm.com/download + +Затым скампіляваць і ўсталяваць: + + $ tar -zxf git-1.6.0.5.tar.gz + $ cd git-1.6.0.5 + $ make prefix=/usr/local all + $ sudo make prefix=/usr/local install + +Пасля гэтага вы можаце атрымаць пракет Git праз ваш усталяваны Git для атрымання абнаўленняў: + + $ git clone git://git.kernel.org/pub/scm/git/git.git + +### Усталёўка на Linux ### + +Калі вы жадаеце ўсталяваць Git на Linux праз бінарны ўстаноўшчык, вы можаце зрабіць гэта з дапамогай звычайнага менеджэра пакетаў вашага дыстрыбутыву. Калі ў вас Fedora, вы можаце скарыстацца yum: + + $ yum install git-core + +Ці калі ў вас дыстрыбутыў на базе Debian, напрыклад Ubuntu, паспрабуйце apt-get: + + $ apt-get install git + +### Усталёўка на Mac ### + +Ёсць два лёгкіх пуці ўсталёкі Git на Mac. Самы лёгкі - выкарыстаць графічны ўсталёўшчык, які вы можаце спампаваць са старонкі SourceForge(гл. Малюнак 1-7): + + http://sourceforge.net/projects/git-osx-installer/ + +Insert 18333fig0107.png +Малюнак 1-7. Усталёўчшык Git на OS X. + +Іншы распаўсюджаны спосаб - гэта ўсталёука праз MacPorts (`http://www.macports.org`). Калі ў вас ёсць MacPorts, усталюйце Git гэтак: + + $ sudo port install git-core +svn +doc +bash_completion +gitweb + +Вам не трэба ўсталёўваць усе дадткі, але верагодна вы захочаце уключыць +svn у выпадку, калі вам калі-небудзь прыйдзеца карыстацца Git на Subversion рэпазітарах (глядзі Главу 8). + +### Усталёўка ў Windows ### + +Усталёўка Git на Windows вельмі лёгкая. Працэдура ўсталёўкі праекта msysGit адна з найбольш лёгкіх. Проста спампуйце exe-файл інсталятара са старонкі GitHub, і выканайце яго: + + http://msysgit.github.com/ + +Пасля яго ўсталёўкі вы маеце як кансольную версію (уключаюцы SSH кліент, які спатрэбіцца ў далейшым), так і стандартную графічную. + +## Першапачатковыя налады Git ## + +Цяпер, калі ў вашай сістэме ёсць Git, вы захочаце зрабіць некалькі рэчаў для наладкі вашага Git. Вы павінны зрабіць гэта толькі адзін раз - пры абнаўленні налады застаюцца. Вы можаце змяніць іх у любы час, выканаўшы каманды яшчэ раз. + +Git пастаўляецца з утылітай, якая называецца git config, якая дае магчымасць вам праглядаць і ўсталёўваць параметры наладкі, якія кантралююць усе аспекты працы і знешняга выгляду Git. Гэтыя параметры могуць змяшчацца ў трох месцах: + +* файл `/etc/gitconfig` : Змяшчае значэнні для ўсіх карыстальнікаў вашай сістэмы і ўсіх іх рэпазітараў. Калі вы перадаеце параметр ` --system` утыліце `git config`, яна чытае і запісвае параметры ў гэта файл. +* файл `~/.gitconfig` : Выкарыстоўваецца для вашага ўліковага запісу. Вы можаце запісваць і чытаць з гэтага файла пры ўказанні параметра `--global`. +* канфігурацыйны файл у каталогу Git (гэта `.git/config`) у тым рэпазітары, які вы выкарыстоўваеце ў данны момант: вызначае параметры для канкрэтнага гэтага рэпазітару. Кожны ўзровень змяняе значэнні папярэдняга ўзроўню, такім чынам значэнні ў `.git/config` перакрываюць адпаведныя ў `/etc/gitconfig`. + +У Windows Git шукае файл `.gitconfig` у каталогу`$HOME` directory (`C:\Documents and Settings\$USER` для большасці карастыльнікаў). Таксама ён шукае /etc/gitconfig, але ўжо адносна карнявога каталогу MSys, які знаходзіцца там, дзе вы вырашылі ўсталяваць Git. + +### Ваша ідэнтыфікацыя ### + +Першае, што вам трэба зрабіць, калі вы ўсталявалі Git, - задаць ваша імя і адрас e-mail. Гэта важна таму, што кожны каміт у Git выкарыстоўвае гэтую інфармацыю, і яна ўключаецца ў каміты, перадаваемыя вамі, і далей ня можа быць зменена: + + $ git config --global user.name "John Doe" + $ git config --global user.email johndoe@example.com + +Зноў-такі, вам трэба зрабіць гэта толькі адзін раз, калі перадалі параметр `--global`, таму шта Git будзе заўжды выкарыстоўваць гэту інфармацыю для ўсяго, што вы будзеце рабіць на гэтай сістэме. Калі вы хочаце змяніць гэта на іншае імя ці адрас e-mail для канкрэтнага праекта, вы можаце выканаць каманду без параметра `--global`, калі вы знаходзіцеся ў каталогу праекта. + +### Ваш рэдактар ### + +Цяпер, калі вы наладзілі данныя ідэнтыфікацыі, вы можаце наладзіць тэкставы рэдактар, які будзе выкарыстоўвацца, калі Git'у трэба, каб вы ўвялі паведамленне. Па змаўчанні Git выкарыстоўвае стандартны рэдактар вашай сістэмы, звычайна гэта Vi ці Vim. Калі вы жадаеце выкарыстаць іншы тэкставы рэдактар, напрыклда Emacs, вы можаце зрабіць наступнае: + + $ git config --global core.editor emacs + +### Ваша утыліта параўнання ### + +Яшчэ адна карысная налада, якую вы мажліва хочаце змяніць, - гэта стандартная утыліта для параўнання, якая выкарыстоўваецца для вырашэння канфліктаў зліцця. Напрыклад, вы хочаце выкарыстоўваць vimdiff: + + $ git config --global merge.tool vimdiff + +Git падтрымлівае kdiff3, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge і opendiff як дапушчальныя утыліты параўнання. Таксама вы можаце наладзіць іншую утыліту; больш аб гэтым напісана ў Главе 7. + +### Праверка вашых наладак ### + +Калі вы хочаце праверыць вышы налады, вы можаце выкарыстаць каманду `git config --list` для вываду ўсіх наладак Git, якія даступны на данным узроўні: + + $ git config --list + user.name=Scott Chacon + user.email=schacon@gmail.com + color.status=auto + color.branch=auto + color.interactive=auto + color.diff=auto + ... + +Вы можаце бачыць параметры больш аднаго разу, бо Git счытвае аднолькавыя параметры з розных файлаў (`/etc/gitconfig` і `~/.gitconfig` для прыкладу). У такім выпадку Git выкарыстоўвае апошняе значэнне для кожнага знайдзеннага параметра. + +Таксама вы можаце праверыць што для Git з'яўляецца значэннем для канкрэтнага параметра, выканаўшы `git config {параметр}`: + + $ git config user.name + Scott Chacon + +## Атрыманне даведкі ## + +Калі вам патрэбна даведка пры выкарыстанні Git, ёсць тры спосабы для атрымання старонкі кіраўніцтва для любой каманды Git: + + $ git help <дзеяслоў> + $ git <дзеяслоў> --help + $ man git-<дзеяслоў> + +Напрыклад вы можаце атрымать даведку па камандзе config, выканаўшы + + $ git help config + +Гэты каманды выдатны тым, што вы можаце выкарыстаць іх усюды, нават калі вы не падключаны да сеткі. +Калі старонкі кіраўніцтва і гэтай кнігі не дастаткова і вы маеце патрэбу ў асабістай дапамозе, вы можаце паспрабаваць канал `#git` ці `#github` IRC серверы Freenode (irc.freenode.net). Гэтыя каналы амаль заўсёды напоўнены сотнямі людзей, якія добра ведаюць Git і звычайна гатовы дапамагчыare often willing to help. + +## Вынікі ## + +Цяпер у вас павінна быць агульнае разуменне што такое Git і чым ён адрозніваецца ад СКВ, якія вы магчыма выкарыстоўвалі. Таксама вы павінны мець працуючую версію Git у вашай сістэме з вашымі наладамі ідэнтыфікацыі. Прыйшоў час вывучаць некаторыя асновы Git. diff --git a/be/02-git-basics/01-chapter2.markdown b/be/02-git-basics/01-chapter2.markdown new file mode 100644 index 000000000..d1f61ded5 --- /dev/null +++ b/be/02-git-basics/01-chapter2.markdown @@ -0,0 +1,1126 @@ +# Асновы Git # + +Калі вы жадаеце прачытаць адну главу і пацаць карыстацца Git, то гэта глава - тое, што вам патрэбна. Гэта глава ахоплівае ўсе базывая каманды, якія вам спатрэбяцца пры рашэнні пераважнай большасці задач, узнікаючых пры працы з Git. Пасля вывучэння главы вы павінны ўмець наладзіць і ініцыялізаваць рэпазітар, пачынаць і супыняць версійны кантроль файлаў, падрыхтоўваць і фіксаваць змяненні. Таксама мы пакажам вам як наладзіць Git на ігнараванне пэўных файлаў і шаблонаў файлаў, як адмяніць хутка і лёгка памылковыя змены, як праглядзець гісторую вашага праекта і праглядзець змены паміж камітамі(commit), як выкладываць(push) і забіраць (pull) змяненні з выдаленага(remote) рэпазітара. + +## Стварэнне рэпазітара Git ## + +Вы можаце атрымаць рэпазітар Git двума асноўнымі падыходамі. Першы - імпарт уснуючага праекта ці каталогу ў Git. Другі - кланіраванне існуючага рэпазітара Git з іншага сервера. + +### Стварэнне рэпазітара ў існуючым каталогу ### + +Калі вы жадаеце пачаць версійны кантроль існуючага праекта праз Git, вам патрэба перайсці ў каталог праекта і ўвесці + + $ git init + +У выніку створыцца падкаталог з назвай `.git`, у якім змяшчаюцца ўсе неабходныя файлы рэпазітара - аснову рапазітара Git. На гэтым этапе ваш праект яшчэ не знаходзіцца пад версійным кантролем. (Глядзіце *Главу 9* для больш поўнай інфармацыі якія дакладна файлы змяшчаюцца ў каталогу `.git`, які вы толькі стварылі. + +Калі вы хочаце пачаць версійны кантроль над існуючымі файламі (у адрозненні ад пустога каталога), вам варта праіндэксаваць гэтыя файлы і зрабіць першую фіксацыю зменаў(першы каміт). Вы можаце зрабіць гэта з дапамогай некалькі каманда `git add`, якія ўказваюць файлы, якія вы хочаце праіндэксаваць, затым выкарыстайце каманду commit: + + $ git add *.c + $ git add README + $ git commit -m 'initial project version' + +Вы разгледзем што гэтыя каманды робяць праз хвіліну. На гэты момант у вас ёсць рэпазітар Git з праіндэксаванымі файламі і першым камітам. + +### Кланіраванне існуючага рэпазітара ### + +Калі вы жадаеце атрымаць копію існуючага рэпазітара, на прыклад, праект, у якім вы жадаеце ўдзельнічаць, патрэбная вам каманда - `git clone`. Калі вы знаёмы з іншымі СКВ, такімі як Subversion, вы заўважыце, што каманда называецца `clone`, а не `checkout`. Гэта важнае адрозненне - Git атрымлівае копію амаль усіх данных, якія ёсць на серверы. Кожная версія кожнага файла з гісторыі праекта забіраецца (pulled), калі вы выконваеце `git clone`. Фактычна, калі ваш серверны дыск пашкоджаны, вы можаце выкарыстаць любою з копій любога кліента каб узнаціць сервер да стану, у якім ён быў кланіраваны (вы можаце згубіць некаторыя серверныя правілы і падобнае да іх, але ўсе дадзенныя пад версіённым кантролем будуць захаваны - больш у *Главе 4*). + +Кланіраванне рэпазітара адбываецца з дапамогай каманды `git clone [url]`. Напрыклад, калі вы жадаеце скланіраваць бібліятэку Ruby Git, вядомую як Grit, вы можаце зрабіць так: + + $ git clone git://github.com/schacon/grit.git + +У выніку ствараецца каталог з назвай `grit`, ініцыялізуя ў ім каталог `.git`, пампуе ўсе дадзеныя гэтага рэпазітара і стварае (checks out) працоўную копію апошняй версіі. Калі вы зойдзеце ў каталог `grit`, вы ўбачыце там файлы праекта гатовыя да працы ці выкарыстання. Калі вы жадаеце кланіраваць рэпазітар у каталог, які завецца інакш чым grit, вы можаце пазначыць гэта ў якасці наступнага параметра каманднай стракі: + + $ git clone git://github.com/schacon/grit.git mygrit + +Гэта каманда робіць тоеж, што і папярэдняя, толькі выходны каталог называецца `mygrit`. + +Git падтрымлівае некалькі транспартных пратаколаў, якімі вы можаце карыстацца. У папярэднім прыкладзе выкарыстоўваецца пратакол `git://`, але вы таксама можаце сустрэць `http(s)://` ці `user@server:/path.git`, якія выкарыстоўваюць транспартны пратакол SSH. У *Главе 4* прадстаўлены ўсе магчымыя налады сервера для доступу да вашага рэпазітару Git, вартасці і недахопы кожнага. + +## Запіс зменаў у рэпазітар ## + +Такім чынам у вас ёсць сапраўдны рэпазітар Git і працоўная копія файлаў праекта. Вам трэба зрабіць некаторыя змены і зафіксаваць "здымкі" станаў (snapshots) гэтых зменаў у вашым рэпазітары кожны раз, калі праект дасягне таго стану, які вы захочаце захаваць. + +Памятайце, што кожны файл у вашым працоўным каталогу можа быць у адным з двух станаў: *адсочваемы*(*tracked*) ці *неадсочваемы*(*untracked*). *Адсочваемыя* файлы - гэта файлы, якія былі ў апошнім "здымку" праекта(snapshot); ямы могуць быць *нязмененыя*(*unmodified*), *змененыя*(*modified*) ці *падрыхтаваныя*(*staged*). *Неадсочваемыя* файлы - гэта ўсё астатнее, файлы ў вашым працоўным каталогу, якія не былі ў вашым апошнім "здымку" і не знаходзяцца ў вобласці падрыхтаваных файлаў. Калі вы ў першы раз кланіруеце рэпазітар, усе вашыя файлы будуць адсочваемыя і немадыфікаванымі таму што вы іх толькі што ўзялі са сховішча і яшчэ не мянялі нічога. + +Як толькі вы зменіце файлы, Git будзе разглядаць іх як мадыфікаваныя, таму што вы змянілі іх з моманту апошняга каміта. Вы *падрыхтоўваеце* гэтыя мадыфікаваныя файлы і затым фіксуеце ўсе вашы падрыхтаваныя змены, затым цыкл паўтараецца. Гэта жыццёвы цыкл адлюстраваны на Малюнку 2-1. + +Insert 18333fig0201.png +Малюнак 2-1. Жыццевы цыкл станаў вашых файлаў. + +### Праверка стану вашых файлаў ### + +Галоўная прылада для вызначэння якія файлы ў якім стане - гэта каманда `git status`. Калі вы выканаеце гэтаую каманду адразу пасля кланавання, вы павінны ўбачыць нешта падобнае да гэтага: + + $ git status + # On branch master + nothing to commit, working directory clean + +Гэта значыць, што ў вас чысты працоўны каталог, іншымі словамі - адсутнічаюць мадыфікаваныя адсочваемыя файлы. Git таксама не знайшоў якія-небудзь неадсочваемыя файлы, у зваротным выпадку яны былі б пералічаны тут. У канцы каманда паказвае вам на якой ветцы вы знаходзіцеся. This means you have a clean working directory — in other words, there are no tracked and modified files. Git also doesn’t see any untracked files, or they would be listed here. Finally, the command tells you which branch you’re on. For now, that is always `master`, which is the default; you won’t worry about it here. The next chapter will go over branches and references in detail. + +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: + + $ vim README + $ git status + # On branch master + # Untracked files: + # (use "git add ..." to include in what will be committed) + # + # README + nothing added to commit but untracked files present (use "git add" to track) + +You can see that your new README file is untracked, because it’s under the “Untracked files” heading in your status output. Untracked basically means that Git sees a file you didn’t have in the previous snapshot (commit); Git won’t start including it in your commit snapshots until you explicitly tell it to do so. It does this so you don’t accidentally begin including generated binary files or other files that you did not mean to include. You do want to start including README, so let’s start tracking the file. + +### Tracking New Files ### + +In order to begin tracking a new file, you use the command `git add`. To begin tracking the README file, you can run this: + + $ git add README + +If you run your status command again, you can see that your README file is now tracked and staged: + + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # + +You can tell that it’s staged because it’s under the “Changes to be committed” heading. If you commit at this point, the version of the file at the time you ran `git add` is what will be in the historical snapshot. You may recall that when you ran `git init` earlier, you then ran `git add (files)` — that was to begin tracking files in your directory. The `git add` command takes a path name for either a file or a directory; if it’s a directory, the command adds all the files in that directory recursively. + +### Staging Modified Files ### + +Let’s change a file that was already tracked. If you change a previously tracked file called `benchmarks.rb` and then run your `status` command again, you get something that looks like this: + + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # + # Changes not staged for commit: + # (use "git add ..." to update what will be committed) + # + # modified: benchmarks.rb + # + +The `benchmarks.rb` file appears under a section named “Changes not staged for commit” — which means that a file that is tracked has been modified in the working directory but not yet staged. To stage it, you run the `git add` command (it’s a multipurpose command — you use it to begin tracking new files, to stage files, and to do other things like marking merge-conflicted files as resolved). Let’s run `git add` now to stage the `benchmarks.rb` file, and then run `git status` again: + + $ git add benchmarks.rb + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # modified: benchmarks.rb + # + +Both files are staged and will go into your next commit. At this point, suppose you remember one little change that you want to make in `benchmarks.rb` before you commit it. You open it again and make that change, and you’re ready to commit. However, let’s run `git status` one more time: + + $ vim benchmarks.rb + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # modified: benchmarks.rb + # + # Changes not staged for commit: + # (use "git add ..." to update what will be committed) + # + # modified: benchmarks.rb + # + +What the heck? Now `benchmarks.rb` is listed as both staged and unstaged. How is that possible? It turns out that Git stages a file exactly as it is when you run the `git add` command. If you commit now, the version of `benchmarks.rb` as it was when you last ran the `git add` command is how it will go into the commit, not the version of the file as it looks in your working directory when you run `git commit`. If you modify a file after you run `git add`, you have to run `git add` again to stage the latest version of the file: + + $ git add benchmarks.rb + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # modified: benchmarks.rb + # + +### Ignoring Files ### + +Often, you’ll have a class of files that you don’t want Git to automatically add or even show you as being untracked. These are generally automatically generated files such as log files or files produced by your build system. In such cases, you can create a file listing patterns to match them named `.gitignore`. Here is an example `.gitignore` file: + + $ cat .gitignore + *.[oa] + *~ + +The first line tells Git to ignore any files ending in `.o` or `.a` — *object* and *archive* files that may be the product of building your code. The second line tells Git to ignore all files that end with a tilde (`~`), which is used by many text editors such as Emacs to mark temporary files. You may also include a `log`, `tmp`, or `pid` directory; automatically generated documentation; and so on. Setting up a `.gitignore` file before you get going is generally a good idea so you don’t accidentally commit files that you really don’t want in your Git repository. + +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. +* 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 in the range (in this case 0 through 9) . + +Here is another example `.gitignore` file: + + # a comment - this is ignored + # no .a files + *.a + # but do track lib.a, even though you're ignoring .a files above + !lib.a + # only ignore the root TODO file, not subdir/TODO + /TODO + # ignore all files in the build/ directory + build/ + # ignore doc/notes.txt, but not doc/server/arch.txt + doc/*.txt + +### Viewing Your Staged and Unstaged Changes ### + +If the `git status` command is too vague for you — you want to know exactly what you changed, not just which files were changed — you can use the `git diff` command. We’ll cover `git diff` in more detail later; but you’ll probably use it most often to answer these two questions: What have you changed but not yet staged? And what have you staged that you are about to commit? Although `git status` answers those questions very generally, `git diff` shows you the exact lines added and removed — the patch, as it were. + +Let’s say you edit and stage the `README` file again and then edit the `benchmarks.rb` file without staging it. If you run your `status` command, you once again see something like this: + + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # + # Changes not staged for commit: + # (use "git add ..." to update what will be committed) + # + # modified: benchmarks.rb + # + +To see what you’ve changed but not yet staged, type `git diff` with no other arguments: + + $ git diff + diff --git a/benchmarks.rb b/benchmarks.rb + index 3cb747f..da65585 100644 + --- a/benchmarks.rb + +++ b/benchmarks.rb + @@ -36,6 +36,10 @@ def main + @commit.parents[0].parents[0].parents[0] + end + + + run_code(x, 'commits 1') do + + git.commits.size + + end + + + run_code(x, 'commits 2') do + log = git.commits('master', 15) + log.size + +That command compares what is in your working directory with what is in your staging area. The result tells you the changes you’ve made that you haven’t yet staged. + +If you want to see what you’ve staged that will go into your next commit, you can use `git diff --cached`. (In Git versions 1.6.1 and later, you can also use `git diff --staged`, which may be easier to remember.) This command compares your staged changes to your last commit: + + $ git diff --cached + diff --git a/README b/README + new file mode 100644 + index 0000000..03902a1 + --- /dev/null + +++ b/README2 + @@ -0,0 +1,5 @@ + +grit + + by Tom Preston-Werner, Chris Wanstrath + + http://github.com/mojombo/grit + + + +Grit is a Ruby library for extracting information from a Git repository + +It’s important to note that `git diff` by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. This can be confusing, because if you’ve staged all of your changes, `git diff` will give you no output. + +For another example, if you stage the `benchmarks.rb` file and then edit it, you can use `git diff` to see the changes in the file that are staged and the changes that are unstaged: + + $ git add benchmarks.rb + $ echo '# test line' >> benchmarks.rb + $ git status + # On branch master + # + # Changes to be committed: + # + # modified: benchmarks.rb + # + # Changes not staged for commit: + # + # modified: benchmarks.rb + # + +Now you can use `git diff` to see what is still unstaged + + $ git diff + diff --git a/benchmarks.rb b/benchmarks.rb + index e445e28..86b2f7c 100644 + --- a/benchmarks.rb + +++ b/benchmarks.rb + @@ -127,3 +127,4 @@ end + main() + + ##pp Grit::GitRuby.cache_client.stats + +# test line + +and `git diff --cached` to see what you’ve staged so far: + + $ git diff --cached + diff --git a/benchmarks.rb b/benchmarks.rb + index 3cb747f..e445e28 100644 + --- a/benchmarks.rb + +++ b/benchmarks.rb + @@ -36,6 +36,10 @@ def main + @commit.parents[0].parents[0].parents[0] + end + + + run_code(x, 'commits 1') do + + git.commits.size + + end + + + run_code(x, 'commits 2') do + log = git.commits('master', 15) + log.size + +### Committing Your Changes ### + +Now that your staging area is set up the way you want it, you can commit your changes. Remember that anything that is still unstaged — any files you have created or modified that you haven’t run `git add` on since you edited them — won’t go into this commit. They will stay as modified files on your disk. +In this case, the last time you ran `git status`, you saw that everything was staged, so you’re ready to commit your changes. The simplest way to commit is to type `git commit`: + + $ git commit + +Doing so launches your editor of choice. (This is set by your shell’s `$EDITOR` environment variable — usually vim or emacs, although you can configure it with whatever you want using the `git config --global core.editor` command as you saw in *Chapter 1*). + +The editor displays the following text (this example is a Vim screen): + + # Please enter the commit message for your changes. Lines starting + # with '#' will be ignored, and an empty message aborts the commit. + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # new file: README + # modified: benchmarks.rb + ~ + ~ + ~ + ".git/COMMIT_EDITMSG" 10L, 283C + +You can see that the default commit message contains the latest output of the `git status` command commented out and one empty line on top. You can remove these comments and type your commit message, or you can leave them there to help you remember what you’re committing. (For an even more explicit reminder of what you’ve modified, you can pass the `-v` option to `git commit`. Doing so also puts the diff of your change in the editor so you can see exactly what you did.) When you exit the editor, Git creates your commit with that commit message (with the comments and diff stripped out). + +Alternatively, you can type your commit message inline with the `commit` command by specifying it after a `-m` flag, like this: + + $ git commit -m "Story 182: Fix benchmarks for speed" + [master]: created 463dc4f: "Fix benchmarks for speed" + 2 files changed, 3 insertions(+), 0 deletions(-) + create mode 100644 README + +Now you’ve created your first commit! You can see that the commit has given you some output about itself: which branch you committed to (`master`), what SHA-1 checksum the commit has (`463dc4f`), how many files were changed, and statistics about lines added and removed in the commit. + +Remember that the commit records the snapshot you set up in your staging area. Anything you didn’t stage is still sitting there modified; you can do another commit to add it to your history. Every time you perform a commit, you’re recording a snapshot of your project that you can revert to or compare to later. + +### Skipping the Staging Area ### + +Although it can be amazingly useful for crafting commits exactly how you want them, the staging area is sometimes a bit more complex than you need in your workflow. If you want to skip the staging area, Git provides a simple shortcut. Providing the `-a` option to the `git commit` command makes Git automatically stage every file that is already tracked before doing the commit, letting you skip the `git add` part: + + $ git status + # On branch master + # + # Changes not staged for commit: + # + # modified: benchmarks.rb + # + $ git commit -a -m 'added new benchmarks' + [master 83e38c7] added new benchmarks + 1 files changed, 5 insertions(+), 0 deletions(-) + +Notice how you don’t have to run `git add` on the `benchmarks.rb` file in this case before you commit. + +### Removing Files ### + +To remove a file from Git, you have to remove it from your tracked files (more accurately, remove it from your staging area) and then commit. The `git rm` command does that and also removes the file from your working directory so you don’t see it as an untracked file next time around. + +If you simply remove the file from your working directory, it shows up under the “Changes not staged for commit” (that is, _unstaged_) area of your `git status` output: + + $ rm grit.gemspec + $ git status + # On branch master + # + # Changes not staged for commit: + # (use "git add/rm ..." to update what will be committed) + # + # deleted: grit.gemspec + # + +Then, if you run `git rm`, it stages the file’s removal: + + $ git rm grit.gemspec + rm 'grit.gemspec' + $ git status + # On branch master + # + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # deleted: grit.gemspec + # + +The next time you commit, the file will be gone and no longer tracked. If you modified the file and added it to the index already, you must force the removal with the `-f` option. This is a safety feature to prevent accidental removal of data that hasn’t yet been recorded in a snapshot and that can’t be recovered from Git. + +Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. In other words, you may want to keep the file on your hard drive but not have Git track it anymore. This is particularly useful if you forgot to add something to your `.gitignore` file and accidentally added it, like a large log file or a bunch of `.a` compiled files. To do this, use the `--cached` option: + + $ git rm --cached readme.txt + +You can pass files, directories, and file-glob patterns to the `git rm` command. That means you can do things such as + + $ git rm log/\*.log + +Note the backslash (`\`) in front of the `*`. This is necessary because Git does its own filename expansion in addition to your shell’s filename expansion. This command removes all files that have the `.log` extension in the `log/` directory. Or, you can do something like this: + + $ git rm \*~ + +This command removes all files that end with `~`. + +### Moving Files ### + +Unlike many other VCS systems, Git doesn’t explicitly track file movement. If you rename a file in Git, no metadata is stored in Git that tells it you renamed the file. However, Git is pretty smart about figuring that out after the fact — we’ll deal with detecting file movement a bit later. + +Thus it’s a bit confusing that Git has a `mv` command. If you want to rename a file in Git, you can run something like + + $ git mv file_from file_to + +and it works fine. In fact, if you run something like this and look at the status, you’ll see that Git considers it a renamed file: + + $ git mv README.txt README + $ git status + # On branch master + # Your branch is ahead of 'origin/master' by 1 commit. + # + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # renamed: README.txt -> README + # + +However, this is equivalent to running something like this: + + $ mv README.txt README + $ git rm README.txt + $ 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 `mv` is one command instead of three — it’s a convenience function. More important, you can use any tool you like to rename a file, and address the add/rm later, before you commit. + +## Viewing the Commit History ## + +After you have created several commits, or if you have cloned a repository with an existing commit history, you’ll probably want to look back to see what has happened. The most basic and powerful tool to do this is the `git log` command. + +These examples use a very simple project called `simplegit` that I often use for demonstrations. To get the project, run + + git clone git://github.com/schacon/simplegit-progit.git + +When you run `git log` in this project, you should get output that looks something like this: + + $ git log + commit ca82a6dff817ec66f44342007202690a93763949 + Author: Scott Chacon + Date: Mon Mar 17 21:52:11 2008 -0700 + + changed the version number + + commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 + Author: Scott Chacon + Date: Sat Mar 15 16:40:33 2008 -0700 + + removed unnecessary test code + + commit a11bef06a3f659402fe7563abf99ad00de2209e6 + Author: Scott Chacon + Date: Sat Mar 15 10:31:28 2008 -0700 + + first commit + +By default, with no arguments, `git log` lists the commits made in that repository in reverse chronological order. That is, the most recent commits show up first. As you can see, this command lists each commit with its SHA-1 checksum, the author’s name and e-mail, the date written, and the commit message. + +A huge number and variety of options to the `git log` command are available to show you exactly what you’re looking for. Here, we’ll show you some of the most-used options. + +One of the more helpful options is `-p`, which shows the diff introduced in each commit. You can also use `-2`, which limits the output to only the last two entries: + + $ git log -p -2 + commit ca82a6dff817ec66f44342007202690a93763949 + Author: Scott Chacon + Date: Mon Mar 17 21:52:11 2008 -0700 + + changed the version number + + diff --git a/Rakefile b/Rakefile + index a874b73..8f94139 100644 + --- a/Rakefile + +++ b/Rakefile + @@ -5,7 +5,7 @@ require 'rake/gempackagetask' + spec = Gem::Specification.new do |s| + - s.version = "0.1.0" + + s.version = "0.1.1" + s.author = "Scott Chacon" + + commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 + Author: Scott Chacon + Date: Sat Mar 15 16:40:33 2008 -0700 + + removed unnecessary test code + + diff --git a/lib/simplegit.rb b/lib/simplegit.rb + index a0a60ae..47c6340 100644 + --- a/lib/simplegit.rb + +++ b/lib/simplegit.rb + @@ -18,8 +18,3 @@ class SimpleGit + end + + end + - + -if $0 == __FILE__ + - git = SimpleGit.new + - puts git.show + -end + \ No newline at end of file + +This option displays the same information but with a diff directly following each entry. This is very helpful for code review or to quickly browse what happened during a series of commits that a collaborator has added. +You can also use a series of summarizing options with `git log`. For example, if you want to see some abbreviated stats for each commit, you can use the `--stat` option: + + $ git log --stat + commit ca82a6dff817ec66f44342007202690a93763949 + Author: Scott Chacon + Date: Mon Mar 17 21:52:11 2008 -0700 + + changed the version number + + Rakefile | 2 +- + 1 files changed, 1 insertions(+), 1 deletions(-) + + commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 + Author: Scott Chacon + Date: Sat Mar 15 16:40:33 2008 -0700 + + removed unnecessary test code + + lib/simplegit.rb | 5 ----- + 1 files changed, 0 insertions(+), 5 deletions(-) + + commit a11bef06a3f659402fe7563abf99ad00de2209e6 + Author: Scott Chacon + Date: Sat Mar 15 10:31:28 2008 -0700 + + first commit + + README | 6 ++++++ + Rakefile | 23 +++++++++++++++++++++++ + lib/simplegit.rb | 25 +++++++++++++++++++++++++ + 3 files changed, 54 insertions(+), 0 deletions(-) + +As you can see, the `--stat` option prints below each commit entry a list of modified files, how many files were changed, and how many lines in those files were added and removed. It also puts a summary of the information at the end. +Another really useful option is `--pretty`. This option changes the log output to formats other than the default. A few prebuilt options are available for you to use. The `oneline` option prints each commit on a single line, which is useful if you’re looking at a lot of commits. In addition, the `short`, `full`, and `fuller` options show the output in roughly the same format but with less or more information, respectively: + + $ git log --pretty=oneline + ca82a6dff817ec66f44342007202690a93763949 changed the version number + 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 removed unnecessary test code + a11bef06a3f659402fe7563abf99ad00de2209e6 first commit + +The most interesting option is `format`, which allows you to specify your own log output format. This is especially useful when you’re generating output for machine parsing — because you specify the format explicitly, you know it won’t change with updates to Git: + + $ git log --pretty=format:"%h - %an, %ar : %s" + ca82a6d - Scott Chacon, 11 months ago : changed the version number + 085bb3b - Scott Chacon, 11 months ago : removed unnecessary test code + a11bef0 - Scott Chacon, 11 months ago : first commit + +Table 2-1 lists some of the more useful options that format takes. + + Option Description of Output + %H Commit hash + %h Abbreviated commit hash + %T Tree hash + %t Abbreviated tree hash + %P Parent hashes + %p Abbreviated parent hashes + %an Author name + %ae Author e-mail + %ad Author date (format respects the –date= option) + %ar Author date, relative + %cn Committer name + %ce Committer email + %cd Committer date + %cr Committer date, relative + %s Subject + +You may be wondering what the difference is between _author_ and _committer_. The _author_ is the person who originally wrote the patch, whereas the _committer_ is the person who last applied the patch. So, if you send in a patch to a project and one of the core members applies the patch, both of you get credit — you as the author and the core member as the committer. We’ll cover this distinction a bit more in *Chapter 5*. + +The `oneline` and `format` options are particularly useful with another `log` option called `--graph`. This option adds a nice little ASCII graph showing your branch and merge history, which we can see our copy of the Grit project repository: + + $ git log --pretty=format:"%h %s" --graph + * 2d3acf9 ignore errors from SIGCHLD on trap + * 5e3ee11 Merge branch 'master' of git://github.com/dustin/grit + |\ + | * 420eac9 Added a method for getting the current branch. + * | 30e367c timeout code and tests + * | 5a09431 add timeout protection to grit + * | e1193f8 support for heads with slashes in them + |/ + * d6016bc require time for xmlschema + * 11d191e Merge branch 'defunkt' into local + +Those are only some simple output-formatting options to `git log` — there are many more. Table 2-2 lists the options we’ve covered so far and some other common formatting options that may be useful, along with how they change the output of the log command. + + 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. + --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. Options include oneline, short, full, fuller, and format (where you specify your own format). + +### Limiting Log Output ### + +In addition to output-formatting options, `git log` takes a number of useful limiting options — that is, options that let you show only a subset of commits. You’ve seen one such option already — the `-2` option, which show only the last two commits. In fact, you can do `-`, where `n` is any integer to show the last `n` commits. In reality, you’re unlikely to use that often, because Git by default pipes all output through a pager so you see only one page of log output at a time. + +However, the time-limiting options such as `--since` and `--until` are very useful. For example, this command gets the list of commits made in the last two weeks: + + $ git log --since=2.weeks + +This command works with lots of formats — you can specify a specific date (“2008-01-15”) or a relative date such as “2 years 1 day 3 minutes ago”. + +You can also filter the list to commits that match some search criteria. The `--author` option allows you to filter on a specific author, and the `--grep` option lets you search for keywords in the commit messages. (Note that if you want to specify both author and grep options, you have to add `--all-match` or the command will match commits with either.) + +The last really useful option to pass to `git log` as a filter is a path. If you specify a directory or file name, you can limit the log output to commits that introduced a change to those files. This is always the last option and is generally preceded by double dashes (`--`) to separate the paths from the options. + +In Table 2-3 we’ll list these and a few other common options for your reference. + + Option Description + -(n) 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. + +For example, if you want to see which commits modifying test files in the Git source code history were committed by Junio Hamano and were not merges in the month of October 2008, you can run something like this: + + $ git log --pretty="%h - %s" --author=gitster --since="2008-10-01" \ + --before="2008-11-01" --no-merges -- t/ + 5610e3b - Fix testcase failure when extended attribute + acd3b9e - Enhance hold_lock_file_for_{update,append}() + f563754 - demonstrate breakage of detached checkout wi + d1a43f2 - reset --hard/read-tree --reset -u: remove un + 51a94af - Fix "checkout --track -b newbranch" on detac + b0ad11e - pull: allow "git pull origin $something:$cur + +Of the nearly 20,000 commits in the Git source code history, this command shows the 6 that match those criteria. + +### Using a GUI to Visualize History ### + +If you like to use a more graphical tool to visualize your commit history, you may want to take a look at a Tcl/Tk program called `gitk` that is distributed with Git. Gitk is basically a visual `git log` tool, and it accepts nearly all the filtering options that `git log` does. If you type `gitk` on the command line in your project, you should see something like Figure 2-2. + +Insert 18333fig0202.png +Figure 2-2. The gitk history visualizer. + +You can see the commit history in the top half of the window along with a nice ancestry graph. The diff viewer in the bottom half of the window shows you the changes introduced at any commit you click. + +## Undoing Things ## + +At any stage, you may want to undo something. Here, we’ll review a few basic tools for undoing changes that you’ve made. Be careful, because you can’t always revert some of these undos. This is one of the few areas in Git where you may lose some work if you do it wrong. + +### Changing Your Last Commit ### + +One of the common undos takes place when you commit too early and possibly forget to add some files, or you mess up your commit message. If you want to try that commit again, you can run commit with the `--amend` option: + + $ git commit --amend + +This command takes your staging area and uses it for the commit. If you’ve made no changes since your last commit (for instance, you run this command immediately after your previous commit), then your snapshot will look exactly the same and all you’ll change is your commit message. + +The same commit-message editor fires up, but it already contains the message of your previous commit. You can edit the message the same as always, but it overwrites your previous commit. + +As an example, if you commit and then realize you forgot to stage the changes in a file you wanted to add to this commit, you can do something like this: + + $ git commit -m 'initial commit' + $ git add forgotten_file + $ git commit --amend + +After these three commands, you end up with a single commit — the second commit replaces the results of the first. + +### Unstaging a Staged File ### + +The next two sections demonstrate how to wrangle your staging area and working directory changes. The nice part is that the command you use to determine the state of those two areas also reminds you how to undo changes to them. For example, let’s say you’ve changed two files and want to commit them as two separate changes, but you accidentally type `git add *` and stage them both. How can you unstage one of the two? The `git status` command reminds you: + + $ git add . + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # modified: README.txt + # modified: benchmarks.rb + # + +Right below the “Changes to be committed” text, it says "use `git reset HEAD ...` to unstage". So, let’s use that advice to unstage the `benchmarks.rb` file: + + $ git reset HEAD benchmarks.rb + benchmarks.rb: locally modified + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # modified: README.txt + # + # Changes not staged for commit: + # (use "git add ..." to update what will be committed) + # (use "git checkout -- ..." to discard changes in working directory) + # + # modified: benchmarks.rb + # + +The command is a bit strange, but it works. The `benchmarks.rb` file is modified but once again unstaged. + +### Unmodifying a Modified File ### + +What if you realize that you don’t want to keep your changes to the `benchmarks.rb` file? How can you easily unmodify it — revert it back to what it looked like when you last committed (or initially cloned, or however you got it into your working directory)? Luckily, `git status` tells you how to do that, too. In the last example output, the unstaged area looks like this: + + # Changes not staged for commit: + # (use "git add ..." to update what will be committed) + # (use "git checkout -- ..." to discard changes in working directory) + # + # modified: benchmarks.rb + # + +It tells you pretty explicitly how to discard the changes you’ve made (at least, the newer versions of Git, 1.6.1 and later, do this — if you have an older version, we highly recommend upgrading it to get some of these nicer usability features). Let’s do what it says: + + $ git checkout -- benchmarks.rb + $ git status + # On branch master + # Changes to be committed: + # (use "git reset HEAD ..." to unstage) + # + # modified: README.txt + # + +You can see that the changes have been reverted. You should also realize that this is a dangerous command: any changes you made to that file are gone — you just copied another file over it. Don’t ever use this command unless you absolutely know that you don’t want the file. If you just need to get it out of the way, we’ll go over stashing and branching in the next chapter; these are generally better ways to go. + +Remember, anything that is committed in Git can almost always be recovered. Even commits that were on branches that were deleted or commits that were overwritten with an `--amend` commit can be recovered (see *Chapter 9* for data recovery). However, anything you lose that was never committed is likely never to be seen again. + +## Working with Remotes ## + +To be able to collaborate on any Git project, you need to know how to manage your remote repositories. Remote repositories are versions of your project that are hosted on the Internet or network somewhere. You can have several of them, each of which generally is either read-only or read/write for you. Collaborating with others involves managing these remote repositories and pushing and pulling data to and from them when you need to share work. +Managing remote repositories includes knowing how to add remote repositories, remove remotes that are no longer valid, manage various remote branches and define them as being tracked or not, and more. In this section, we’ll cover these remote-management skills. + +### Showing Your Remotes ### + +To see which remote servers you have configured, you can run the `git remote` command. It lists the shortnames of each remote handle you’ve specified. If you’ve cloned your repository, you should at least see *origin* — that is the default name Git gives to the server you cloned from: + + $ git clone git://github.com/schacon/ticgit.git + Initialized empty Git repository in /private/tmp/ticgit/.git/ + remote: Counting objects: 595, done. + remote: Compressing objects: 100% (269/269), done. + remote: Total 595 (delta 255), reused 589 (delta 253) + Receiving objects: 100% (595/595), 73.31 KiB | 1 KiB/s, done. + Resolving deltas: 100% (255/255), done. + $ cd ticgit + $ git remote + origin + +You can also specify `-v`, which shows you the URL that Git has stored for the shortname to be expanded to: + + $ git remote -v + origin git://github.com/schacon/ticgit.git + +If you have more than one remote, the command lists them all. For example, my Grit repository looks something like this. + + $ cd grit + $ git remote -v + bakkdoor git://github.com/bakkdoor/grit.git + cho45 git://github.com/cho45/grit.git + defunkt git://github.com/defunkt/grit.git + koke git://github.com/koke/grit.git + origin git@github.com:mojombo/grit.git + +This means we can pull contributions from any of these users pretty easily. But notice that only the origin remote is an SSH URL, so it’s the only one I can push to (we’ll cover why this is in *Chapter 4*). + +### Adding Remote Repositories ### + +I’ve mentioned and given some demonstrations of adding remote repositories in previous sections, but here is how to do it explicitly. To add a new remote Git repository as a shortname you can reference easily, run `git remote add [shortname] [url]`: + + $ git remote + origin + $ git remote add pb git://github.com/paulboone/ticgit.git + $ git remote -v + origin git://github.com/schacon/ticgit.git + pb git://github.com/paulboone/ticgit.git + +Now you can use the string `pb` on the command line in lieu 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: + + $ git fetch pb + remote: Counting objects: 58, done. + remote: Compressing objects: 100% (41/41), done. + remote: Total 44 (delta 24), reused 1 (delta 0) + Unpacking objects: 100% (44/44), done. + From git://github.com/paulboone/ticgit + * [new branch] master -> pb/master + * [new branch] ticgit -> pb/ticgit + +Paul’s master branch is accessible locally as `pb/master` — you can merge it into one of your branches, or you can check out a local branch at that point if you want to inspect it. + +### Fetching and Pulling from Your Remotes ### + +As you just saw, to get data from your remote projects, you can run: + + $ git fetch [remote-name] + +The command goes out to that remote project and pulls down all the data from that remote project that you don’t have yet. After you do this, you should have references to all the branches from that remote, which you can merge in or inspect at any time. (We’ll go over what branches are and how to use them in much more detail in *Chapter 3*.) + +If you clone a repository, the command automatically adds that remote repository under the name *origin*. So, `git fetch origin` fetches any new work that has been pushed to that server since you cloned (or last fetched from) it. It’s important to note that the `fetch` command pulls the data to your local repository — it doesn’t automatically merge it with any of your work or modify what you’re currently working on. You have to merge it manually into your work when you’re ready. + +If you have a branch set up to track a remote branch (see the next section and *Chapter 3* for more information), you can use the `git pull` command to automatically fetch and then merge a remote branch into your current branch. This may be an easier or more comfortable workflow for you; and by default, the `git clone` command automatically sets up your local master branch to track the remote master branch on the server you cloned from (assuming the remote has a master branch). Running `git pull` generally fetches data from the server you originally cloned from and automatically tries to merge it into the code you’re currently working on. + +### Pushing to Your Remotes ### + +When you have your project at a point that you want to share, you have to push it upstream. The command for this is simple: `git push [remote-name] [branch-name]`. If you want to push your master branch to your `origin` server (again, cloning generally sets up both of those names for you automatically), then you can run this to push your work back up to the server: + + $ git push origin master + +This command works only if you cloned from a server to which you have write access and if nobody has pushed in the meantime. If you and someone else clone at the same time and they push upstream and then you push upstream, your push will rightly be rejected. You’ll have to pull down their work first and incorporate it into yours before you’ll be allowed to push. See *Chapter 3* for more detailed information on how to push to remote servers. + +### Inspecting a Remote ### + +If you want to see more information about a particular remote, you can use the `git remote show [remote-name]` command. If you run this command with a particular shortname, such as `origin`, you get something like this: + + $ git remote show origin + * remote origin + URL: git://github.com/schacon/ticgit.git + Remote branch merged with 'git pull' while on branch master + master + Tracked remote branches + master + ticgit + +It lists the URL for the remote repository as well as the tracking branch information. The command helpfully tells you that if you’re on the master branch and you run `git pull`, it will automatically merge in the master branch on the remote after it fetches all the remote references. It also lists all the remote references it has pulled down. + +That is a simple example you’re likely to encounter. When you’re using Git more heavily, however, you may see much more information from `git remote show`: + + $ git remote show origin + * remote origin + URL: git@github.com:defunkt/github.git + Remote branch merged with 'git pull' while on branch issues + issues + Remote branch merged with 'git pull' while on branch master + master + New remote branches (next fetch will store in remotes/origin) + caching + Stale tracking branches (use 'git remote prune') + libwalker + walker2 + Tracked remote branches + acl + apiv2 + dashboard2 + issues + master + postgres + Local branch pushed with 'git push' + master:master + +This command shows which branch is automatically pushed when you run `git push` on certain branches. It also shows you which remote branches on the server you don’t yet have, which remote branches you have that have been removed from the server, and multiple branches that are automatically merged when you run `git pull`. + +### Removing and Renaming Remotes ### + +If you want to rename a reference, in newer versions of Git you can run `git remote rename` to change a remote’s shortname. For instance, if you want to rename `pb` to `paul`, you can do so with `git remote rename`: + + $ git remote rename pb paul + $ git remote + origin + paul + +It’s worth mentioning that this changes your remote branch names, too. What used to be referenced at `pb/master` is now at `paul/master`. + +If you want to remove a reference for some reason — you’ve moved the server or are no longer using a particular mirror, or perhaps a contributor isn’t contributing anymore — you can use `git remote rm`: + + $ git remote rm paul + $ git remote + origin + +## Tagging ## + +Like most VCSs, Git has the ability to tag specific points in history as being important. Generally, people use this functionality to mark release points (`v1.0`, and so on). In this section, you’ll learn how to list the available tags, how to create new tags, and what the different types of tags are. + +### Listing Your Tags ### + +Listing the available tags in Git is straightforward. Just type `git tag`: + + $ git tag + v0.1 + v1.3 + +This command lists the tags in alphabetical order; the order in which they appear has no real importance. + +You can also search for tags with a particular pattern. The Git source repo, for instance, contains more than 240 tags. If you’re only interested in looking at the 1.4.2 series, you can run this: + + $ git tag -l 'v1.4.2.*' + v1.4.2.1 + v1.4.2.2 + v1.4.2.3 + v1.4.2.4 + +### Creating Tags ### + +Git uses two main types of tags: lightweight and annotated. A lightweight tag is very much like a branch that doesn’t change — it’s just a pointer to a specific commit. Annotated tags, however, are stored as full objects in the Git database. They’re checksummed; contain the tagger name, e-mail, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG). It’s generally recommended that you create annotated tags so you can have all this information; but if you want a temporary tag or for some reason don’t want to keep the other information, lightweight tags are available too. + +### Annotated Tags ### + +Creating an annotated tag in Git is simple. The easiest way is to specify `-a` when you run the `tag` command: + + $ git tag -a v1.4 -m 'my version 1.4' + $ git tag + v0.1 + v1.3 + v1.4 + +The `-m` specifies a tagging message, which is stored with the tag. If you don’t specify a message for an annotated tag, Git launches your editor so you can type it in. + +You can see the tag data along with the commit that was tagged by using the `git show` command: + + $ git show v1.4 + tag v1.4 + Tagger: Scott Chacon + Date: Mon Feb 9 14:45:11 2009 -0800 + + my version 1.4 + commit 15027957951b64cf874c3557a0f3547bd83b3ff6 + Merge: 4a447f7... a6b4c97... + Author: Scott Chacon + Date: Sun Feb 8 19:02:46 2009 -0800 + + Merge branch 'experiment' + +That shows the tagger information, the date the commit was tagged, and the annotation message before showing the commit information. + +### Signed Tags ### + +You can also sign your tags with GPG, assuming you have a private key. All you have to do is use `-s` instead of `-a`: + + $ git tag -s v1.5 -m 'my signed 1.5 tag' + You need a passphrase to unlock the secret key for + user: "Scott Chacon " + 1024-bit DSA key, ID F721C45A, created 2009-02-09 + +If you run `git show` on that tag, you can see your GPG signature attached to it: + + $ git show v1.5 + tag v1.5 + Tagger: Scott Chacon + Date: Mon Feb 9 15:22:20 2009 -0800 + + my signed 1.5 tag + -----BEGIN PGP SIGNATURE----- + Version: GnuPG v1.4.8 (Darwin) + + iEYEABECAAYFAkmQurIACgkQON3DxfchxFr5cACeIMN+ZxLKggJQf0QYiQBwgySN + Ki0An2JeAVUCAiJ7Ox6ZEtK+NvZAj82/ + =WryJ + -----END PGP SIGNATURE----- + commit 15027957951b64cf874c3557a0f3547bd83b3ff6 + Merge: 4a447f7... a6b4c97... + Author: Scott Chacon + Date: Sun Feb 8 19:02:46 2009 -0800 + + Merge branch 'experiment' + +A bit later, you’ll learn how to verify signed tags. + +### Lightweight Tags ### + +Another way to tag commits is with a lightweight tag. This is basically the commit checksum stored in a file — no other information is kept. To create a lightweight tag, don’t supply the `-a`, `-s`, or `-m` option: + + $ git tag v1.4-lw + $ git tag + v0.1 + v1.3 + v1.4 + v1.4-lw + v1.5 + +This time, if you run `git show` on the tag, you don’t see the extra tag information. The command just shows the commit: + + $ git show v1.4-lw + commit 15027957951b64cf874c3557a0f3547bd83b3ff6 + Merge: 4a447f7... a6b4c97... + Author: Scott Chacon + Date: Sun Feb 8 19:02:46 2009 -0800 + + Merge branch 'experiment' + +### Verifying Tags ### + +To verify a signed tag, you use `git tag -v [tag-name]`. This command uses GPG to verify the signature. You need the signer’s public key in your keyring for this to work properly: + + $ git tag -v v1.4.2.1 + object 883653babd8ee7ea23e6a5c392bb739348b1eb61 + type commit + tag v1.4.2.1 + tagger Junio C Hamano 1158138501 -0700 + + GIT 1.4.2.1 + + Minor fixes since 1.4.2, including git-mv and git-http with alternates. + gpg: Signature made Wed Sep 13 02:08:25 2006 PDT using DSA key ID F3119B9A + gpg: Good signature from "Junio C Hamano " + gpg: aka "[jpeg image of size 1513]" + Primary key fingerprint: 3565 2A26 2040 E066 C9A7 4A7D C0C6 D9A4 F311 9B9A + +If you don’t have the signer’s public key, you get something like this instead: + + gpg: Signature made Wed Sep 13 02:08:25 2006 PDT using DSA key ID F3119B9A + gpg: Can't check signature: public key not found + error: could not verify the tag 'v1.4.2.1' + +### Tagging Later ### + +You can also tag commits after you’ve moved past them. Suppose your commit history looks like this: + + $ git log --pretty=oneline + 15027957951b64cf874c3557a0f3547bd83b3ff6 Merge branch 'experiment' + a6b4c97498bd301d84096da251c98a07c7723e65 beginning write support + 0d52aaab4479697da7686c15f77a3d64d9165190 one more thing + 6d52a271eda8725415634dd79daabbc4d9b6008e Merge branch 'experiment' + 0b7434d86859cc7b8c3d5e1dddfed66ff742fcbc added a commit function + 4682c3261057305bdd616e23b64b0857d832627b added a todo file + 166ae0c4d3f420721acbb115cc33848dfcc2121a started write support + 9fceb02d0ae598e95dc970b74767f19372d61af8 updated rakefile + 964f16d36dfccde844893cac5b347e7b3d44abbc commit the todo + 8a5cbc430f1a9c3d00faaeffd07798508422908a updated readme + +Now, suppose you forgot to tag the project at `v1.2`, which was at the "updated rakefile" commit. You can add it after the fact. To tag that commit, you specify the commit checksum (or part of it) at the end of the command: + + $ git tag -a v1.2 9fceb02 + +You can see that you’ve tagged the commit: + + $ git tag + v0.1 + v1.2 + v1.3 + v1.4 + v1.4-lw + v1.5 + + $ git show v1.2 + tag v1.2 + Tagger: Scott Chacon + Date: Mon Feb 9 15:32:16 2009 -0800 + + version 1.2 + commit 9fceb02d0ae598e95dc970b74767f19372d61af8 + Author: Magnus Chacon + Date: Sun Apr 27 20:43:35 2008 -0700 + + updated rakefile + ... + +### Sharing Tags ### + +By default, the `git push` command doesn’t transfer tags to remote servers. You will have to explicitly push tags to a shared server after you have created them. This process is just like sharing remote branches — you can run `git push origin [tagname]`. + + $ git push origin v1.5 + Counting objects: 50, done. + Compressing objects: 100% (38/38), done. + Writing objects: 100% (44/44), 4.56 KiB, done. + Total 44 (delta 18), reused 8 (delta 1) + To git@github.com:schacon/simplegit.git + * [new tag] v1.5 -> v1.5 + +If you have a lot of tags that you want to push up at once, you can also use the `--tags` option to the `git push` command. This will transfer all of your tags to the remote server that are not already there. + + $ git push origin --tags + Counting objects: 50, done. + Compressing objects: 100% (38/38), done. + Writing objects: 100% (44/44), 4.56 KiB, done. + Total 44 (delta 18), reused 8 (delta 1) + To git@github.com:schacon/simplegit.git + * [new tag] v0.1 -> v0.1 + * [new tag] v1.2 -> v1.2 + * [new tag] v1.4 -> v1.4 + * [new tag] v1.4-lw -> v1.4-lw + * [new tag] v1.5 -> v1.5 + +Now, when someone else clones or pulls from your repository, they will get all your tags as well. + +## Tips and Tricks ## + +Before we finish this chapter on basic Git, a few little tips and tricks may make your Git experience a bit simpler, easier, or more familiar. Many people use Git without using any of these tips, and we won’t refer to them or assume you’ve used them later in the book; but you should probably know how to do them. + +### Auto-Completion ### + +If you use the Bash shell, Git comes with a nice auto-completion script you can enable. Download the Git source code, and look in the `contrib/completion` directory; there should be a file called `git-completion.bash`. Copy this file to your home directory, and add this to your `.bashrc` file: + + source ~/.git-completion.bash + +If you want to set up Git to automatically have Bash shell completion for all users, copy this script to the `/opt/local/etc/bash_completion.d` directory on Mac systems or to the `/etc/bash_completion.d/` directory on Linux systems. This is a directory of scripts that Bash will automatically load to provide shell completions. + +If you’re using Windows with Git Bash, which is the default when installing Git on Windows with msysGit, auto-completion should be preconfigured. + +Press the Tab key when you’re writing a Git command, and it should return a set of suggestions for you to pick from: + + $ git co + commit config + +In this case, typing `git co` and then pressing the Tab key twice suggests commit and config. Adding `m` completes `git commit` automatically. + +This also works with options, which is probably more useful. For instance, if you’re running a `git log` command and can’t remember one of the options, you can start typing it and press Tab to see what matches: + + $ git log --s + --shortstat --since= --src-prefix= --stat --summary + +That’s a pretty nice trick and may save you some time and documentation reading. + +### Git Aliases ### + +Git doesn’t infer your command if you type it in partially. If you don’t want to type the entire text of each of the Git commands, you can easily set up an alias for each command using `git config`. Here are a couple of examples you may want to set up: + + $ git config --global alias.co checkout + $ git config --global alias.br branch + $ git config --global alias.ci commit + $ git config --global alias.st status + +This means that, for example, instead of typing `git commit`, you just need to type `git ci`. As you go on using Git, you’ll probably use other commands frequently as well; in this case, don’t hesitate to create new aliases. + +This technique can also be very useful in creating commands that you think should exist. For example, to correct the usability problem you encountered with unstaging a file, you can add your own unstage alias to Git: + + $ git config --global alias.unstage 'reset HEAD --' + +This makes the following two commands equivalent: + + $ git unstage fileA + $ git reset HEAD fileA + +This seems a bit clearer. It’s also common to add a `last` command, like this: + + $ git config --global alias.last 'log -1 HEAD' + +This way, you can see the last commit easily: + + $ git last + commit 66938dae3329c7aebe598c2246a8e6af90d04646 + Author: Josh Goebel + Date: Tue Aug 26 19:48:51 2008 +0800 + + test for current head + + Signed-off-by: Scott Chacon + +As you can tell, Git simply replaces the new command with whatever you alias it to. However, maybe you want to run an external command, rather than a Git subcommand. In that case, you start the command with a `!` character. This is useful if you write your own tools that work with a Git repository. We can demonstrate by aliasing `git visual` to run `gitk`: + + $ git config --global alias.visual '!gitk' + +## Summary ## + +At this point, you can do all the basic local Git operations — creating or cloning a repository, making changes, staging and committing those changes, and viewing the history of all the changes the repository has been through. Next, we’ll cover Git’s killer feature: its branching model. diff --git a/es-mx/01-introduction/01-chapter1.markdown b/ca/01-introduction/01-chapter1.markdown similarity index 91% rename from es-mx/01-introduction/01-chapter1.markdown rename to ca/01-introduction/01-chapter1.markdown index 398db5eec..1944283d7 100644 --- a/es-mx/01-introduction/01-chapter1.markdown +++ b/ca/01-introduction/01-chapter1.markdown @@ -1,14 +1,14 @@ -# Getting Started # +# Comencem # -This chapter will be about getting started with Git. We will begin at the beginning by explaining some background on version control tools, then move on to how to get Git running on your system and finally how to get it setup to start working with. At the end of this chapter you should understand why Git is around, why you should use it and you should be all setup to do so. +Aquest capítol tracta com iniciar-se amb Git. Començarem explicant alguns conceptes relatius a les eines de control de versions, seguirem amb com instal·lar Git al nostre ordinador i finalment com configurar-lo per a treballar-hi. Al final d'aquest capítol, hauríes d'entendre el perquè de Git, perquè és recomanable utilitzar-lo i amb les bases preparades per a començar. -## About Version Control ## +## Control de Versions ## -What is version control, and why should you care? Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later. For the examples in this book you will use software source code as the files being version controlled, though in reality you can do this with nearly any type of file on a computer. +Que es el control de version i per què t'hauria d'importar? El control de versions es un sitema que registra els canvis a un arxiu o conjunt d'arxius de manera que despres pot recuperar cualsevol de les versions. Tot i que els exemples de control de versions del llibre son codi font, potfer servir gairebe quansevol mena de arxiu per del teu ordinador. -If you are a graphic or web designer and want to keep every version of an image or layout (which you would most certainly want to), a Version Control System (VCS) is a very wise thing to use. It allows you to revert files back to a previous state, revert the entire project back to a previous state, compare changes over time, see who last modified something that might be causing a problem, who introduced an issue and when, and more. Using a VCS also generally means that if you screw things up or lose files, you can easily recover. In addition, you get all this for very little overhead. +Si ets un disenyador gràfic o de pagines web i vols guardar cada escuna de les versions d'una imatge o disenys (que segur que vols) un sitema de control de versions (Version Control System -VCS-) sera una eina acurada. Et permetrà torna al estat anterior dels fitxers, tornar a un punt anterior de tot el projecte, comparà canvis en el proces, saber qui es el darrer a modificat coses que potser estant donant problemes, qui a introduit un tema i quant, i encara més coses. Fer servir VCS vol dir que si la pífias o pot arreglar, generalment. i tot aixo amb pocs costos. -### Local Version Control Systems ### +### Sitemas de control de versions locals ### Many people’s version-control method of choice is to copy files into another directory (perhaps a time-stamped directory, if they’re clever). This approach is very common because it is so simple, but it is also incredibly error prone. It is easy to forget which directory you’re in and accidentally write to the wrong file or copy over files you don’t mean to. @@ -73,7 +73,7 @@ This is an important distinction between Git and nearly all other VCSs. It makes ### Nearly Every Operation Is Local ### -Most operations in Git only need local files and resources to operate – generally no information is needed from another computer on your network. If you’re used to a CVCS where most operations have that network latency overhead, this aspect of Git will make you think that the gods of speed have blessed Git with unworldly powers. Because you have the entire history of the project right there on your local disk, most operations seem almost instantaneous. +Most operations in Git only need local files and resources to operate — generally no information is needed from another computer on your network. If you’re used to a CVCS where most operations have that network latency overhead, this aspect of Git will make you think that the gods of speed have blessed Git with unworldly powers. Because you have the entire history of the project right there on your local disk, most operations seem almost instantaneous. For example, to browse the history of the project, Git doesn’t need to go out to the server to get the history and display it for you—it simply reads it directly from your local database. This means you see the project history almost instantly. If you want to see the changes introduced between the current version of a file and the file a month ago, Git can look up the file a month ago and do a local difference calculation, instead of having to either ask a remote server to do it or pull an older version of the file from the remote server to do it locally. @@ -112,9 +112,9 @@ The staging area is a simple file, generally contained in your Git directory, th The basic Git workflow goes something like this: -1. You modify files in your working directory. -2. You stage the files, adding snapshots of them to your staging area. -3. You do a commit, which takes the files as they are in the staging area and stores that snapshot permanently to your Git directory. +1. You modify files in your working directory. +2. You stage the files, adding snapshots of them to your staging area. +3. You do a commit, which takes the files as they are in the staging area and stores that snapshot permanently to your Git directory. If a particular version of a file is in the git directory, it’s considered committed. If it’s modified but has been added to the staging area, it is staged. And if it was changed since it was checked out but has not been staged, it is modified. In Chapter 2, you’ll learn more about these states and how you can either take advantage of them or skip the staged part entirely. @@ -132,7 +132,7 @@ To install Git, you need to have the following libraries that Git depends on: cu openssl-devel zlib-devel $ apt-get install libcurl4-gnutls-dev libexpat1-dev gettext \ - libz-dev + libz-dev libssl-dev When you have all the necessary dependencies, you can go ahead and grab the latest snapshot from the Git web site: @@ -140,8 +140,8 @@ When you have all the necessary dependencies, you can go ahead and grab the late Then, compile and install: - $ tar -zxf git-1.6.0.5.tar.gz - $ cd git-1.6.0.5 + $ tar -zxf git-1.7.2.2.tar.gz + $ cd git-1.7.2.2 $ make prefix=/usr/local all $ sudo make prefix=/usr/local install @@ -157,13 +157,13 @@ If you want to install Git on Linux via a binary installer, you can generally do Or if you’re on a Debian-based distribution like Ubuntu, try apt-get: - $ apt-get install git-core + $ apt-get install git ### Installing on Mac ### -There are two easy ways to install Git on a Mac. The easiest is to use the graphical Git installer, which you can download from the Google Code page (see Figure 1-7): +There are two easy ways to install Git on a Mac. The easiest is to use the graphical Git installer, which you can download from the SourceForge page (see Figure 1-7): - http://code.google.com/p/git-osx-installer + http://sourceforge.net/projects/git-osx-installer/ Insert 18333fig0107.png Figure 1-7. Git OS X installer. @@ -176,9 +176,9 @@ You don’t have to add all the extras, but you’ll probably want to include +s ### Installing on Windows ### -Installing Git on Windows is very easy. The msysGit project has one of the easier installation procedures. Simply download the installer exe file from the Google Code page, and run it: +Installing Git on Windows is very easy. The msysGit project has one of the easier installation procedures. Simply download the installer exe file from the GitHub page, and run it: - http://code.google.com/p/msysgit + http://msysgit.github.com/ After it’s installed, you have both a command-line version (including an SSH client that will come in handy later) and the standard GUI. diff --git a/ca/README.txt b/ca/README.txt new file mode 100644 index 000000000..bf9295916 --- /dev/null +++ b/ca/README.txt @@ -0,0 +1 @@ +TRADUCCI AL CATAL de progit. Qualsevol aportaci o comentari, s benvingut/da. a@alexandresaiz.com \ No newline at end of file diff --git a/cs/01-introduction/01-chapter1.markdown b/cs/01-introduction/01-chapter1.markdown index 167dc9054..6a29be757 100644 --- a/cs/01-introduction/01-chapter1.markdown +++ b/cs/01-introduction/01-chapter1.markdown @@ -1,321 +1,227 @@ # Úvod # -V této kapitole si vysvětlíme, jak začít s Gitem. Jak fungují systémy kontroly verzí, ukážeme si, jak Git nainstalovat -a jak ho nastavit tak, abychom s ním mohli pohodlně pracovat. Objasníme si, proč Git používá tolik lidí -a proč byste ho měli používat i vy. +Tato kapitola vám ve stručnosti představí systém Git. Začneme od samého začátku. Nahlédneme do historie nástrojů ke správě verzí, poté se budeme věnovat tomu, jak spustit systém Git ve vašem počítači, a nakonec se podíváme na možnosti úvodního nastavení. V této kapitole se dozvíte, k čemu Git slouží a proč byste ho měli používat. Kromě toho se také naučíte, jak Git nastavit podle svých potřeb. ## Správa verzí ## -Co je to správa verzí? Proč by vás to vůbec mělo zajímat? Správa verzí je systém, -který zaznamenává změny souborů v čase tak, že se v případě potřeby můžeme vrátit -k některé z předchozích verzí. Pro příklady v této knize použijeme zdrojový kód softwaru -jako ony spravované soubory, ale samozřejmě to není nutné -- můžete spravovat v podstatě -jakýkoli druh souborů. +Co je to správa verzí a proč by vás měla zajímat? Správa verzí je systém, který zaznamenává změny souboru nebo sady souborů v průběhu času, a uživatel tak může kdykoli obnovit jeho/jejich konkrétní verzi (tzv. verzování). Příklady verzovaných souborů jsou v této knize ilustrovány na zdrojovém kódu softwaru, avšak ve skutečnosti lze verzování provádět téměř se všemi typy souborů v počítači. -Pokud jste grafik nebo web-designer a chcete si schovat každou verzi obrázku nebo -rozvržení stránky (což zcela jistě budete chtít), je velmi moudré rozhodnutí použít -systém pro správu verzí (SSV).[^1] Umožňuje vám vrátit jednotlivé soubory nebo celý projekt -do nějakého z předchozích stavů, porovnávat změny, vidět, kdo naposledy změnil soubor, ve kterém -se objevil nějaký problém, kdo napsal chybový kód a mnohé další ... Používat SSV také obecně -znamená, že pokud něco zkazíte nebo přijdete o nějaké soubory, můžete se jed\-no\-du\-še vrátit. -Navíc s minimálními režijními náklady. +Pokud jste grafik nebo webdesigner a chcete uchovávat všechny verze obrázku nebo všechna rozložení stránky (což jistě není k zahození), je pro vás systém správy verzí (zkráceně VCS z anglického Version Control System) ideálním nástrojem. VCS umožňuje vrátit jednotlivé soubory nebo celý projekt do předchozího stavu, porovnávat změny provedené v průběhu času, zjistit, kdo naposledy upravil něco, co nyní možná způsobuje problémy, kdo vložil jakou verzi a kdy a mnoho dalšího. Používáte-li verzovací systém, většinou to také znamená, že snadno obnovíte soubory, které jste ztratili nebo v nichž byly provedeny nežádoucí změny. Všechny funkcionality verzovacího systému můžete navíc používat velice jednoduchým způsobem. -[^1]: Pozn. překl.: V anglickém originále VCS -- Version Control System +### Lokální systémy správy verzí ### -### Místní systémy správy verzí ### +Uživatelé často provádějí správu verzí tím způsobem, že zkopírují soubory do jiného adresáře (pokud jsou chytří, označí adresář i příslušným datem). Takový přístup je velmi častý, protože je jednoduchý. Je s ním však spojeno také velké riziko omylů a chyb. Člověk snadno zapomene, ve kterém adresáři se právě nachází, a nedopatřením začne zapisovat do nesprávného souboru nebo přepíše nesprávné soubory. -Mnoha lidmi používaná metoda je prosté kopírování souborů na jiné místo, občas označené -např. datem, pokud jsou chytřejší. Tento přístup je oblíbený pro svoji jednoduchost, ale -je neskutečně chybový. Je tak jednoduché zapomenout, ve kterém adresáři se zrovna nacházíte, -a omylem zapsat do špatného souboru nebo chybně kopírovat. +Aby se uživatelé tomuto riziku vyhnuli, vyvinuli programátoři už před dlouhou dobou lokální systémy VCS s jednoduchou databází, která uchovávala všechny změny souborů s nastavenou správou revizí (viz obrázek 1-1). -Kdysi dávno právě z těchto důvodů vznikly místní SSV, které v jednoduché databázi udržovaly -všechny změny spravovaných souborů (obr. 1-1). +Insert 18333fig0101.png +Obrázek 1-1. Diagram lokální správy verzí -Insert 18333fig0101.png -Obrázek 1-1. Místní SSV - -Jeden z populárnějších SSV byl program rcs, který je stále ještě dodáván i s mnoha dnešními počítači. -Zvláště populární operační systém Mac OS X obsahuje příkaz rcs, když instalujete Developer Tools. -Funguje v podstatě na principu uchovávání patchů mezi jednotlivými změnami ve speciálním formátu -na disku, takže může obnovit jakýkoli bod v minulosti aplikováním všech těchto patchů v sérii. +Jedním z velmi oblíbených nástrojů VCS byl systém s názvem rcs, který je ještě dnes distribuován s mnoha počítači. Dokonce i populární operační systém Mac OS X obsahuje po nainstalování vývojářských nástrojů (Developer Tools) příkaz rcs. Tento nástroj pracuje na tom principu, že na disku uchovává ve speciálním formátu seznam změn mezi jednotlivými verzemi. Systém později může díky porovnání těchto změn vrátit jakýkoli soubor do podoby, v níž byl v libovolném okamžiku. ### Centralizované systémy správy verzí ### -Další požadavek na SSV je, aby umožnil spolupráci více vývojářů z různých koutů světa. Proto byly vytvořeny -centralizované systémy správy verzí (CSSV). Tyto systémy, jako např. CVS, Subversion nebo Perforce, -mají vždy jeden server, který obsahuje všechny spravované soubory ve všech verzích, a množství klientů, -již stahují soubory z tohoto jednoho centrálního místa. Po mnoho let byl toto standard ve správě verzí (obr. 1-2). +Dalším velkým problémem, s nímž se uživatelé potýkají, je potřeba spolupráce s dalšími pracovníky týmu. Řešení tohoto problému nabízejí tzv. centralizované systémy správy verzí (CVCS z angl. Centralized Version Control System). Tyto systémy, jmenovitě např. CVS, Subversion či Perforce, obsahují serverovou část, která uchovává všechny verzované soubory. Z tohoto centrálního úložiště si potom soubory stahují jednotliví klienti. Tento koncept byl dlouhá léta standardem pro správu verzí (viz obrázek 1-2). -Insert 18333fig0102.png -Obrázek 1-2. Centralizovaný SSV +Insert 18333fig0102.png +Obrázek 1-2. Diagram centralizované správy verzí -Toto uspořádání přináší mnoho výhod, zvláště proti místním SSV. Třeba všichni ví do jisté míry, kdo další -se ještě na projektu podílí. Administrátoři mají přesnou kontrolu nad tím, kdo co dělá -- je to daleko jednodušší -než spravovat místní databáze u každého klienta zvlášť. +Nabízí ostatně mnoho výhod, zejména v porovnání s lokálními systémy VCS. Každý například — do určité míry — ví, co dělají ostatní účastníci projektu a administrátoři mají přesnou kontrolu nad jednotlivými právy. Kromě toho je podstatně jednodušší spravovat CVCS, než pracovat s lokálními databázemi na jednotlivých klientech. -Samozřejmě to má i vážná úskalí. Nejviditelnější je asi ten jeden jediný bod uprostřed reprezentovaný centralizovaným -serverem. Když má server hodinový výpadek, pak samozřejmě behem této hodiny nikdo nepřispěje, nikdo nemůže uložit -své provedené změny na projektu, na kterém právě pracuje. Pokud dojde k poruše harddisku centrální databáze a nikdo dostatečně nezálohoval, -pak ztratíte absolutně všechno. Kompletní historii projektu kromě nějakých osamělých kopií, které mají uživatelé a vývojáři na svém -vlastním počítači. Tím mimochodem trpí i místní SSV -- jakmile máte všechno na jednom místě, riskujete, -že při neopatrnosti nebo poruše jednoduše přijdete o všechno. +Avšak i tato koncepce má závažné nedostatky. Tímto nejkřiklavějším je riziko kolapsu celého projektu po výpadku jediného místa — centrálního serveru. Pokud takový server na hodinu vypadne, pak během této hodiny buď nelze pracovat vůbec, nebo přinejmenším není možné ukládat změny ve verzích souborů, na nichž uživatelé právě pracují. A dojde-li k poruše pevného disku, na němž je uložena centrální databáze, a disk nebyl předem zálohován, dojde ke ztrátě všech dat, celé historie projektu, s výjimkou souborů aktuálních verzí, jež mají uživatelé v lokálních počítačích. Ke stejnému riziku jsou náchylné také lokální systémy VCS. Jestliže máte celou historii projektu uloženou na jednom místě, hrozí, že přijdete o vše. ### Distribuované systémy správy verzí ### -Proto nastoupily na scénu distribuované SSV (DSSV). V takovém systému (Git, Mercurial, Bazaar, Darcs apod.) -klient neuchovává jen poslední verzi souborů, nýbrž vytváří kompletní duplikát repositáře. Pak pokud nějaký -server v těchto podmínkách odejde do počítačového nebe, nic se vlastně nestane. Jakýkoli repositář u klienta -je možno nahrát zpět na server a jede se dál. Každý checkout je v podstatě kompletní záloha všech dat (obr. 1-3) +V tomto místě přicházejí ke slovu tzv. distribuované systémy správy verzí (DVCS z angl. Distributed Version Control System). V systémech DVCS (např. Git, Mercurial, Bazaar nebo Darcs) uživatelé nestahují pouze nejnovější verzi souborů (tzv. snímek, anglicky snapshot), ale uchovávají kompletní kopii repozitáře (repository). Pokud v takové situaci dojde ke kolapsu serveru, lze jej obnovit zkopírováním repozitáře od libovolného uživatele. Každá lokální kopie (checkout) je plnohodnotnou zálohou všech dat (viz obrázek 1-3). -Insert 18333fig0103.png -Obrázek 1-3. Distribuovaný SSV +Insert 18333fig0103.png +Obrázek 1-3. Diagram distribuované správy verzí -Navíc mnoho těchto systémů umí slušně pracovat s více vzdálenými repositáři najednou, takže můžete spolupracovat -s různými skupinami lidí na různých částech téhož projektu. To umožňuje mít různé způsoby organizace práce, -které v centralizovaných systémech vůbec nejsou možné, jako je hierarchický model. +Mnoho z těchto systémů navíc bez větších obtíží pracuje i s několika vzdálenými repozitáři, takže můžete v rámci jednoho projektu různým způsobem spolupracovat s různými skupinami lidí najednou. Můžete zavést několik typů pracovních postupů, které nejsou v centralizovaných systémech možné — jako jsou například hierarchické modely. -## Stručná historie Gitu ## +## Stručná historie systému Git ## -Stejně jako mnoho velkých událostí i historie Gitu začíná trochou tvořivé destrukce a prudké kontroverze. -Linuxové jádro je dosti rozsáhlý open-source softwarový projekt. Nejprve docela dlouho (1991-2002) byly -změny kódu prováděny jako patche a archivované soubory. V roce 2002 pak projekt přešel na proprietární DSSV -BitKeeper. +Tak jako mnoho velkých věcí v lidské historii se i systém Git zrodil z kreativní destrukce a vášnivého sporu. Jádro Linuxu je software celkem velkého rozsahu, s otevřeným kódem. V letech 1991 — 2002 bylo jádro Linuxu spravováno formou záplat a archivních souborů. V roce 2002 začal projekt vývoje linuxového jádra využívat komerční systém DVCS s názvem BitKeeper. -Po třech letech (2005) ochladly vztahy mezi vývojáři jádra a firmou, která BitKepper vyvinula, už neměl být zdarma, -a tak se komunita vývojářů jádra (zvláště Linus Torvalds, tvůrce Linuxu) rozhodla vytvořit vlastní DSSV -postavený na získaných zkušenostech z BitKeeperu. Požadované vlastnosti nového systému byly: +V roce 2005 se zhoršily vztahy mezi komunitou, která vyvíjela jádro Linuxu, a komerční společností, která vyvinula BitKeeper, a společnost přestala tento systém poskytovat zdarma. To přimělo komunitu vývojářů Linuxu (a zejména Linuse Torvaldse, tvůrce Linuxu), aby vyvinula vlastní nástroj, založený na poznatcích, které nasbírala při užívání systému BitKeeper. Mezi požadované vlastnosti systému patřily zejména: -* Rychlost -* Jednoduchý návrh -* Propracovaná podpora pro nelineární vývoj (tisíce paralelních větví) -* Plná distribuovanost -* Schopnost udržet tak velký projekt jako jádro Linuxu úsporně z hlediska rychlosti i množství dat +* Rychlost, +* jednoduchý design, +* silná podpora nelineárního vývoje (tisíce paralelních větví), +* plná distribuovatelnost, +* schopnost efektivně spravovat velké projekty, jako je linuxové jádro (rychlost a objem dat). -Od jeho zrodu v roce 2005 se Git vyvinul a dospěl do jednoduše použitelného systému a stále splňuje tyto původní -předpoklady. Je neuvěřitelně rychlý, bez velkých režijních nákladů i u obrovských projektů a má nevídaný systém větvení (kap. 3) -pro nelineární vývoj. +Od svého vzniku v roce 2005 se Git vyvinul a vyzrál v snadno použitelný systém, který si dodnes uchovává své prvotní kvality. Je extrémně rychlý, velmi efektivně pracuje i s velkými projekty a nabízí skvělý systém větvení pro nelineární způsob vývoje (viz kapitola 3). -## Základy Gitu ## -Takže v kostce, co je to Git? Tohle je důležité vědět, protože pokud budete rozumět, co to Git je a jak zhruba funguje, -bude pro vás pravděpodobně výrazně jednodušší ho používat efektivně. Až se Git naůčíte, zkuste zapomenout všechno, -co jste věděli o ostatních SSV jako Subversion nebo Perforce. Git ukládá informace a přemýšlí o nich naprosto -odlišným způsobem i přesto, že uživatelské rozhraní je dosti podobné. Porozumět těmto drobným rozdílům pomůže -překonat možnou prvotní zmatenost z přechodu na Git. +## Základy systému Git ## -### Snapshoty, ne rozdíly ### +Jak bychom tedy mohli Git charakterizovat? Odpověď na tuto otázku je velmi důležitá, protože pokud pochopíte, co je Git a na jakém principu pracuje, budete ho bezpochyby moci používat mnohem efektivněji. Při seznámení se systémem Git se pokuste zapomenout na vše, co už možná víte o jiných systémech VCS, např. Subversion nebo Perforce. Vyhnete se tak nežádoucím vlivům, které by vás mohly při používání systému Git mást. Ačkoli je uživatelské rozhraní velmi podobné, Git ukládá a zpracovává informace poněkud odlišně od ostatních systémů. Pochopení těchto rozdílů vám pomůže předejít nejasnostem, které mohou při používání systému Git vzniknout. -Hlavní rozdíl mezi Gitem a ostatními SSV (Subversion a jeho přátelé) je způsob, jakým Git přemýšlí nad svými daty. -Koncepcí většiny ostatních systémů je ukládat informace jako seznam změn v jednotlivých souborech. Udržují si sadu souborů -a změny v nich provedené (obr. 1-4). +### Snímky, nikoli rozdíly ### -Insert 18333fig0104.png -Obrázek 1-4. Ostatní systémy ukládají data jako změny každého souboru. +Hlavním rozdílem mezi systémem Git a všemi ostatními systémy VCS (včetně Subversion a jemu podobných) je způsob, jakým Git zpracovává data. Většina ostatních systémů ukládá informace jako seznamy změn jednotlivých souborů. Tyto systémy (CVS, Perforce, Bazaar atd.) chápou uložené informace jako sadu souborů a seznamů změn těchto souborů v čase — viz obrázek 1-4. -Gitu je takovýto přístup cizí. Místo toho jsou pro něj data spíše mnoho snapshotů malého filesystému. Pokaždé, když commitnete[^2] -stav svého projektu do Gitu, jednoduše si udělá obrázek, jak teď právě vypadají všechny soubory, a uloží to. Pro úsporu -si nezměněné soubory ukládá jen jako odkaz na předchozí identický soubor. Git přemýšlí nad daty asi jako na obrázku 1-5. +Insert 18333fig0104.png +Obrázek 1-4. Ostatní systémy ukládají data jako změny v základní verzi každého souboru. -[^2]: Pozn. překl.: Český ekvivalent "předáte" se v podstatě neužívá. +Git zpracovává data jinak. Chápe je spíše jako sadu snímků (snapshots) vlastního malého systému souborů. Pokaždé, když v systému zapíšete (uložíte) stav projektu, Git v podstatě „vyfotí“, jak vypadají všechny vaše soubory v daném okamžiku, a uloží reference na tento snímek. Pokud v souborech nebyly provedeny žádné změny, Git v zájmu zefektivnění práce neukládá znovu celý soubor, ale pouze odkaz na předchozí identický soubor, který už byl uložen. Zpracování dat v systému Git ilustruje obrázek 1-5. -Insert 18333fig0105.png -Obrázek 1-5. Git ukládá data jako snapshoty projektu. +Insert 18333fig0105.png +Obrázek 1-5. Git ukládá data jako snímky projektu proměnlivé v čase. -To je důležitý rozdíl mezi Gitem a skoro všemi ostatními SSV. Nutí to Git znovu uvážit téměř každý aspekt správy verzí, které většina -ostatních systémů převzala z předchozí generace. To dělá z Gitu spíše malý filesystém s několika neuvěřitelně mocnými nástroji -nad sebou než prostě SSV. K některým výhodám tohoto přístupu dojdeme v kapitole 3, kde se budeme zabývat větvením vývojového stromu. +Toto je důležitý rozdíl mezi systémem Git a téměř všemi ostatními systémy VCS. Git díky tomu znovu zkoumá skoro každý aspekt správy verzí, které ostatní systémy kopírovaly z předchozí generace. Git se podobá malému systému souborů (spíše než obyčejnému VCS) s řadou skutečně výkonných nástrojů, jež jsou na něm postavené. Některé přednosti, které tato metoda správy dat nabízí, si podrobně ukážeme na systému větvení v kapitole 3. -### Většině operací stačí váš stroj ### +### Téměř každá operace je lokální ### -Drtivá většina operací v Gitu nepotřebuje víc než místní soubory a zdroje. Obecně nepotřebuje žádnou informawci z jiného než vašeho stroje. -Pokud jste zvyklí na CSSV, kde téměř všechny operace mají režijní náklady zvýšené o zpoždění na síti, pak si budete myslet, že božstvo rychlosti -požehnalo Gitu a udělilo mu nadzemskou moc. Protože máte celou historii projektu právě u sebe na místním disku, vypadá většina operací, -že jsou vykonány okamžitě. +Většina operací v systému Git vyžaduje ke své činnosti pouze lokální soubory a zdroje a nejsou potřeba informace z jiných počítačů v síti. Pokud jste zvyklí pracovat se systémy CVCS, kde je většina operací poznamenána latencí sítě, patrně vás při práci v systému Git napadne, že mu bohové rychlosti dali do vínku nadpřirozené schopnosti. Protože máte celou historii projektu uloženou přímo na svém lokálním disku, probíhá většina operací takřka okamžitě. -Například pokud si chcete prohlédnout historii projektu, Git nepotřebuje jít na server, aby získal historii a zobrazil ji pro vás -- jednoduše -ji přečte přímo z vaší místní databáze. To znamená, že historii projektu vidíte téměř hned. Pokud chcete vidět změny mezi současnou verzí souboru -a verzí měsíc starou, Git najde soubor v místní databázi a spočítá rozdíly lokálně místo toho, aby o to buďto požádal vzdálený server, nebo alespoň -stáhl starou verzi. +Pokud chcete například procházet historii projektu, Git kvůli tomu nemusí vyhledávat informace na serveru — načte je jednoduše přímo z vaší lokální databáze. Znamená to, že se historie projektu zobrazí téměř hned. Pokud si chcete prohlédnout změny provedené mezi aktuální verzí souboru a týmž souborem před měsícem, Git vyhledá měsíc starý soubor a provede lokální výpočet rozdílů, aniž by o to musel žádat vzdálený server nebo stahovat starší verzi souboru ze vzdáleného serveru a poté provádět lokální výpočet. -To také znamená, že je velmi málo toho, co nemůžete dělat, pokud jste offline. Sedíte-li na palubě letadla nebo ve vlaku a chcete udělat trochu práce, -můžete vesele commitovat, i když zrovna nemáte připojení k síti. Pokud jste doma a nemůžete se připojit k repositáři, -můžete stále pracovat. U mnoha jiných systému je to dosti bolestivý proces, ne-li zhola nemožný. -V Perforce např. nemůžete dělat skoro nic; v Subversion nebo CVS můžete upravovat soubory, ale -předat je nejde (logicky -- databáze je offline). To nemusí vypadat jako velká změna, ale může vás příjemně překvapit, jak výrazný rozdíl to může být. +To také znamená, že je jen velmi málo operací, které nemůžete provádět offline nebo bez připojení k VPN. Jste-li v letadle nebo ve vlaku a chcete pokračovat v práci, můžete beze všeho zapisovat nové revize. Ty odešlete až po opětovném připojení k síti. Jestliže přijedete domů a zjistíte, že VPN klient nefunguje, stále můžete pracovat. V mnoha jiných systémech je takový postup nemožný nebo přinejmenším obtížný. Například v systému Perforce toho lze bez připojení k serveru dělat jen velmi málo, v systémech Subversion a CVS můžete sice upravovat soubory, ale nemůžete zapisovat změny do databáze, neboť ta je offline. Možná to vypadá jako maličkost, ale divili byste se, jak velký je v tom rozdíl. -### Git drží integritu ### +### Git pracuje důsledně ### -Než je cokoli v Gitu uloženo, je tomu spočítán kontrolní součet. Ten se potom používá i k identifikaci celého commitu. -To znamená, že je zhola nemožné změnit obsah jakéhokoli souboru nebo adresáře bez toho, aby o tom Git věděl. Tato vlastnost -je do Gitu zabudována na těch nejnižších úrovních a je nedílnou součástí jeho filosofie. Nemůžete ztratit informace při přenosu -nebo přijít k poškození dat bez toho, aby to byl Git schopen odhalit. +Než je v systému Git cokoli uloženo, je nejprve proveden kontrolní součet, který je potom používán k identifikaci uloženého souboru. Znamená to, že není možné změnit obsah jakéhokoli souboru nebo adresáře, aniž by o tom Git nevěděl. Tato funkce je integrována do systému Git na nejnižších úrovních a je nedílnou součástí jeho filozofie. Nemůže tak dojít ke ztrátě informací při přenosu dat nebo k poškození souboru, aniž by to byl Git schopen zjistit. -Git k tomu používá mechanismus zvaný SHA-1 hash. To je 40 znaků dlouhý řetězec sestávající z hexadecimálních znaků (0-9 a a-f) -a spočítaný na základě obsahu souboru nebo adresářové struktury v Gitu. SHA-1 hash vypadá nějak takto: +Mechanismus, který Git k tomuto kontrolnímu součtu používá, se nazývá otisk SHA-1 (SHA-1 hash). Jedná se o řetězec o 40 hexadecimálních znacích (0–9; a–f) vypočítaný na základě obsahu souboru nebo adresářové struktury systému Git. Otisk SHA-1 může vypadat například takto: 24b9da6552252987aa493b52f8696cd6d3b00373 -S těmito hashi se v Gitu setkáte úplně všude. V podstatě Git všechno ukládá nikoli na základě jména souboru, ale právě na základě -hashe jeho obsahu. +S těmito otisky se budete setkávat ve všech úložištích systému Git, protože je používá opravdu často. Git nic neukládá podle názvu souboru. Místo toho používá databázi adresovatelnou hodnotou otisku, který odpovídá obsahu souboru. -### Git obecně jen přidává data ### +### Git většinou jen přidává data ### -Pokud něco v Gitu děláte, téměř cokoli z toho jen přidá data do jeho databáze. Je opravdu obtížné donutit systém udělat něco, co by se nedalo vrátit, -nebo donutit ho nějakým způsobem smazat svoje data. Jako v každém SSV můžete samozřejmě ztratit změny provedené od posledního commitu, -ale jakmile jsou commitnuty, je velmi obtížné o ně přijít, zvláště pak pokud pravidelně zálohujete databázi do jiného repositáře. +Jednotlivé operace ve většině případů jednoduše přidávají data do Git databáze. Přimět systém, aby udělal něco, co nelze vzít zpět, nebo aby smazal jakákoli data, je velice obtížné. Stejně jako ve všech systémech VCS můžete ztratit nebo nevratně zničit změny, které ještě nebyly zapsány. Jakmile však jednou zapíšete snímek do systému Git, je téměř nemožné ho ztratit, zvlášť pokud pravidelně zálohujete databázi do jiného repozitáře. -Je pak radost používat Git, protože víme, že můžeme experimentovat bez nebezpečí, že bychom si něco vážně poškodili. Pro hlubší náhled do problematiky, -jak Git ukládá data a jak se můžete vrátit k datům, která vypadají, že jsou ztracena, si přečtěte kapitolu 9. +Díky tomu vás bude práce se systémem Git bavit. Budete pracovat s vědomím, že můžete experimentovat, a neriskujete přitom nevratné zničení své práce. Podrobnější informace o tom, jak Git ukládá data a jak lze obnovit zdánlivě ztracenou práci, najdete v kapitole 9. ### Tři stavy ### -Teď dávejte pozor. Tohle je hlavní věc, kterou si u Gitu musíte pamatovat, pokud chcete, aby vaše další studium Gitu šlo hladce. -Git má tři základní stavy, kterých můžou vaše soubory nabývat: "commited", "modified" a "staged"[^3]. -Commited znamená, že data jsou bezpečně uložena v místní databázi. Modified znamená, že soubor byl oproti poslednímu předání změněn. -A staged je ten soubor, u kterého máte značku, že bude v této verzi zařazen do nejbližšího commitu. - -[^3]: Pozn. překl.: Vzhledem k neexistující lokalizaci Gitu do češtiny budu nadále používat tyto anglické výrazy, -se kterými se v Gitu setkáte de facto na každém rohu narozdíl od českých ekvivalentů. - -To nás vede ke třem hlavním sekcím projektu v Gitu: Git directory, working directory a staging area[^4]. +A nyní pozor. Pokud chcete dále hladce pokračovat ve studiu Git, budou pro vás následující informace stěžejní. Git používá pro spravované soubory tři základní stavy: zapsáno (committed), změněno (modified) a připraveno k zapsání (staged). Zapsáno znamená, že jsou data bezpečně uložena ve vaší lokální databázi. Změněno znamená, že v souboru byly provedeny změny, avšak soubor ještě nebyl zapsán do databáze. Připraveno k zapsání znamená, že jste změněný soubor v jeho aktuální verzi určili k tomu, aby byl zapsán v další revizi (tzv. commit). -[^4]: Pozn. překl.: Jako u předchozího. Tyto výrazy nemá nejmenší smysl překládat do češtiny. +Z toho vyplývá, že projekt je v systému Git rozdělen do tří hlavních částí: adresář systému Git (Git directory), pracovní adresář (working directory) a oblast připravených změn (staging area). -Insert 18333fig0106.png -Figure 1-6. Git directory, working directory a staging area +Insert 18333fig0106.png +Obrázek 1-6. Pracovní adresář, oblast připravených změn a adresář Git -Git directory je místo, kde Git skladuje svoje vnitřní data a databázi objektů vašeho projektu. To je ta nejdůležitější část Gitu, -která se kopíruje, pokud si stahujete repositář z jiného počítače. +Adresář Git (repozitář) je místo, kde Git uchovává metadata a databázi objektů vašeho projektu. Je to nejdůležitější část systému Git a zároveň adresář, který se zkopíruje, když klonujete repozitář z jiného počítače. -Working directory je samotný obraz jedné verze spravovaného projektu. Jsou to soubory vytažené z databáze v Git directory -a umístěné na disk, abyste je použili nebo měnili. +Pracovní adresář obsahuje lokální kopii jedné verze projektu. Tyto soubory jsou staženy ze zkomprimované databáze v adresáři Git a umístěny na disk, kde je můžete používat nebo upravovat. -Staging area je jednoduchý soubor, obvykle uložený ve vašem Git directory, který ukládá informace o tom, co bude součástí nejbližšího commitu. -Občas je též nazýván index, ale v angličtině se postupně stává standardem označovat ho jako "staging area". +Oblast připravených změn je jednoduchý soubor, většinou uložený v adresáři Git, který obsahuje informace o tom, co bude obsahovat příští revize. Soubor se někdy označuje také anglickým výrazem „index“, ale oblast připravených změn (staging area) je už dnes termín běžnější. -Základní pracovní postup Gitu je pak zhruba takovýto: +Standardní pracovní postup vypadá v systému Git následovně: -1. Změníte soubory ve svém working directory. -2. Vložíte soubory do staging area. -3. Vytvoříte commit, který vezme všechny soubory tak, jak jsou ve staging area, a uloží tento snímek permanentně do Git directory. +1. Změníte soubory ve svém pracovním adresáři. +2. Soubory připravíte k uložení tak, že vložíte jejich snímky do oblasti připravených změn. +3. Zapíšete revizi. Snímky souborů, uložené v oblasti připravených změn, se trvale uloží do adresáře Git. -Pokud je nějaká verze souboru v Git directory, je označována jako commited, pokud je upravena a vložena do staging area, je staged. A konečně -pokud byla změněna a není staged, pak je modified. V kapitole 2 se dozvíte více o těchto stavech a jak můžete využít jejich výhod, nebo -naopak úplně přeskočit staging area. +Nachází-li se konkrétní verze souboru v adresáři Git, je považována za zapsanou. Pokud je modifikovaná verze přidána do oblasti připravených změn, je považována za připravenou k zapsání. A pokud byla od poslední operace checkout změněna, ale nebyla připravena k zapsání, je považována za změněnou. O těchto stavech, způsobech jak je co nejlépe využívat nebo i o tom, jak přeskočit proces připravení souborů, se dozvíte v kapitole 2. -## Instalujeme Git ## +## Instalace systému Git ## -Ponořme se nyní do používání Gitu. Ale od začátku -- nejprve ho musíte nainstalovat; dá se získat mnoha způsoby -- dva hlavní jsou -instalace ze zdrojových souborů a instalace už existujícího balíčku pro váš systém. +Je načase začít systém Git aktivně používat. Instalaci můžete provést celou řadou způsobů. Většinou se využívá buď instalace ze zdrojových souborů, nebo instalace z existujícího balíčku, určeného pro vaši platformu. -### Instalujeme ze zdroje ### +### Instalace ze zdrojových souborů ### -Pokud to umíte, je obecně možné instalovat Git ze zdrojových kódů, protože získáte nejnovější verzi. -Vývojáři se stále snaží vylepšovat uživatelské rozhraní, takže stažení poslední verze je obvykle nejlepší cesta k cíli, -pokud se tedy cítíte na překládání zdrojových souborů. To je také řešení případu, kdy je ve mnoha dostribucích Linuxu dostupný -jen nějaký starý balík; takže pokud zrovna nemáte nějakou aktuální distribuci nebo nepoužíváte "backports", bude instalace -ze zdroje asi nejlepší možností. +Pokud je to možné, je nejvhodnější instalovat Git ze zdrojových souborů. Tak je zaručeno, že vždy získáte aktuální verzi. Každá další verze systému se snaží přidat nová vylepšení uživatelského rozhraní. Použití poslední verze je tedy zpravidla tou nejlepší cestou, samozřejmě pokud vám nedělá problémy kompilace softwaru ze zdrojových souborů. Skutečností také je, že mnoho linuxových distribucí obsahuje velmi staré balíčky. Takže pokud nepoužíváte velmi čerstvou distribuci, nebo pokud záměrně používáte starší verzi, bývá instalace ze zdrojových souborů nejlepší volbou. -Git závisí na několika knihovnách, bez kterých ho nenainstalujete: curl, zlib, openssl, expat a libiconv. Např. pokud máte distribuci -užívající balíčkovací systém Yum (Fedora) nebo Apt (Debian a distribuce na něm založené), můžete použít jeden z těchto příkazů k instalaci -těchto závislostí. +Před instalací samotného Gitu musí váš systém obsahovat následující knihovny, na nichž je Git závislý: curl, zlib, openssl, expat, a libiconv. Pokud používáte systém s nástrojem yum (například u distribuce Fedora) nebo apt-get (například distribuce odvozené od Debianu), můžete k instalaci použít jeden z následujících příkazů: $ yum install curl-devel expat-devel gettext-devel \ openssl-devel zlib-devel $ apt-get install libcurl4-gnutls-dev libexpat1-dev gettext \ - libz-dev - -Když jste už všechno nainstalovali, můžete pokročit dále a stáhnout si poslední verzi z webových stránek Gitu: + libz-dev libssl-dev + +Po doinstalování všech potřebných závislostí můžete pokračovat stažením nejnovější verze z webových stránek systému Git: http://git-scm.com/download - -Rozbalíme, přeložíme a nainstalujeme: - $ tar -zxf git-1.6.0.5.tar.gz - $ cd git-1.6.0.5 +Poté spusťte kompilaci a instalaci: + + $ tar -zxf git-1.7.2.2.tar.gz + $ cd git-1.7.2.2 $ make prefix=/usr/local all $ sudo make prefix=/usr/local install -Když jsme hotovi, můžeme také získat Git prostřednictvím jeho samotného (možnost další aktualizace): +Po dokončení instalace můžete rovněž vyhledat aktualizace systému Git prostřednictvím systému samotného: $ git clone git://git.kernel.org/pub/scm/git/git.git - -### Instalujeme na Linuxu ### -Pokud chcete instalovat Git na Linuxu z binárního balíčku, měli byste použít váš balíčkovací program podle vaší distribuce, -který udělá vše za vás. Pokud máte Fedoru, můžete použít Yum: +### Instalace v Linuxu ### - $ yum install git-core +Chcete-li nainstalovat Git v Linuxu pomocí binárního instalátoru, většinou tak můžete učinit pomocí základního nástroje pro správu balíčků, který je součástí vaší distribuce. Ve Fedoře můžete použít nástroj yum: -Nebo pokud jste na distribuci založené na Debianu (např. Ubuntu), použijte Apt: + $ yum install git - $ apt-get install git-core +V distribuci založené na Debianu (jako je například Ubuntu) zkuste použít program apt-get: -### Instalujeme na Macu ### + $ apt-get install git -Existují dva jednoduché způsoby, jak nainstalovat Git na Mac. Nejjednodušší je použít grafický instalátor, který si můžete stáhnout ze stránek Google Code (viz obr. 1-7): +### Instalace v systému Mac ### - http://code.google.com/p/git-osx-installer +Existují dva jednoduché způsoby, jak nainstalovat Git v systému Mac. Tím nejjednodušším je použít grafický instalátor Git, který si můžete stáhnout ze stránky SourceForge (viz obrázek 1-7): -Insert 18333fig0107.png -Obrázek 1-7. Git OS X installer + http://sourceforge.net/projects/git-osx-installer/ -Druhá základní možnost je přes MacPorts (`http://www.macports.org`). Když už je máte, instalujete Git pomocí +Insert 18333fig0107.png +Obrázek 1-7. Instalátor Git pro OS X - $ sudo port install git-core +svn +doc +bash_completion +gitweb +Jiným obvyklým způsobem je instalace systému Git prostřednictvím systému MacPorts (`http://www.macports.org`). Máte-li systém MacPorts nainstalován, nainstalujte Git příkazem: -Nemusíte samozřejmě přidávat všechny extra balíčky, ale určitě si vyberete naapř. +svn, pokud musíte ještě -používat Git s repoozitáři Subversion (více v kapitole 8). + $ sudo port install git +svn +doc +bash_completion +gitweb -### Instalujeme na Windows ### +Není nutné přidávat všechny doplňky, ale pokud budete někdy používat Git s repozitáři systému Subversion, budete pravděpodobně chtít nainstalovat i doplněk +svn (viz kapitola 8). -Nainstalovat Git na Windows je velmi jednoduché. Stáhněte si exe instalátor ze stránek Google Code a spusťte ho: +### Instalace v systému Windows ### - http://code.google.com/p/msysgit +Instalace systému Git v OS Windows je velice nenáročná. Postup instalace projektu msysGit patří k těm nejjednodušším. Ze stránky GitHub stáhněte instalační soubor exe a spusťte ho: -Po dokončení instalace máte jak verzi pro příkazový řádek (včetně SSH klienta, který se bude hodit později), tak standardní grafické rozhraní. + http://msysgit.github.io -## Počáteční nastavení ## +Po dokončení instalace budete mít k dispozici jak verzi pro příkazový řádek (včetně SSH klienta, který se vám bude hodit později), tak standardní grafické uživatelské rozhraní. -Teď, když máte na svém systému Git, si v něm možná budete chtít nastavit pár věcí, přizpůsobit svým požadavkům. Budete to muset udělat pouze jednou -- uchovávají se při upgradech. Samozřejmě je kdykoli můžete změnit provedením obdobných příkazů jako teď. +Poznámka k používání pod Windows: Git byste měli používat z dodaného shellu msysGit (unixový styl). Umožní vám zadávat složité řádkové příkazy, které v této knize naleznete. Pokud z nějakého důvodu potřebujete používat původní windowsovský shell / konzoli příkazové řádky, budete muset používat místo apostrofů uvozovky (pro parametry s mezerami uvnitř), a parametry končící stříškou (^) budete muset uzavírat do uvozovek v případě, kdy se stříška nachází na konci řádku. Ve Windows se totiž používá jako pokračovací znak. -Git obsahuje nástroj zvaný git config, který umožňuje nastavovat konfigurační hodnoty, které ovládají, jak Git vypadá a jak se chová. Mohou být uloženy na třech různých místech: +## První nastavení systému Git ## -* soubor `/etc/gitconfig`: Obsahuje hodnoty pro všechny uživatele a všechny repozitáře na tomto systému dohromady. Pokud připojíte volbu ` --system` za `git config`, bude pracovat výhradně s tímto souborem. -* soubot `~/.gitconfig`: Specifický pro uživatele. Tento soubor můžete upravovat také přidáním volby `--global`. -* konfigurační soubor v Git directory (tj. `.git/config`) každého repozitáře: specifický pro každý jednotlivý repozitář. +Nyní, když máte Git nainstalovaný, můžete provést některá uživatelská nastavení systému. Nastavení stačí provést pouze jednou — zůstanou zachována i po případných aktualizacích. -Každá další vrstva překrývá tu předchozí, takže hodnoty v `.git/config` přebijí hodnoty z `/etc/gitconfig`. +Nastavení konfiguračních proměnných systému, které ovlivňují jak vzhled systému Git, tak ostatní aspekty jeho práce, umožňuje příkaz `git config`. Tyto proměnné mohou být uloženy na třech různých místech: -Na Windows hledá Git soubor `.gitconfig` v `$HOME` (obvykle `C:\Documents and Settings\$USER`). Samozřejmě pořád uvažuje /etc/gitconfig, přestože tato cesta je relativní ke kořenu MSys, což je místo, kam jste se rozhodli instalovat Git ve vašem systému Windows. +* Soubor `/etc/gitconfig` obsahuje údaje pro všechny uživatele systému a pro všechny jejich repozitáře. Pokud příkazu `git config` zadáme parametr `--system` bude číst a zapisovat jen do tohoto souboru. +* Soubor `~/.gitconfig` je vázán na uživatelský účet. Čtení a zápis do tohoto souboru zajistíte zadáním parametru `--global`. +* Konfigurační soubor v adresáři Git (tedy `.git/config`) jakéhokoliv užívaného repozitáře přísluší tomuto konkrétnímu repozitáři. Každá úroveň je nadřazená hodnotám úrovně předchozí, takže hodnoty v `.git/config` převládnou nad hodnotami v `/etc/gitconfig`. -### Vaše identita ### +Ve Windows Git hledá soubor `.gitconfig` v adresáři `$HOME` (v proměnných prostředí Windows je to `%USERPROFILE%`), což je u většiny uživatelů `C:\Documents and Settings\$USER` nebo `C:\Users\$USER` (`$USER` se ve Windows zapisuje odkazem na proměnnou prostředí `%USERNAME%`). I ve Windows se hledá soubor `/etc/gitconfig`, který je ale umístěn relativně v kořeni MSys, tedy vůči místu, do kterého jste se po spuštění instalačního programu rozhodli Git nainstalovat. -První věc, kterou máte udělat po instalaci Gitu, je nastavení vašeho uživatelského jména a e-mailu. To je důležité, jelikož každý commit tyto informace obsahuje, a jsou nevratně "zataveny" do všech vašich commitů. +### Vaše totožnost ### + +První věcí, kterou byste měli po nainstalování systému Git udělat, je nastavení vašeho uživatelského jména (user name) a e-mailové adresy. Je to důležité, protože tuto informaci Git používá pro každý zápis revize a uvedené údaje stanou trvalou složkou záznamů o revizi, které budou putovat po okolí: $ git config --global user.name "John Doe" $ git config --global user.email johndoe@example.com -Znovu -- toto musíte udělat jen jednou, pokud připojíte volbu ` --global`, protože pak tyto informace použije Git pro cokoli, co na vašem systému děláte. Pokud je chcete přepsat jiným jménem nebo e-mailem pro nějaký projekt, stačí spustit příslušný příkaz bez volby ` --global` v adresáři onoho projektu. +Použijete-li parametr `--global`, pak také toto nastavení stačí provést pouze jednou. Git bude používat tyto údaje pro všechny operace, které v systému uděláte. Pokud chcete pro konkrétní projekt uživatelské jméno nebo e-mailovou adresu změnit (přebít), můžete příkaz spustit bez parametru `--global`. V takovém případě je nutné, abyste se nacházeli v adresáři daného projektu. ### Váš editor ### -Teď, když máte nastaveno, kdo jste, si můžete nastavit výchozí textový editor, který Git použije, když bude chtít, abyste napsali zprávu. Jinak Git použije výchozí editor podle nastavení systému, což je obvykle Vi nebo Vim. Pokud chcete použít jiný textový editor, třeba Emacs, nastavte si to: +Nyní, když jste zadali své osobní údaje, můžete nastavit výchozí textový editor, který se použije, když po vás Git bude chtít napsat nějakou zprávu. Pokud toto nastavení nezměníte, bude Git používat výchozí editor vašeho systému, jímž je většinou Vi nebo Vim. Chcete-li používat jiný textový editor, například Emacs, můžete použít následující příkaz: $ git config --global core.editor emacs - -### Váš nástroj pro řešení kolizních situací ### -Další užitečnou volbou je nastavení výchozího nástroje pro řešení kolizí. Takto nastavíte, že chcete používat vimdiff: +### Váš nástroj diff ### + +Další užitečnou volbou, jejíž nastavení můžete chtít upravit, je výchozí nástroj pro zjišťování rozdílů (diff), který Git používá k řešení konfliktů při slučování (merge). Řekněme, že jste se rozhodli používat vimdiff: $ git config --global merge.tool vimdiff -Git umí pracovat s nástroji kdiff3, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge, and opendiff. Můžete také nastavit i jiný nástroj; více v kapitole 7. +Jako platné nástroje slučování Git akceptuje: kdiff3, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge a opendiff. Nastavit můžete ale i jiné uživatelské nástroje — více informací o této možnosti naleznete v kapitole 7. -### Kontrola vašeho nastavení ### +### Kontrola vašeho nastavení ### -Pokud chcete zkontrolovat vaše nastavení, použijte `git config --list` k zobrazení všech nastavení, která dokáže na tomto místě Git najít: +Chcete-li zkontrolovat vaše nastavení, použijte příkaz `git config --list`. Git vypíše všechna aktuálně dostupná nastavení: $ git config --list user.name=Scott Chacon @@ -326,28 +232,28 @@ Pokud chcete zkontrolovat vaše nastavení, použijte `git config --list` k zobr color.diff=auto ... -Některé hodnoty můžete vidět vícekrát, protože je Git přečte z více různých souborů (např. `/etc/gitconfig` a `~/.gitconfig`). V takovém případě se Git řídí poslední načtenou hodnotou. +Některé klíče se mohou objevit vícekrát, protože Git načítá stejný klíč z různých souborů (například `/etc/gitconfig` a `~/.gitconfig`). V takovém případě použije Git poslední hodnotu pro každý unikátní klíč, který vidí. -Také můžete zobrazit jednu konkrétní hodnotu napsáním `git config {key}`: +Můžete také zkontrolovat, jakou hodnotu Git uchovává pro konkrétní klíč zadáním `git config {klíč}`: $ git config user.name Scott Chacon -## První pomoc ## +## Získání nápovědy ## -Pokud náhodou potřebujete pomoct s používáním Gitu, jsou tři možnosti, jak získat manuál (manpage) pro každý jeden příkaz Gitu: +Budete-li někdy při používání systému Git potřebovat pomoc, existují tři způsoby, jak vyvolat nápovědu z manuálové stránky (manpage) pro jakýkoli z příkazů systému Git: - $ git help - $ git --help - $ man git- + $ git help + $ git --help + $ man git- -Například manpage pro příkaz config získáte spuštěním +Například manpage nápovědu pro příkaz `config` vyvoláte zadáním: $ git help config -Tyto příkazy jsou užitečné zejména proto, že je můžete spustit kdykoli -- i offline. -Pokud by ani manuálové stránky, ani tato kniha neposkytly to, co potřebujete, zkuste IRC kanály `#git` nebo `#github` na Freenode IRC serveru (irc.freenode.net). Tyto kanály jsou pravidelně zaplněny stovkami lidí, kteří o Gitu ví opravdu mnoho a často vám rádi pomohou. +Tyto příkazy jsou užitečné, neboť je můžete spustit kdykoli, dokonce i offline. +Pokud nestačí ani manuálová stránka ani tato kniha a uvítali byste osobní pomoc, můžete zkusit kanál `#git` nebo `#github` na serveru Freenode IRC (irc.freenode.net). Na těchto kanálech se většinou pohybují stovky lidí, kteří mají se systémem Git bohaté zkušenosti a často ochotně pomohou. (Nutno ovšem podotknout, že se na těchto kanálech mluví anglicky – pozn. překl.) ## Shrnutí ## -Měli byste v základu vědět, co to je Git a v jakém směru je odlišný od CSSV, který možná zrovna používáte. Měli byste mít na svém systému funkční Git nastavený podle vás. Nyní je čas na naučení se základů Gitu. +Nyní byste měli mít základní představu o tom, co je to Git a v čem se liší od systému CVCS, který jste možná dosud používali. Také byste nyní měli mít nainstalovanou fungující verzi systému Git, nastavenou na vaše osobní údaje. Nejvyšší čas podívat se na základy práce se systémem Git. diff --git a/cs/02-git-basics/01-chapter2.markdown b/cs/02-git-basics/01-chapter2.markdown index 787c81944..c301bbb54 100644 --- a/cs/02-git-basics/01-chapter2.markdown +++ b/cs/02-git-basics/01-chapter2.markdown @@ -1,261 +1,214 @@ -# Základy Gitu # +# Základy práce se systémem Git # -Pokud máte čas si přečíst jen jednu kapitolu, přečtěte si tuto. Pokrývá všechny základní příkazy, -které potřebujete k naprosté většině činností, které kdy budete s Gitem dělat. Naučíte se konfigurovat a inicializovat repozitář, -přidávat a odebírat sledované soubory a ukládat změny. Také donutíme Git ignorovat některé soubory; zjistíme, jak rychle a jednoduše opravovat chyby, -prohlížet historii a změny mezi jednotlivými commity a synchronizovat se vzdálenými repozitáři. +Pokud jste ochotni přečíst si o systému Git jen jednu kapitolu, měla by to být právě tahle. Tato kapitola popíše všechny základní příkazy, jejichž prováděním strávíte při práci se systémem Git drtivou většinu času. Po přečtení kapitoly byste měli být schopni nakonfigurovat a inicializovat repozitář, spustit a ukončit sledování souborů, připravovat soubory a zapisovat revize. Ukážeme si také, jak nastavit Git, aby ignoroval určité soubory a masky souborů, jak rychle a jednoduše vrátit nežádoucí změny, jak procházet historii projektu a zobrazit změny mezi jednotlivými revizemi a jak posílat soubory do vzdálených repozitářů a naopak z nich soubory zase stahovat. -## Jak získat repozitář Gitu ## +## Získání repozitáře Git ## -Jsou dva základní způsoby, jak získat projekt v Gitu. První vezme existující projekt nebo adresář a importuje ho do Gitu. -Druhý naklonuje existující repozitář z jiného serveru. +Projekt v systému Git lze získat dvěma základními způsoby. První způsob spočívá v tom, že vezmeme existující projekt nebo adresář a importujeme ho do systému Git. Druhý způsob spočívá v naklonování již existujícího repozitáře Git z jiného serveru. -### Inicializace repozitáře z existujícího adresáře ### +### Inicializace repozitáře v existujícím adresáři ### -Pokud chcete začít spravovat projekt Gitem, vstoupíte do jeho adresáře a spustíte +Chcete-li zahájit sledování existujícího projektu v systému Git, přejděte do adresáře projektu a zadejte příkaz: $ git init -To vytvoří podadresář .git, který obsahuje všechno, co Git potřebuje pro tento projekt, jakousi kostru. Ovšem zatím je prázdný, nic nesleduje. -(V kapitole 9 si podrobněji rozebereme, co tento příkaz vlastně vytvořil.) +Příkaz vytvoří nový podadresář s názvem `.git`, který bude obsahovat všechny soubory nezbytné pro repozitář, tzv. kostru repozitáře Git. V tomto okamžiku se z vašeho projektu ještě nic nesleduje. (Více informací o tom, jaké soubory obsahuje právě vytvořený adresář `.git`, naleznete v *kapitole 9*.) -Pokud chcete spravovat již existující soubory (pokud zrovna nezačínáte od píky a nemáte úplně prázdný adresář), asi je budete chtít začít sledovat -a provést první commit. To zařídíte spuštěním několika příkazů, kterými určíte, co sledovat, načež to shrnete do commitu: +Chcete-li spustit verzování existujících souborů (a ne jen prázdného adresáře), měli byste pravděpodobně zahájit sledování (tracking) těchto souborů a provést první revizi (commit). Můžete tak učinit pomocí několika příkazů `git add`, jimiž určíte soubory, které chcete sledovat, a provedete revizi: $ git add *.c $ git add README - $ git commit –m 'initial project version' + $ git commit -m 'initial project version' -Pozn. překl.: Bývá zvykem, že popisky commitů (initial project version aj.) jsou psány v angličtině, není-li explicitně řečeno jinak; -české popisky mívají opodstatnění jen u ryze českých, resp. československých projektů, kde se nepočítá s tím, že by se na nich podílel -někdo, pro koho je čeština nesrozumitelným jazykem. +K tomu, co přesně tyto příkazy provedou, se dostaneme za okamžik. V této chvíli máte vytvořen repozitář Git se sledovanými soubory a úvodní revizí. -Za chvilku si projdeme, co tyto příkazy vlastně dělají. V tuto chvíli máte repozitář se sledovanými soubory a prvním commitem. +### Klonování existujícího repozitáře ### -### Klonování stávajícího repozitáře ### +Chcete-li vytvořit kopii existujícího repozitáře Git (například u projektu, do nějž chcete začít přispívat), pak příkazem, který hledáte, je `git clone`. Pokud jste zvyklí pracovat s jinými systémy pro správu verzí, jako je například Subversion, jistě jste si všimli, že příkaz zní `clone`, a nikoli `checkout`. Souvisí to s jedním podstatným rozdílem: Git získá kopii téměř všech dat na serveru. Po spuštění příkazu `git clone` budou k historii projektu staženy všechny verze všech souborů. Pokud by někdy poté došlo k poruše disku serveru, lze použít libovolný z těchto klonů na kterémkoli klientovi a obnovit pomocí něj server zpět do stavu, v němž byl v okamžiku klonování (může dojít ke ztrátě některých zásuvných modulů na straně serveru a podobných věcí, ale všechna verzovaná data budou obnovena. Další podrobnosti naleznete v *kapitole 4*). -Pokud chcete mít kopii již existujícího repozitáře -- např. projektu, na kterém se chcete podílet -- příkaz, který potřebujete, je `git clone`. -Když máte zkušenosti s jinými SSV jako Subversion, povšimnete si, že použitý příkaz je `clone` a nikoli `checkout`. To je důležitý rozdíl. -Git totiž dostane téměř kompletní kopii toho, co server zrovna má. Každou verzi každého souboru z minulosti. -Tedy, pokud se vám na serveru porouchá disk, stačí zpět naklonovat repozitář jakéhokoli klienta a máte přesně takový stav, jaký byl na serveru -v době, kdy ho on naposledy aktualizoval. Možná ztratíte nějaká specifická serverová nastavení, ale každopádně to cenné -- spravovaná data -- máte -v bezpečí. - -Repozitář naklonujete příkazem `git clone [url]`. Např. pro naklonování knihovny Gitu pro Ruby (Grit) provedete tento příkaz: +Repozitář naklonujete příkazem `git clone [url]`. Pokud například chcete naklonovat knihovnu Ruby Git nazvanou Grit, můžete to provést následovně: $ git clone git://github.com/schacon/grit.git -Ten vytvoří adresář "grit", v něm adresář `.git`, stáhne všechna data repozitáře a rozbalí aktuální verzi. Pokud vstoupíte do tohoto nového -adresáře, najdete v něm všechny soubory projektu připravené k práci nebo použití. -Když chcete naklonovat repozitář někam jinam než do složky "grit", můžete mu to říct takto: +Tímto příkazem se vytvoří adresář s názvem `grit`, inicializuje se v něm adresář `.git`, stáhnou se všechna data pro tento repozitář a vytvoří se pracovní kopie nejnovější verze. Přejdete-li do nového adresáře `grit`, uvidíte v něm soubory projektu připravené ke zpracování nebo jinému použití. Pokud chcete naklonovat repozitář do adresáře pojmenovaného jinak než grit, můžete název zadat jako další parametr na příkazovém řádku: $ git clone git://github.com/schacon/grit.git mygrit -Tak provedete všechno, co udělal minulý příkaz, ale do adresáře `mygrit`. +Tento příkaz učiní totéž co příkaz předchozí, ale cílový adresář se bude jmenovat `mygrit`. -Git podporuje více různých přenosových protokolů. Předchozí příklad používá protokol `git://`, ale také můžete použít `http(s)://` -nebo `uživatel@server:/cesta.git`, což použije SSH. Všechny možnosti včetně jejich pro a proti si ukážeme v kapitole 4. +Git nabízí celou řadu různých přenosových protokolů. Předchozí příklad využívá protokol `git://`, můžete se ale setkat také s protokolem `http(s)://` nebo `user@server:/path.git`, který používá přenosový protokol SSH. V *kapitole 4* budou představeny všechny dostupné možnosti, které mohou být pro přístup do repozitáře Git na serveru nastaveny, včetně jejich předností a nevýhod. -## Zaznamenávání změn do repozitáře ## +## Nahrávání změn do repozitáře ## -Nyní máte připravený repozitář Gitu a checkout neboli pracovní kopii souborů projektu. -Potřebujete udělat nějaké změny a ukládat commity těchto změn do repozitáře pokaždé, když -projekt dospěje do stavu, který chcete zaznamenat. +Nyní máte vytvořen opravdový gitový repozitář a pracovní kopii souborů k projektu (checkout). Řekněme, že potřebujete udělat pár změn a zapsat snímky těchto změn do svého repozitáře pokaždé, kdy se projekt dostane do stavu, který chcete zaznamenat. -Pamatujte, že každý soubor ve vašem pracovním adresáři může být v jednom ze dvou stavů: -tracked nebo untracked. První z nich jsou ty, které byly v posledním snímku. Mohou být -nezměněny, změněny, nebo staged. Untracked je všechno ostatní. V posledním snímku nebyly, -nejsou ve staging area a Git se o ně nestará. Když poprvé naklonujete repozitář, všechny -vaše souboru budou tracked a unmodified, protože jste je právě zkopírovali z repozitáře -a nic ještě neupravili. +Nezapomeňte, že každý soubor ve vašem pracovním adresáři může být ve dvou různých stavech: *sledován* (tracked) a *nesledován* (untracked). Za *sledované* jsou označovány soubory, které byly součástí posledního snímku. Mohou být ve stavu *změněn* (modified), *nezměněn* (unmodified) nebo *připraven k zapsání* (staged). *Nesledované* soubory jsou všechny ostatní, tedy veškeré soubory ve vašem pracovním adresáři, které nebyly obsaženy ve vašem posledním snímku a nejsou v oblasti připravených změn. Po úvodním klonování repozitáře budou všechny vaše soubory sledované a nezměněné, protože jste právě provedli jejich checkout a dosud jste neudělali žádné změny. -Když upravujete soubory, Git je prohlásí za změněné, protože se změnily vzhledem k poslednímu -commitu. Vy je vložíte do staging area, vyrobíte commit ze všech těchto změn a cyklus se opakuje -jako na obrázku 2-1. +Jakmile začnete soubory upravovat, Git je bude považovat za změněné, protože jste v nich od poslední revize provedli změny. Poté všechny tyto změněné soubory *připravíte k zapsání* (stage) a následně všechny připravené změny zapíšete (commit). A celý cyklus se opakuje. Pracovní cyklus je znázorněn na obrázku 2-1. -Insert 18333fig0201.png +Insert 18333fig0201.png Obrázek 2-1. Cyklus stavů vašich souborů -### Kontrola stavu vašich souborů ### +### Kontrola stavu souborů ### -Základní nástroj, který se používá na určování, který soubor je v jakém stavu, je -příkaz `git status`. Pokud ho pustíte hned po `git clone`, měli byste vidět něco jako: +Hlavním nástrojem na zjišťování stavu jednotlivých souborů je příkaz `git status`. Spustíte-li tento příkaz bezprostředně po klonování, objeví se zhruba následující: $ git status - # On branch master - nothing to commit (working directory clean) + On branch master + nothing to commit, working directory clean -To znamená, že máte čistý pracovní adresář -- jinými slovy, nejsou v něm žádné soubory -změněné (modified) a žádné nejsou v indexu (staged). -Git také nevidí žádný přebývající (untracked) soubor, jinak by ho vypsal. A konečně vám -příkaz sdělí, v jaké jste větvi. Protentokrát to bude vždy master, ten je výchozí; teď -a tady se o to starat nemusíte. Větvení a reference probereme detailně v další kapitole. +To znamená, že žádné soubory nejsou připraveny k zapsání a pracovní adresář je čistý. Jinými slovy, žádné sledované soubory nebyly změněny. Git také neví o žádných nesledovaných souborech, jinak by byly ve výčtu uvedeny. Příkaz vám dále sděluje, na jaké větvi (branch) se nacházíte. Pro tuto chvíli nebudeme situaci komplikovat a výchozí bude vždy hlavní větev (`master` branch). Větve a reference budou podrobně popsány v následující kapitole. -Řekněme, že přidáte nový soubor do vašeho projektu, třeba jednoduché README. Pokud ten soubor -dosud neexistoval a vy pustíte `git status`, uvidíte soubor ve stavu untracked: +Řekněme, že nyní přidáte do projektu nový soubor, například soubor `README`. Pokud soubor dříve neexistoval a vy spustíte příkaz `git status`, bude nesledovaný soubor uveden takto: $ vim README $ git status - # On branch master - # Untracked files: - # (use "git add ..." to include in what will be committed) - # - # README + On branch master + Untracked files: + (use "git add ..." to include in what will be committed) + + README + nothing added to commit but untracked files present (use "git add" to track) -Je vidět, že vaše README je untracked, protože je pod nadpisem "Untracked files" -ve výpisu stavu. To jednoduše znamená, že tento soubor Git dosud nespravoval, a také ho -spravovat nebude, dokud mu to explicitně neřeknete. Dělá to proto, aby nezačal náhodou -zběsile spravovat vygenerované binární soubory nebo jiné, třeba dočasné soubory, které -určitě do projektu zahrnout nechcete. Toto README však chcete spravovat, nuže pojďme si -ukázat, jak na to. +Vidíte, že nový soubor `README` není sledován, protože je ve výpisu stavů uveden v části „Untracked files“. Není-li soubor sledován, obecně to znamená, že Git ví o souboru, který nebyl v předchozím snímku (v předchozí revizi), a nezařadí ho ani do dalších snímků, dokud mu k tomu nedáte výslovný příkaz. Díky tomu se nemůže stát, že budou do revizí nedopatřením zahrnuty vygenerované binární soubory nebo jiné soubory, které si nepřejete zahrnout. Vy si ale přejete soubor README zahrnout, a proto ho začněme sledovat. -### Spravování nových souborů ### +### Sledování nových souborů ### -K započetí spravování nových souborů použijeme příkaz `git add`. Konkrétně v tomto případě, -abychom přidali soubor README, spustíme toto: +K zahájení sledování nových souborů se používá příkaz `git add`. Chcete-li zahájit sledování souboru `README`, můžete zadat příkaz: $ git add README -Pokud si nyní znovu zkontrolujeme stav příkazem `git status`, můžeme vidět, -že naše README je nyní tracked a staged: +Když nyní znovu provedete příkaz k výpisu stavů (git status), uvidíte, že je nyní soubor `README` sledován a připraven k zapsání: $ git status - # On branch master - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # new file: README - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) + + new file: README -Staged je proto, že je pod nadpisem "Changes to be committed". Pokud uděláte commit v tuto -chvíli, bude verze souboru ve chvíli, kdy jste udělali `git add`, vložena do snímku a uložena. -Můžete si také vzpomenout, že když jste dříve pouštěli `git init`, museli jste pak pustit -i `git add` -- to byl počátek správy souborů ve vašem adresáři. Příkaz `git add` přebírá cestu -buďto k souboru nebo k adresáři; pokud je to adresář, uloží příkaz všechny soubory v onom adresáři. -Rekurzivně. -### Vkládání upravených souborů do indexu ### +Můžeme říci, že je připraven k zapsání, protože je uveden v části „Changes to be committed“, tedy „Změny k zapsání“. Pokud v tomto okamžiku zapíšete revizi, v historickém snímku bude verze souboru z okamžiku, kdy jste spustili příkaz `git add`. Možná si vzpomínáte, že když jste před časem spustili příkaz `git init`, provedli jste potom příkaz `git add (soubory)`. Příkaz jste zadávali kvůli zahájení sledování souborů ve vašem adresáři. Příkaz `git add` je doplněn uvedením cesty buď k souboru, nebo k adresáři. Pokud se jedná o adresář, příkaz přidá rekurzivně všechny soubory v tomto adresáři. -Nyní změníme soubor, který už spravujeme. Když změníte spravovaný soubor, pro příklad nechť -se jmenuje `benchmarks.rb`, a pak pustíte `git status` znovu, dostanete něco, co bude vypadat -zhruba takto: +### Příprava změněných souborů k zapsání ### + +Nyní provedeme změny v souboru, který už byl sledován. Pokud změníte už dříve sledovaný soubor s názvem `benchmarks.rb` a poté znovu spustíte příkaz `status`, zobrazí se něco takového: $ git status - # On branch master - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # new file: README - # - # Changed but not updated: - # (use "git add ..." to update what will be committed) - # - # modified: benchmarks.rb - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) + + new file: README + + Changes not staged for commit: + (use "git add ..." to update what will be committed) + (use "git checkout -- ..." to discard changes in working directory) + + modified: benchmarks.rb -Soubor `benchmarks.rb` se objevil v sekci nazvané "Changed but not updated" -- to znamená, že -soubor, který je spravován, byl upraven v pracovním adresáři, ale ještě nebyl vložen do indexu. -K vložení do indexu použijeme příkaz `git add` (má mnoho funkcí -- je používán k započetí správy -nových souborů, ke vkládání do indexu a i k jiným operacím, např. k označování souborů postižených -merge-conflictem jako vyřešených). Vložme tedy `benchmarks.rb` do indexu a pak si znovu zobrazme -status: + +Soubor `benchmarks.rb` je uveden v části „Changes not staged for commit“ (změny, které nejsou připraveny k zapsání). Znamená to, že soubor, který je sledován, byl v pracovním adresáři změněn, avšak ještě nebyl připraven k zapsání (staged). Chcete-li ho připravit k zapsání, spusťte příkaz `git add` (jedná se o víceúčelový příkaz – používá se k zahájení sledování nových souborů i k dalším operacím, jako je například označení vyřešených případů kolize souborů při slučování). Spusťme nyní příkaz `git add`, abychom soubor `benchmarks.rb` připravili k zapsání, a potom znovu zadejme příkaz `git status`: $ git add benchmarks.rb $ git status - # On branch master - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # new file: README - # modified: benchmarks.rb - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) + + new file: README + modified: benchmarks.rb -Oba soubory jsou v indexu a půjdou do nejbližšího commitu. V tuto chvíli jste si ale uvědomili, -že v souboru `benchmarks.rb` je potřeba udělat ještě jednu malou změnu, než ho uložíte do commitu. -Otevřete ho tedy znovu, uložíte a jste připraveni vytvořit commit. Tak se ještě jednou podíváme -na status: - $ vim benchmarks.rb +Oba soubory jsou nyní připraveny k zapsání a budou zahrnuty do příští revize. Nyní předpokládejme, že jste si vzpomněli na jednu malou změnu, kterou chcete ještě před zapsáním revize provést v souboru `benchmarks.rb`. Soubor znovu otevřete, provedete změnu a chcete jej zapsat. Spusťme však ještě jednou příkaz `git status`: + + $ vim benchmarks.rb $ git status - # On branch master - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # new file: README - # modified: benchmarks.rb - # - # Changed but not updated: - # (use "git add ..." to update what will be committed) - # - # modified: benchmarks.rb - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) + + new file: README + modified: benchmarks.rb + + Changes not staged for commit: + (use "git add ..." to update what will be committed) + (use "git checkout -- ..." to discard changes in working directory) + + modified: benchmarks.rb -Co to má znamenat? Teď je soubor `benchmarks.rb` označen jako staged i jako unstaged. -Jak je to možné? Git vloží soubor do indexu právě takový, jaký byl, když jste na něj -naposled použil `git add`. Pokud vytvoříte commit teď, bude do něj uložena ta verze, -která je v indexu, tedy ta, která byla v adresáři ve chvíli, kdy byl naposled použit -příkaz `git add`. Takže pokud chcete uložit i následující změny, musíte pustit `git add` -znovu: + +Co to má být? Soubor `benchmarks.rb` je nyní uveden jak v části připraveno k zapsání (Changes to be committed), tak v části nepřipraveno k zapsání (Changes not staged for commit). Jak je tohle možné? Věc se má tak, že Git po spuštění příkazu `git add` připraví soubor k zapsání přesně ve tvaru, v jakém se nachází v daném okamžiku. Pokud nyní revizi zapíšete, bude obsahovat soubor `benchmarks.rb` tak, jak vypadal, když jste naposledy spustili příkaz `git add`, nikoli v té podobě, kterou měl v pracovním adresáři v okamžiku, když jste spustili příkaz `git commit`. Pokud upravíte soubor po provedení příkazu `git add`, je třeba spustit `git add` ještě jednou, aby byla připravena aktuální verze souboru: $ git add benchmarks.rb $ git status - # On branch master - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # new file: README - # modified: benchmarks.rb - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) -### Ignoring Files ### + new file: README + modified: benchmarks.rb -Often, you’ll have a class of files that you don’t want Git to automatically add or even show you as being untracked. These are generally automatically generated files such as log files or files produced by your build system. In such cases, you can create a file listing patterns to match them named .gitignore. Here is an example .gitignore file: + +### Ignorované soubory ### + +Ve vašem adresáři se často vyskytne skupina souborů, u nichž nebudete chtít, aby je Git automaticky přidával nebo aby je vůbec uváděl jako nesledované. Jedná se většinou o automaticky vygenerované soubory, jako soubory log nebo soubory vytvořené při překladu. V takových případech můžete vytvořit soubor `.gitignore` se seznamem masek pro ignorované soubory. Tady je malý příklad souboru `.gitignore`: $ cat .gitignore *.[oa] *~ -The first line tells Git to ignore any files ending in .o or .a — object and archive files that may be the product of building your code. The second line tells Git to ignore all files that end with a tilde (`~`), which is used by many text editors such as Emacs to mark temporary files. You may also include a log, tmp, or pid directory; automatically generated documentation; and so on. Setting up a .gitignore file before you get going is generally a good idea so you don’t accidentally commit files that you really don’t want in your Git repository. +První řádek říká systému Git, že má ignorovat všechny soubory končící na `.o` nebo `.a` – *objekty* a *archivní* soubory, které mohou být výsledkem překladu. Druhý řádek systému Git říká, aby ignoroval všechny soubory končící vlnovkou (`~`), kterou mnoho textových editorů (např. Emacs) používá k označení dočasných souborů. Můžete rovněž přidat adresář `log`, `tmp` nebo `pid`, automaticky vygenerovanou dokumentaci a podobné. Vytvoření a naplnění souboru `.gitignore` ještě dříve než se pustíte do práce bývá většinou dobrý nápad. Alespoň se vám nestane, že byste nedopatřením zapsali také soubory, o které v repozitáři Git nestojíte. + +Pravidla pro masky, které můžete použít v souboru `.gitignore`, jsou následující: -The rules for the patterns you can put in the .gitignore file are as follows: +* Prázdné řádky nebo řádky začínající znakem `#` budou ignorovány. +* Standardní masky souborů (glob patterns). +* Chcete-li označit adresář, můžete masku zakončit lomítkem (`/`). +* Pokud řádek začíná vykřičníkem (`!`), maska na něm je negována. -* Blank lines or lines starting with # are ignored. -* Standard glob patterns work. -* You can end patterns with a forward slash (`/`) to specify a directory. -* You can negate a pattern by starting it with an exclamation point (`!`). +Masky souborů jsou jako zjednodušené regulární výrazy, které používá shell. Hvězdička (`*`) označuje žádný nebo více znaků; `[abc]` označuje jakýkoli znak uvedený v závorkách (v tomto případě `a`, `b` nebo `c`); otazník (`?`) označuje jeden znak; znaky v závorkách oddělené pomlčkou (`[0-9]`) označují jakýkoli znak v daném rozmezí (v našem případě 0 až 9). -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) . +Tady je další příklad souboru `.gitignore`: -Here is another example .gitignore file: + # komentář – ignoruje se + # žádné soubory s příponou .a + *.a + # ale sleduj soubor lib.a, přestože máš ignorovat soubory s příponou .a + !lib.a + # ignoruj soubor TODO pouze v kořenovém adresáři, ne v podadresářích + /TODO + # ignoruj všechny soubory v adresáři build/ + build/ + # ignoruj doc/notes.txt, ale nikoli doc/server/arch.txt + doc/*.txt + # ignoruj všechny .txt soubory v adresáři doc/ + doc/**/*.txt - # a comment – this is ignored - *.a # no .a files - !lib.a # but do track lib.a, even though you're ignoring .a files above - /TODO # only ignore the root TODO file, not subdir/TODO - build/ # ignore all files in the build/ directory - doc/*.txt # ignore doc/notes.txt, but not doc/server/arch.txt +Část masky `**/` je v Gitu dostupná od verze 1.8.2. -### Viewing Your Staged and Unstaged Changes ### +### Zobrazení připravených a nepřipravených změn ### -If the `git status` command is too vague for you — you want to know exactly what you changed, not just which files were changed — you can use the `git diff` command. We’ll cover `git diff` in more detail later; but you’ll probably use it most often to answer these two questions: What have you changed but not yet staged? And what have you staged that you are about to commit? Although `git status` answers those questions very generally, `git diff` shows you the exact lines added and removed — the patch, as it were. +Je-li pro vaše potřeby příkaz `git status` příliš neurčitý – chcete přesně vědět, co jste změnili, nejen které soubory – můžete použít příkaz `git diff`. Podrobněji se budeme příkazu `git diff` věnovat později. Vy ho však nejspíš budete nejčastěji využívat k zodpovězení těchto dvou otázek: Co jste změnili, ale ještě nepřipravili k zapsání? A co jste připravili a nyní může být zapsáno? Zatímco příkaz `git status` vám tyto otázky zodpoví velmi obecně, příkaz `git diff` přesně zobrazí přidané a odstraněné řádky – tedy samotnou záplatu. -Let’s say you edit and stage the README file again and then edit the benchmarks.rb file without staging it. If you run your `status` command, you once again see something like this: +Řekněme, že znovu upravíte a připravíte soubor `README` a poté bez připravení upravíte soubor `benchmarks.rb`. Po spuštění příkazu `status` se zobrazí zhruba toto: $ git status - # On branch master - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # new file: README - # - # Changed but not updated: - # (use "git add ..." to update what will be committed) - # - # modified: benchmarks.rb - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) + + new file: README + + Changes not staged for commit: + (use "git add ..." to update what will be committed) + (use "git checkout -- ..." to discard changes in working directory) -To see what you’ve changed but not yet staged, type `git diff` with no other arguments: + modified: benchmarks.rb + + +Chcete-li vidět, co jste změnili, avšak ještě nepřipravili k zapsání, zadejte příkaz `git diff` bez dalších parametrů: $ git diff diff --git a/benchmarks.rb b/benchmarks.rb @@ -274,9 +227,9 @@ To see what you’ve changed but not yet staged, type `git diff` with no other a log = git.commits('master', 15) log.size -That command compares what is in your working directory with what is in your staging area. The result tells you the changes you’ve made that you haven’t yet staged. +Tento příkaz srovná obsah vašeho pracovního adresáře a oblasti připravených změn. Výsledek vám ukáže provedené změny, které jste dosud nepřipravili k zapsání. -If you want to see what you’ve staged that will go into your next commit, you can use `git diff –-cached`. (In Git versions 1.6.1 and later, you can also use `git diff –-staged`, which may be easier to remember.) This command compares your staged changes to your last commit: +Chcete-li vidět, co jste připravili a co bude součástí příští revize, použijte příkaz `git diff --cached`. (Ve verzích Git 1.6.1 a novějších můžete použít také příkaz `git diff --staged`, který se možná snáze pamatuje.) Tento příkaz srovná připravené změny (staged changes) s poslední revizí: $ git diff --cached diff --git a/README b/README @@ -291,27 +244,29 @@ If you want to see what you’ve staged that will go into your next commit, you + +Grit is a Ruby library for extracting information from a Git repository -It’s important to note that `git diff` by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. This can be confusing, because if you’ve staged all of your changes, `git diff` will give you no output. +K tomu je třeba poznamenat, že příkaz `git diff` sám o sobě nezobrazí všechny změny provedené od poslední revize, ale jen změny, které zatím nejsou připraveny. To může být občas matoucí, protože pokud jste připravili všechny provedené změny, bude výstup příkazu `git diff` prázdný. -For another example, if you stage the benchmarks.rb file and then edit it, you can use `git diff` to see the changes in the file that are staged and the changes that are unstaged: +V dalším příkladu ukážeme situaci, kdy jste připravili soubor `benchmarks.rb` a poté ho znovu upravili. Příkaz `git diff` můžete nyní použít k zobrazení změn v souboru, které byly připraveny, a změn, které nejsou připraveny: $ git add benchmarks.rb $ echo '# test line' >> benchmarks.rb $ git status - # On branch master - # - # Changes to be committed: - # - # modified: benchmarks.rb - # - # Changed but not updated: - # - # modified: benchmarks.rb - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) + + modified: benchmarks.rb -Now you can use `git diff` to see what is still unstaged + Changes not staged for commit: + (use "git add ..." to update what will be committed) + (use "git checkout -- ..." to discard changes in working directory) - $ git diff + modified: benchmarks.rb + + +Příkaz `git diff` nyní můžete použít k zobrazení změn, které dosud nejsou připraveny: + + $ git diff diff --git a/benchmarks.rb b/benchmarks.rb index e445e28..86b2f7c 100644 --- a/benchmarks.rb @@ -319,10 +274,10 @@ Now you can use `git diff` to see what is still unstaged @@ -127,3 +127,4 @@ end main() - ##pp Grit::GitRuby.cache_client.stats + ##pp Grit::GitRuby.cache_client.stats +# test line -and `git diff --cached` to see what you’ve staged so far: +A příkaz `git diff --cached` ukáže změny, které už připraveny jsou: $ git diff --cached diff --git a/benchmarks.rb b/benchmarks.rb @@ -336,148 +291,147 @@ and `git diff --cached` to see what you’ve staged so far: + run_code(x, 'commits 1') do + git.commits.size + end - + + + run_code(x, 'commits 2') do log = git.commits('master', 15) log.size -### Committing Your Changes ### +### Zapisování změn ### -Now that your staging area is set up the way you want it, you can commit your changes. Remember that anything that is still unstaged — any files you have created or modified that you haven’t run `git add` on since you edited them — won’t go into this commit. They will stay as modified files on your disk. -In this case, the last time you ran `git status`, you saw that everything was staged, so you’re ready to commit your changes. The simplest way to commit is to type `git commit`: +Nyní, když jste seznam připravených změn nastavili podle svých představ, můžete začít zapisovat změny. Nezapomeňte, že všechno, co dosud nebylo připraveno k zapsání – všechny soubory, které jste vytvořili nebo změnili a na které jste po úpravách nepoužili příkaz `git add` –, nebudou do revize zahrnuty. Zůstanou na vašem disku jako změněné soubory. +Když jste v našem případě naposledy spustili příkaz `git status`, viděli jste, že všechny soubory byly připraveny k zapsání. Takže jste připraveni k samotnému zapsání změn. Nejjednodušší způsob zapsání změn spočívá v použití příkazu `git commit`: $ git commit -Doing so launches your editor of choice. (This is set by your shell’s `$EDITOR` environment variable — usually vim or emacs, although you can configure it with whatever you want using the `git config --global core.editor` command as you saw in Chapter 1). +Po zadání příkazu se otevře vámi zvolený editor. (Ten je nastaven proměnnou prostředí `$EDITOR` vašeho shellu. Většinou se bude jednat o editor vim nebo emacs, ale pomocí příkazu `git config --global core.editor` můžete nastavit i jakýkoli jiný – viz *kapitola 1*.) -The editor displays the following text (this example is a Vim screen): +Editor zobrazí následující text (tento příklad je z editoru Vim): # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # On branch master # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # # new file: README - # modified: benchmarks.rb + # modified: benchmarks.rb + # ~ ~ ~ ".git/COMMIT_EDITMSG" 10L, 283C -You can see that the default commit message contains the latest output of the `git status` command commented out and one empty line on top. You can remove these comments and type your commit message, or you can leave them there to help you remember what you’re committing. (For an even more explicit reminder of what you’ve modified, you can pass the `-v` option to `git commit`. Doing so also puts the diff of your change in the editor so you can see exactly what you did.) When you exit the editor, Git creates your commit with that commit message (with the comments and diff stripped out). +Jak vidíte, výchozí zpráva k revizi (commit message) obsahuje zakomentovaný aktuální výstup příkazu `git status` a nahoře jeden prázdný řádek. Tyto komentáře můžete odstranit a napsat vlastní zprávu k revizi, nebo je můžete v souboru ponechat, abyste si lépe vzpomněli, co bylo obsahem dané revize. (Chcete-li zařadit ještě podrobnější informace o tom, co jste měnili, můžete k příkazu `git commit` přidat parametr `-v`. V editoru se pak zobrazí také výstup rozdílů (diff) ke konkrétním změnám a vy přesně uvidíte, co bylo změněno.) Jakmile editor zavřete, Git vytvoří revizi se zprávou, kterou jste napsali (s odstraněnými komentáři a rozdíly). -Alternatively, you can type your commit message inline with the `commit` command by specifying it after a -m flag, like this: +Zprávu k revizi můžete rovněž napsat do řádku k příkazu `commit`. Jako zprávu ji označíte tak, že před ni vložíte příznak `-m`: $ git commit -m "Story 182: Fix benchmarks for speed" - [master]: created 463dc4f: "Fix benchmarks for speed" - 2 files changed, 3 insertions(+), 0 deletions(-) + [master 463dc4f] Story 182: Fix benchmarks for speed + 2 files changed, 3 insertions(+) create mode 100644 README -Now you’ve created your first commit! You can see that the commit has given you some output about itself: which branch you committed to (master), what SHA-1 checksum the commit has (`463dc4f`), how many files were changed, and statistics about lines added and removed in the commit. +Nyní jste vytvořili svou první revizi! Vidíte, že se po zapsání revize zobrazil výpis s informacemi: do jaké větve jste revizi zapsali (`master`), jaký je kontrolní součet SHA-1 revize (`463dc4f`), kolik souborů bylo změněno a statistiku přidaných a odstraněných řádků revize. -Remember that the commit records the snapshot you set up in your staging area. Anything you didn’t stage is still sitting there modified; you can do another commit to add it to your history. Every time you perform a commit, you’re recording a snapshot of your project that you can revert to or compare to later. +Nezapomeňte, že revize zaznamená snímek projektu, jak je obsažen v oblasti připravených změn. Vše, co jste nepřipravili k zapsání, zůstane ve stavu změněno na vašem disku. Chcete-li i tyto soubory přidat do své historie, zapište další revizi. Pokaždé, když zapíšete revizi, nahrajete snímek svého projektu, k němuž se můžete později vrátit nebo ho můžete použít k srovnání. -### Skipping the Staging Area ### +### Přeskočení oblasti připravených změn ### -Although it can be amazingly useful for crafting commits exactly how you want them, the staging area is sometimes a bit more complex than you need in your workflow. If you want to skip the staging area, Git provides a simple shortcut. Providing the `-a` option to the `git commit` command makes Git automatically stage every file that is already tracked before doing the commit, letting you skip the `git add` part: +Přestože může být oblast připravených změn opravdu užitečným nástrojem pro přesné vytváření revizí, je někdy při daném pracovním postupu zbytečným mezikrokem. Chcete-li oblast připravených změn úplně přeskočit, nabízí Git jednoduchou zkratku. Přidáte-li k příkazu `git commit` parametr `-a`, Git do revize automaticky zahrne každý soubor, který je sledován. Odpadá potřeba zadávat příkaz `git add`: $ git status - # On branch master - # - # Changed but not updated: - # - # modified: benchmarks.rb - # + On branch master + Changes not staged for commit: + (use "git add ..." to update what will be committed) + (use "git checkout -- ..." to discard changes in working directory) + + modified: benchmarks.rb + + no changes added to commit (use "git add" and/or "git commit -a") $ git commit -a -m 'added new benchmarks' [master 83e38c7] added new benchmarks - 1 files changed, 5 insertions(+), 0 deletions(-) + 1 files changed, 5 insertions(+) -Notice how you don’t have to run `git add` on the benchmarks.rb file in this case before you commit. +Povšimněte si, že kvůli souboru `benchmarks.rb` v tomto případě nemusíte před zapsáním revize provádět příkaz `git add`. -### Removing Files ### +### Odstraňování souborů ### -To remove a file from Git, you have to remove it from your tracked files (more accurately, remove it from your staging area) and then commit. The `git rm` command does that and also removes the file from your working directory so you don’t see it as an untracked file next time around. +Chcete-li odstranit soubor ze systému Git, musíte ho odstranit ze sledovaných souborů (přesněji řečeno odstranit z oblasti připravených změn) a zapsat revizi. Odstranění provedete příkazem `git rm`, který odstraní soubor zároveň z vašeho pracovního adresáře, a proto ho už příště neuvidíte mezi nesledovanými soubory. -If you simply remove the file from your working directory, it shows up under the “Changed but not updated” (that is, _unstaged_) area of your `git status` output: +Pokud soubor jednoduše odstraníte z pracovního adresáře, zobrazí se ve výpisu `git status` v části „Changes not staged for commit“ (tedy *nepřipraveno*): $ rm grit.gemspec $ git status - # On branch master - # - # Changed but not updated: - # (use "git add/rm ..." to update what will be committed) - # - # deleted: grit.gemspec - # + On branch master + Changes not staged for commit: + (use "git add/rm ..." to update what will be committed) + (use "git checkout -- ..." to discard changes in working directory) + + deleted: grit.gemspec -Then, if you run `git rm`, it stages the file’s removal: + no changes added to commit (use "git add" and/or "git commit -a") + +Pokud nyní provedete příkaz `git rm`, bude k zapsání připraveno odstranění souboru: $ git rm grit.gemspec rm 'grit.gemspec' $ git status - # On branch master - # - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # deleted: grit.gemspec - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) + + deleted: grit.gemspec + -The next time you commit, the file will be gone and no longer tracked. If you modified the file and added it to the index already, you must force the removal with the `-f` option. This is a safety feature to prevent accidental removal of data that hasn’t yet been recorded in a snapshot and that can’t be recovered from Git. +Po příštím zapsání revize soubor zmizí a přestane být sledován. Pokud už jste soubor upravili a přidali do indexu, musíte odstranění provést pomocí parametru `-f`. Jedná se o bezpečnostní funkci, jež má zabránit nechtěnému odstranění dat, která ještě nebyla nahrána do snímku, a nemohou proto být ze systému Git obnovena. -Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. In other words, you may want to keep the file on your hard drive but not have Git track it anymore. This is particularly useful if you forgot to add something to your `.gitignore` file and accidentally added it, like a large log file or a bunch of `.a` compiled files. To do this, use the `--cached` option: +Další užitečnou možností, která se vám může hodit, je zachování souboru v pracovním stromě a odstranění z oblasti připravených změn. Soubor tak ponecháte na svém pevném disku, ale ukončíte jeho sledování systémem Git. To může být užitečné zejména v situaci, kdy něco zapomenete přidat do souboru `.gitignore`, a omylem to tak zahrnete do revize, např. velký log soubor nebo pár zkompilovaných souborů s příponou `.a`. V takovém případě použijte parametr `--cached`: $ git rm --cached readme.txt -You can pass files, directories, and file-glob patterns to the `git rm` command. That means you can do things such as +Příkaz `git rm` lze používat v kombinaci se soubory, adresáři a maskami souborů. Můžete tak zadat například příkaz ve tvaru: $ git rm log/\*.log -Note the backslash (`\`) in front of the `*`. This is necessary because Git does its own filename expansion in addition to your shell’s filename expansion. This command removes all files that have the `.log` extension in the `log/` directory. Or, you can do something like this: +Všimněte si tu zpětného lomítka (`\`) před znakem `*`. Je tu proto, že Git provádí své vlastní nahrazování masek souborů nad to, které provádí váš shell. Tímto příkazem odstraníte všechny soubory s příponou `.log` z adresáře `log/`. Provést můžete také tento příkaz: $ git rm \*~ -This command removes all files that end with `~`. +Tento příkaz odstraní všechny soubory, které končí vlnovkou (`~`). -### Moving Files ### +### Přesouvání souborů ### -Unlike many other VCS systems, Git doesn’t explicitly track file movement. If you rename a file in Git, no metadata is stored in Git that tells it you renamed the file. However, Git is pretty smart about figuring that out after the fact — we’ll deal with detecting file movement a bit later. +Na rozdíl od ostatních systémů pro správu verzí nesleduje Git explicitně přesouvání souborů. Pokud soubor v systému Git přejmenujete, neuloží se žádná metadata s informací, že jste soubor přejmenovali. Git však používá jinou fintu, aby zjistil, že byl soubor přejmenován. Na ni se podíváme později. -Thus it’s a bit confusing that Git has a `mv` command. If you want to rename a file in Git, you can run something like +Může se zdát zvláštní, že Git přesto používá příkaz `mv`. Chcete-li v systému Git přejmenovat soubor, můžete spustit třeba příkaz - $ git mv file_from file_to + $ git mv původní_název nový_název -and it works fine. In fact, if you run something like this and look at the status, you’ll see that Git considers it a renamed file: +a vše funguje na výbornou. A skutečně, pokud takový příkaz provedete a podíváte se na stav souboru, uvidíte, že ho Git považuje za přejmenovaný (renamed): - $ git mv README.txt README + $ git mv README README.txt $ git status - # On branch master - # Your branch is ahead of 'origin/master' by 1 commit. - # - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # renamed: README.txt -> README - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) -However, this is equivalent to running something like this: + renamed: README -> README.txt - $ mv README.txt README - $ git rm README.txt - $ 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 `mv` is one command instead of three — it’s a convenience function. More important, you can use any tool you like to rename a file, and address the add/rm later, before you commit. +Výsledek je však stejný, jako byste provedli následující: + + $ mv README README.txt + $ git rm README + $ git add README.txt + +Git implicitně zjistí, že se jedná o přejmenování, a proto nehraje roli, zda přejmenujete soubor tímto způsobem, nebo pomocí příkazu `mv`. Jediným skutečným rozdílem je, že `mv` je jediný příkaz, zatímco u druhého způsobu potřebujete příkazy tři — příkaz `mv` je pouze zjednodušením. Důležitější je, že můžete použít jakýkoli způsob přejmenování a příkaz add/rm provést později, před zapsáním revize. -## Viewing the Commit History ## +## Zobrazení historie revizí ## -After you have created several commits, or if you have cloned a repository with an existing commit history, you’ll probably want to look back to see what has happened. The most basic and powerful tool to do this is the `git log` command. +Až vytvoříte několik revizí nebo pokud naklonujete repozitář s existující historií revizí, možná budete chtít nahlédnout do historie projektu. Nejzákladnějším a nejmocnějším nástrojem je v tomto případě příkaz `git log`. -These examples use a very simple project called simplegit that I often use for demonstrations. To get the project, run +Následující příklady ukazují velmi jednoduchý projekt pojmenovaný `simplegit`, který pro názornost často používám. Chcete-li si projekt naklonovat, zadejte: git clone git://github.com/schacon/simplegit-progit.git -When you run `git log` in this project, you should get output that looks something like this: +Po zadání příkazu `git log` v tomto projektu byste měli dostat výstup, který vypadá zhruba takto: $ git log commit ca82a6dff817ec66f44342007202690a93763949 @@ -498,13 +452,13 @@ When you run `git log` in this project, you should get output that looks somethi first commit -By default, with no arguments, `git log` lists the commits made in that repository in reverse chronological order. That is, the most recent commits show up first. As you can see, this command lists each commit with its SHA-1 checksum, the author’s name and e-mail, the date written, and the commit message. +Ve výchozím nastavení a bez dalších parametrů vypíše příkaz `git log` revize provedené v daném repozitáři v obráceném chronologickém pořadí. Nejnovější revize tak budou uvedeny nahoře. Jak vidíte, tento příkaz vypíše všechny revize s jejich kontrolním součtem SHA-1, jménem a e-mailem autora, datem zápisu a zprávou o revizi. -A huge number and variety of options to the `git log` command are available to show you exactly what you’re looking for. Here, we’ll show you some of the most-used options. +K příkazu `git log` je k dispozici velké množství nejrůznějších parametrů, díky nimž můžete zobrazit přesně to, co potřebujete. Ukážeme si některé z nejpoužívanějších možností. -One of the more helpful options is `-p`, which shows the diff introduced in each commit. You can also use `-2`, which limits the output to only the last two entries: +Jedním z nejužitečnějších je parametr `-p`, který zobrazí rozdíly (diff) provedené v každé revizi. Můžete také použít parametr `-2`, který omezí výpis pouze na dva poslední záznamy: - $ git log –p -2 + $ git log -p -2 commit ca82a6dff817ec66f44342007202690a93763949 Author: Scott Chacon Date: Mon Mar 17 21:52:11 2008 -0700 @@ -515,11 +469,13 @@ One of the more helpful options is `-p`, which shows the diff introduced in each index a874b73..8f94139 100644 --- a/Rakefile +++ b/Rakefile - @@ -5,7 +5,7 @@ require 'rake/gempackagetask' + @@ -5,5 +5,5 @@ require 'rake/gempackagetask' spec = Gem::Specification.new do |s| + s.name = "simplegit" - s.version = "0.1.0" + s.version = "0.1.1" s.author = "Scott Chacon" + s.email = "schacon@gee-mail.com commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 Author: Scott Chacon @@ -542,10 +498,31 @@ One of the more helpful options is `-p`, which shows the diff introduced in each -end \ No newline at end of file -This option displays the same information but with a diff directly following each entry. This is very helpful for code review or to quickly browse what happened during a series of commits that a collaborator has added. -You can also use a series of summarizing options with `git log`. For example, if you want to see some abbreviated stats for each commit, you can use the `--stat` option: +Tento parametr zobrazí tytéž informace, ale za každým záznamem následuje informace o rozdílech. Tato funkce je velmi užitečná při kontrole kódu nebo k rychlému zjištění, co bylo obsahem série revizí, které přidal váš spolupracovník. + +Někdy se změny kontrolují snadněji na úrovni slov než na úrovni řádků. Git nabízí parametr `--word-diff`, který můžeme přidat za příkaz `git log -p`. Místo obvyklé detekce rozdílů po řádcích získáme rozdíly po slovech. Zjišťování rozdílů po slovech je u zdrojového kódu celkem k ničemu, ale pokud porovnáváme velké textové soubory -- jako například knihy nebo vaši disertační práci --, pak se tato možnost hodí. Tady máme příklad: + + $ git log -U1 --word-diff + commit ca82a6dff817ec66f44342007202690a93763949 + Author: Scott Chacon + Date: Mon Mar 17 21:52:11 2008 -0700 + + changed the version number + + diff --git a/Rakefile b/Rakefile + index a874b73..8f94139 100644 + --- a/Rakefile + +++ b/Rakefile + @@ -7,3 +7,3 @@ spec = Gem::Specification.new do |s| + s.name = "simplegit" + s.version = [-"0.1.0"-]{+"0.1.1"+} + s.author = "Scott Chacon" + +Jak vidíte, výstup neobsahuje žádné přidané a odstraněné řádky, jak tomu bývá u běžného zobrazení rozdílů (diff). Místo toho se změny zobrazují uvnitř textu. Přidaná slova jsou uzavřena mezi značkami `{+ +}` a odstraněná jsou uzavřena v `[- -]`. Možná byste také rádi zredukovali obvyklé třířádkové okolí změny na pouhý jeden řádek, protože chcete znát okolí slova a ne okolí řádku. Můžeme toho dosáhnout zadáním parametru `-U1`, jako ve výše uvedeném příkladu. - $ git log --stat +Ve spojení s příkazem `git log` můžete použít také celou řadu shrnujících parametrů. Pokud například chcete zobrazit některé stručné statistiky pro každou revizi, použijte parametr `--stat`: + + $ git log --stat commit ca82a6dff817ec66f44342007202690a93763949 Author: Scott Chacon Date: Mon Mar 17 21:52:11 2008 -0700 @@ -553,7 +530,7 @@ You can also use a series of summarizing options with `git log`. For example, if changed the version number Rakefile | 2 +- - 1 files changed, 1 insertions(+), 1 deletions(-) + 1 file changed, 1 insertion(+), 1 deletion(-) commit 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 Author: Scott Chacon @@ -562,7 +539,7 @@ You can also use a series of summarizing options with `git log`. For example, if removed unnecessary test code lib/simplegit.rb | 5 ----- - 1 files changed, 0 insertions(+), 5 deletions(-) + 1 file changed, 5 deletions(-) commit a11bef06a3f659402fe7563abf99ad00de2209e6 Author: Scott Chacon @@ -573,98 +550,162 @@ You can also use a series of summarizing options with `git log`. For example, if README | 6 ++++++ Rakefile | 23 +++++++++++++++++++++++ lib/simplegit.rb | 25 +++++++++++++++++++++++++ - 3 files changed, 54 insertions(+), 0 deletions(-) + 3 files changed, 54 insertions(+) -As you can see, the `--stat` option prints below each commit entry a list of modified files, how many files were changed, and how many lines in those files were added and removed. It also puts a summary of the information at the end. -Another really useful option is `--pretty`. This option changes the log output to formats other than the default. A few prebuilt options are available for you to use. The oneline option prints each commit on a single line, which is useful if you’re looking at a lot of commits. In addition, the `short`, `full`, and `fuller` options show the output in roughly the same format but with less or more information, respectively: +Jak vidíte, parametr `--stat` vypíše pod každým záznamem revize seznam změněných souborů, kolik souborů bylo změněno (changed) a kolik řádků bylo v těchto souborech vloženo (insertions) a smazáno (deletions). Zároveň vloží na konec výpisu shrnutí těchto informací. +Další opravdu užitečnou možností je parametr `--pretty`. Tento parametr změní výstup logu na jiný než výchozí formát. K dispozici máte několik přednastavených možností. Parametr `oneline` vypíše všechny revize na jednom řádku. Tuto možnost oceníte při velkém množství revizí. Dále se nabízejí parametry `short`, `full` a `fuller` (zkrácený, plný, úplný). Zobrazují výstup přibližně ve stejném formátu, avšak s více či méně podrobnými informacemi: $ git log --pretty=oneline ca82a6dff817ec66f44342007202690a93763949 changed the version number 085bb3bcb608e1e8451d4b2432f8ecbe6306e7e7 removed unnecessary test code a11bef06a3f659402fe7563abf99ad00de2209e6 first commit -The most interesting option is `format`, which allows you to specify your own log output format. This is especially useful when you’re generating output for machine parsing — because you specify the format explicitly, you know it won’t change with updates to Git: +Nejzajímavějším parametrem je pak `format`, který umožňuje definovat vlastní formát výstupu logu. Tato možnost je užitečná zejména v situaci, kdy vytváříte výpis pro strojovou analýzu. Jelikož specifikujete formát explicitně, máte jistotu, že se s aktualizací systému Git nezmění: $ git log --pretty=format:"%h - %an, %ar : %s" ca82a6d - Scott Chacon, 11 months ago : changed the version number 085bb3b - Scott Chacon, 11 months ago : removed unnecessary test code a11bef0 - Scott Chacon, 11 months ago : first commit -Table 2-1 lists some of the more useful options that format takes. - - Option Description of Output - %H Commit hash - %h Abbreviated commit hash - %T Tree hash - %t Abbreviated tree hash - %P Parent hashes - %p Abbreviated parent hashes - %an Author name - %ae Author e-mail - %ad Author date (format respects the –date= option) - %ar Author date, relative - %cn Committer name - %ce Committer email - %cd Committer date - %cr Committer date, relative - %s Subject - -You may be wondering what the difference is between _author_ and _committer_. The author is the person who originally wrote the work, whereas the committer is the person who last applied the work. So, if you send in a patch to a project and one of the core members applies the patch, both of you get credit — you as the author and the core member as the committer. We’ll cover this distinction a bit more in Chapter 5. - -The oneline and format options are particularly useful with another `log` option called `--graph`. This option adds a nice little ASCII graph showing your branch and merge history, which we can see our copy of the Grit project repository: +Tabulka 2-1 uvádí některé užitečné parametry, které format akceptuje. + + + + Parametr Popis výstupu + %H Otisk (hash) revize + %h Zkrácený otisk revize + %T Otisk stromu + %t Zkrácený otisk stromu + %P Otisky rodičovských revizí + %p Zkrácené otisky rodičovských revizí + %an Jméno autora + %ae E-mail autora + %ad Datum autora (formát je možné nastavit parametrem --date) + %ar Datum autora, relativní + %cn Jméno autora revize + %ce E-mail autora revize + %cd Datum autora revize + %cr Datum autora revize, relativní + %s Předmět + +Možná se ptáte, jaký je rozdíl mezi *autorem* a *autorem revize*. *Autor* (author) je osoba, která práci původně napsala, zatímco *autor revize* (committer) je osoba, která práci zapsala do repozitáře. Pokud tedy pošlete záplatu k projektu a některý z ústředních členů (core members) ji použije, do výpisu se dostanete oba – vy jako autor a core member jako autor revize. K tomuto rozlišení se blíže dostaneme v *kapitole 5*. + +Parametry `oneline` a `format` jsou zvlášť užitečné ve spojení s další možností `log`u – parametrem `--graph`. Tento parametr vloží pěkný malý ASCII graf, znázorňující historii vaší větve a slučování, kterou si ukážeme na naší kopii repozitáře projektu Grit: $ git log --pretty=format:"%h %s" --graph * 2d3acf9 ignore errors from SIGCHLD on trap * 5e3ee11 Merge branch 'master' of git://github.com/dustin/grit - |\ + |\ | * 420eac9 Added a method for getting the current branch. * | 30e367c timeout code and tests * | 5a09431 add timeout protection to grit * | e1193f8 support for heads with slashes in them - |/ + |/ * d6016bc require time for xmlschema * 11d191e Merge branch 'defunkt' into local -Those are only some simple output-formatting options to `git log` — there are many more. Table 2-2 lists the options we’ve covered so far and some other common formatting options that may be useful, along with how they change the output of the log command. +To je jen několik základních parametrů k formátování výstupu pro příkaz `git log`, celkově jich je mnohem více. Tabulka 2-2 uvádí parametry, které jsme už zmínili, a některé další běžné parametry formátování, které mohou být užitečné. Pravý sloupec popisuje, jak který parametr změní výstup `log`u. + + - 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. - --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. Options include oneline, short, full, fuller, and format (where you specify your own format). + Parametr Popis + -p Zobrazí záplatu vytvořenou s každou revizí. + --word-diff Zobrazí záplatu ve tvaru rozdílu po slovech. + --stat Zobrazí statistiku pro změněné soubory v každé revizi. + --shortstat Zobrazí pouze řádek změněno/vloženo/smazáno z příkazu --stat. + --name-only Za informacemi o revizi zobrazí seznam změněných souborů. + --name-status Zobrazí seznam dotčených souborů spolu s informací přidáno/změněno/smazáno. + --abbrev-commit Zobrazí pouze prvních několik znaků kontrolního součtu SHA-1 místo všech 40. + --relative-date Zobrazí datum v relativním formátu (např. "2 weeks ago", tj. před 2 týdny) místo formátu s úplným datem. + --graph Zobrazí vedle výstupu logu ASCII graf k historii větve a slučování. + --pretty Zobrazí revize v alternativním formátu. Parametry příkazu jsou oneline, short, full, fuller a format (ve kterém uvedete svůj vlastní formát). + --oneline Užitečná zkratka pro `--pretty=oneline --abbrev-commit`. -### Limiting Log Output ### +### Omezení výstupu logu ### -In addition to output-formatting options, git log takes a number of useful limiting options — that is, options that let you show only a subset of commits. You’ve seen one such option already — the `-2` option, which show only the last two commits. In fact, you can do `-`, where `n` is any integer to show the last `n` commits. In reality, you’re unlikely to use that often, because Git by default pipes all output through a pager so you see only one page of log output at a time. +Kromě parametrů k formátování výstupu lze pro `git log` použít také celou řadu omezujících parametrů, tj. takových, které zobrazí jen definovanou podmnožinu revizí. My už jsme se s jedním takovým parametrem setkali. Byl to parametr `-2`, který zobrazí pouze dvě poslední revize. Obecně lze tedy říci, že můžete zadat parametr `-`, kde `n` je libovolné celé číslo pro zobrazení posledních `n` revizí. Je však třeba dodat, že tuto funkci asi nebudete využívat příliš často. Git totiž standardně redukuje všechny výpisy stránkovačem, a proto se vždy najednou zobrazí pouze jedna stránka logu. -However, the time-limiting options such as `--since` and `--until` are very useful. For example, this command gets the list of commits made in the last two weeks: +Velmi užitečné jsou naproti tomu časově omezující parametry, jako `--since` a `--until` („od“ a „do“). Například tento příkaz zobrazí seznam všech revizí pořízených za poslední dva týdny (2 weeks): $ git log --since=2.weeks -This command works with lots of formats — you can specify a specific date (“2008-01-15”) or a relative date such as “2 years 1 day 3 minutes ago”. +Tento příkaz pracuje s velkým množstvím formátů. Můžete zadat konkrétní datum („2008-01-15“) nebo relativní datum, např. „2 years 1 day 3 minutes ago“ (před 2 roky, 1 dnem a 3 minutami). + +Z výpisu rovněž můžete filtrovat pouze revize, které odpovídají určitým kritériím. Parametr `--author` umožňuje filtrovat výpisy podle konkrétního autora, pomocí parametru `--grep` můžete ve zprávách k revizím vyhledávat klíčová slova. (Všimněte si, že pokud použijete současně parametry author a grep, bude příkaz vyhledávat záznamy splňující obojí.) + +Pokud chcete zadat více parametrů grep, musíte přidat výraz `--all-match`, jinak se bude hledat kterýkoli z nich. + +Posledním opravdu užitečným parametrem, který lze přidat k příkazu `git log` , je zadání cesty. Jestliže zadáte název adresáře nebo souboru, výstup logu tím omezíte na revize, které provedly změnu v těchto souborech. Cesta je vždy posledním parametrem a většinou jí předcházejí dvě pomlčky (`--`) , jimiž je oddělena od ostatních parametrů. + +Tabulka 2-3 uvádí pro přehlednost zmíněné parametry a několik málo dalších. Tabulka 2.2 + + + + Parametr Popis + -(n) Zobrazí pouze posledních n revizí. + --since, --after Omezí výpis na revize provedené po zadaném datu. + --until, --before Omezí výpis na revize provedené před zadaným datem. + --author Zobrazí pouze revize, v nichž autor odpovídá zadanému řetězci. + --committer Zobrazí pouze revize, v nichž autor revize odpovídá zadanému řetězci. + + +### Omezení výstupního logu na určité datum nebo čas ### + +Pokud chcete zjistit, které revize (commit) v repozitáři se zdrojovým kódem Git (git://git.kernel.org/pub/scm/git/git.git) mají datum zápisu (CommitDate) 2014-04-29 -- relativně k vašemu lokálnímu časovému pásmu (takovému, jaké je nastaveno na vašem počítači), použijte příkaz + + $ git log --after="2014-04-29 00:00:00" --before="2014-04-29 23:59:59" \ + --pretty=fuller + +Protože se výstup bude lišit podle časového pásma v místě spuštění, doporučuje se v argumentech `--after` a `--before` vždy používat absolutní čas (například ve formátu ISO 8601, který obsahuje i informaci o časovém pásmu). Činíme tak proto, aby každý, kdo stejný příkaz spustí, obdržel stejné, opakovatelné výsledky. + +Pokud chceme získat zápisy z určitého časového okamžiku (například z 29. dubna 2013 v 17:07:22 středoevropského času), můžeme použít příkaz + + $ git log --after="2013-04-29T17:07:22+0200" \ + --before="2013-04-29T17:07:22+0200" --pretty=fuller -You can also filter the list to commits that match some search criteria. The `--author` option allows you to filter on a specific author, and the `--grep` option lets you search for keywords in the commit messages. (Note that if you want to specify both author and grep options, you have to add `--all-match` or the command will match commits with either.) + commit de7c201a10857e5d424dbd8db880a6f24ba250f9 + Author: Ramkumar Ramachandra + AuthorDate: Mon Apr 29 18:19:37 2013 +0530 + Commit: Junio C Hamano + CommitDate: Mon Apr 29 08:07:22 2013 -0700 -The last really useful option to pass to `git log` as a filter is a path. If you specify a directory or file name, you can limit the log output to commits that introduced a change to those files. This is always the last option and is generally preceded by double dashes (`--`) to separate the paths from the options. + git-completion.bash: lexical sorting for diff.statGraphWidth -In Table 2-3 we’ll list these and a few other common options for your reference. + df44483a (diff --stat: add config option to limit graph width, + 2012-03-01) added the option diff.startGraphWidth to the list of + configuration variables in git-completion.bash, but failed to notice + that the list is sorted alphabetically. Move it to its rightful place + in the list. - Option Description - -(n) 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. + Signed-off-by: Ramkumar Ramachandra + Signed-off-by: Junio C Hamano -For example, if you want to see which commits modifying test files in the Git source code history were committed by Junio Hamano and were not merges in the month of October 2008, you can run something like this: +Výše uvedené časy (`AuthorDate`, `CommitDate`) se zobrazují v základním tvaru (`--date=default`), který zobrazuje informaci o časovém pásmu autora nebo přispěvatele. - $ git log --pretty="%h - %s" --author=gitster --since="2008-10-01" \ - --before="2008-11-01" --no-merges -- t/ +K dalším užitečným formátům patří `--date=iso` (ISO 8601), `--date=rfc` (RFC 2822), `--date=raw` (sekundy od počátku (epoch; 1970-01-01 UTC)), `--date=local` (časy ve vašem lokálním časovém pásmu) a také `--date=relative` (jako například "2 hours ago", tj. před dvěma hodinami). + +Pokud použijete příkaz `git log` bez určení času, uvažuje se čas odpovídající okamžiku spuštění na vašem počítači (používá stejný posun vůči UTC). + +Pokud například na vašem počítači spustíte `git log` v 09:00 a vaše časové pásmo je vůči greenwichskému času posunuto o tři hodiny vpřed, pak se výsledek následujících dvou příkazů shoduje: + + $ git log --after=2008-06-01 --before=2008-07-01 + $ git log --after="2008-06-01T09:00:00+0300" \ + --before="2008-07-01T09:00:00+0300" + +A poslední příklad. Pokud chcete zjistit, které revize upravující testovací soubory ve zdrojovém kódu Git zapsal Junio Hamano v říjnu 2008 (relativě k časové zóně New Yorku) a které přitom nebyly sloučením (merge), můžete zadat následující příkaz: + + $ git log --pretty="%h - %s" --author=gitster \ + --after="2008-10-01T00:00:00-0400" \ + --before="2008-10-31T23:59:59-0400" --no-merges -- t/ 5610e3b - Fix testcase failure when extended attribute acd3b9e - Enhance hold_lock_file_for_{update,append}() f563754 - demonstrate breakage of detached checkout wi @@ -672,125 +713,127 @@ For example, if you want to see which commits modifying test files in the Git so 51a94af - Fix "checkout --track -b newbranch" on detac b0ad11e - pull: allow "git pull origin $something:$cur -Of the nearly 20,000 commits in the Git source code history, this command shows the 6 that match those criteria. +Z více než 36 tisíc revizí v historii zdrojového kódu Git zobrazí tento příkaz 6 záznamů, které odpovídají zadaným kritériím. -### Using a GUI to Visualize History ### +### Grafické uživatelské rozhraní pro procházení historie ### -If you like to use a more graphical tool to visualize your commit history, you may want to take a look at a Tcl/Tk program called gitk that is distributed with Git. Gitk is basically a visual `git log` tool, and it accepts nearly all the filtering options that `git log` does. If you type gitk on the command line in your project, you should see something like Figure 2-2. +Chcete-li použít graficky výrazněji zpracovaný nástroj k procházení historie revizí, možná oceníte Tcl/Tk program nazvaný `gitk`, který je distribuován spolu se systémem Git. Gitk je v zásadě grafická verze příkazu `git log` a umožňuje téměř všechny možnosti filtrování jako `git log`. Pokud do příkazového řádku ve svém projektu zadáte příkaz `gitk`, otevře se okno podobné jako na obrázku 2-2. -Insert 18333fig0202.png -Figure 2-2. The gitk history visualizer +Insert 18333fig0202.png +Obrázek 2-2. Graficky zpracovaná historie v nástroji „gitk“ -You can see the commit history in the top half of the window along with a nice ancestry graph. The diff viewer in the bottom half of the window shows you the changes introduced at any commit you click. +V horní polovině okna vidíte historii revizí, doplněnou názorným hierarchickým grafem. Prohlížeč rozdílů v dolní polovině okna zobrazuje změny provedené v každé revizi, na niž kliknete. -## Undoing Things ## +## Rušení změn ## -At any stage, you may want to undo something. Here, we’ll review a few basic tools for undoing changes that you’ve made. Be careful, because you can’t always undo some of these undos. This is one of the few areas in Git where you may lose some work if you do it wrong. +Kdykoli se může stát, že byste nějakou úpravu chtěli vrátit do původního stavu.. Podívejme se proto, jaké základní nástroje se nám tu nabízejí. Ale buďte opatrní! Ne všechny zrušené změny se dají vrátit. Je to jedna z mála oblastí v systému Git, kdy při neuváženém postupu riskujete, že přijdete o část své práce. -### Changing Your Last Commit ### +### Změna poslední revize ### -One of the common undos takes place when you commit too early and possibly forget to add some files, or you mess up your commit message. If you want to try that commit again, you can run commit with the `--amend` option: +Jedním z nejčastějších důvodů pro rušení úprav je situace, kdy zapíšete revizi příliš brzy a ještě jste například zapomněli přidat některé soubory, nebo byste rádi změnili zprávu k revizi. Chcete-li opravit poslední revizi, můžete spustit příkaz commit s parametrem `--amend`: $ git commit --amend -This command takes your staging area and uses it for the commit. If you’ve have made no changes since your last commit (for instance, you run this command immediately after your previous commit), then your snapshot will look exactly the same and all you’ll change is your commit message. +Tento příkaz vezme vaši oblast připravených změn a použije ji k vytvoření revize. Pokud jste od poslední revize neprovedli žádné změny (například spustíte tento příkaz bezprostředně po předchozí revizi), bude snímek vypadat úplně stejně a jediné, co změníte, je zpráva k revizi. -The same commit-message editor fires up, but it already contains the message of your previous commit. You can edit the message the same as always, but it overwrites your previous commit. +Spustí se stejný editor pro editaci zpráv k revizím, ale tentokrát už obsahuje zprávu z vaší předchozí revize. Zprávu můžete editovat stejným způsobem jako vždy. Zpráva přepíše předchozí revizi. -As an example, if you commit and then realize you forgot to stage the changes in a file you wanted to add to this commit, you can do something like this: +Pokud například zapíšete revizi a potom si uvědomíte, že jste zapomněli připravit k zapsání změny v souboru, který jste chtěli do této revize přidat, můžete provést následující: $ git commit -m 'initial commit' $ git add forgotten_file - $ git commit --amend + $ git commit --amend -All three of these commands end up with a single commit — the second command replaces the results of the first. +Provedení uvedených tří příkazů zůstane jediná revize – druhý příkaz `commit` nahradí výsledky prvního. -### Unstaging a Staged File ### +### Odstranění souboru z oblasti připravených změn ### -The next two sections demonstrate how to wrangle your staging area and working directory changes. The nice part is that the command you use to determine the state of those two areas also reminds you how to undo changes to them. For example, let’s say you’ve changed two files and want to commit them as two separate changes, but you accidentally type `git add *` and stage them both. How can you unstage one of the two? The `git status` command reminds you: +Následující dvě části popisují, jak se poprat s oblastí připravených změn a se změnami v pracovním adresáři. Je příjemné, že příkaz, jímž se zjišťuje stav těchto dvou oblastí, zároveň připomíná, jak v nich nežádoucí změny zrušit. Řekněme například, že jste změnili dva soubory a chcete je zapsat jako dvě oddělené změny. Jenže omylem jste zadali příkaz `git add *` a oba soubory jste tím připravili k zapsání. Jak lze tyto dva soubory vrátit z oblasti připravených změn? Připomene vám to příkaz `git status`: $ git add . $ git status - # On branch master - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # modified: README.txt - # modified: benchmarks.rb - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) -Right below the “Changes to be committed” text, it says use `git reset HEAD ...` to unstage. So, let’s use that advice to unstage the benchmarks.rb file: + modified: README.txt + modified: benchmarks.rb - $ git reset HEAD benchmarks.rb - benchmarks.rb: locally modified + +Přímo pod nadpisem „Changes to be committed“ (Změny k zapsání) se říká: pro návrat z oblasti připravených změn použijte příkaz `git reset HEAD ...` Budeme se tedy řídit touto radou a vrátíme soubor `benchmarks.rb` z oblasti připravených změn: + + $ git reset HEAD benchmarks.rb + Unstaged changes after reset: + M benchmarks.rb $ git status - # On branch master - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # modified: README.txt - # - # Changed but not updated: - # (use "git add ..." to update what will be committed) - # (use "git checkout -- ..." to discard changes in working directory) - # - # modified: benchmarks.rb - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) -The command is a bit strange, but it works. The benchmarks.rb file is modified but once again unstaged. + modified: README.txt -### Unmodifying a Modified File ### + Changes not staged for commit: + (use "git add ..." to update what will be committed) + (use "git checkout -- ..." to discard changes in working directory) -What if you realize that you don’t want to keep your changes to the benchmarks.rb file? How can you easily unmodify it — revert it back to what it looked like when you last committed (or initially cloned, or however you got it into your working directory)? Luckily, `git status` tells you how to do that, too. In the last example output, the unstaged area looks like this: + modified: benchmarks.rb - # Changed but not updated: - # (use "git add ..." to update what will be committed) - # (use "git checkout -- ..." to discard changes in working directory) - # - # modified: benchmarks.rb - # -It tells you pretty explicitly how to discard the changes you’ve made (at least, the newer versions of Git, 1.6.1 and later, do this — if you have an older version, we highly recommend upgrading it to get some of these nicer usability features). Let’s do what it says: +Příkaz je sice trochu zvláštní, ale funguje. Soubor `benchmarks.rb` má stav „změněn“, ale už se nenachází v oblasti připravených změn. + +### Rušení změn ve změněných souborech ### + +A co když zjistíte, že nechcete zachovat změny, které jste provedli v souboru `benchmarks.rb`? Jak je můžete snadno zrušit a vrátit soubor zpět do podoby při poslední revizi (nebo při prvním klonování nebo v jakémkoli okamžiku, kdy jste ho zaznamenali v pracovním adresáři)? Příkaz `git status` vám naštěstí řekne, co dělat. U posledního příkladu vypadá oblast připravených změn takto: + + Changes not staged for commit: + (use "git add ..." to update what will be committed) + (use "git checkout -- ..." to discard changes in working directory) + + modified: benchmarks.rb + + +Výpis vám sděluje, jak zahodit změny (discard changes), které jste provedli (přinejmenším tak činí novější verze systému Git, od verze 1.6.1; pokud máte starší verzi, doporučujeme ji aktualizovat, čímž získáte některé z těchto vylepšených funkcí). Uděláme, co nám výpis radí: $ git checkout -- benchmarks.rb $ git status - # On branch master - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # modified: README.txt - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) + + modified: README.txt -You can see that the changes have been reverted. You should also realize that this is a dangerous command: any changes you made to that file are gone — you just copied another file over it. Don’t ever use this command unless you absolutely know that you don’t want the file. If you just need to get it out of the way, we’ll go over stashing and branching in the next chapter; these are generally better ways to go. -Remember, anything that is committed in Git can almost always be recovered. Even commits that were on branches that were deleted or commits that were overwritten with an `--amend` commit can be recovered (see Chapter 9 for data recovery). However, anything you lose that was never committed is likely never to be seen again. +Jak vidíte, změny byly zahozeny. Všimněte si také, že se jedná o nebezpečný příkaz. Veškeré změny, které jste v souboru provedli, jsou ztraceny, soubor jste právě překopírovali jiným souborem. Nikdy tento příkaz nepoužívejte, pokud si nejste zcela jisti, že už daný soubor nebudete potřebovat. Pokud potřebujete pouze odstranit soubor z cesty, podívejte se na odkládání (stashing) a větvení v následující kapitole. Tyto postupy většinou bývají vhodnější. -## Working with Remotes ## +Zapamatujte si, že vše, co je zapsáno v systému Git, lze téměř vždy obnovit. Obnovit lze dokonce i revize na odstraněných větvích nebo revize, které byly přepsány revizí `--amend` (o obnovování dat viz *kapitola 9*). Pokud však dojde ke ztrátě dat, která dosud nebyla součástí žádné revize, bude tato ztráta patrně nevratná. -To be able to collaborate on any Git project, you need to know how to manage your remote repositories. Remote repositories are versions of your project that are hosted on the Internet or network somewhere. You can have several of them, each of which generally is either read-only or read/write for you. Collaborating with others involves managing these remote repositories and pushing and pulling data to and from them when you need to share work. -Managing remote repositories includes knowing how to add remote repositories, remove remotes that are no longer valid, manage various remote branches and define them as being tracked or not, and more. In this section, we’ll cover these remote-management skills. +## Práce se vzdálenými repozitáři ## -### Showing Your Remotes ### +Abyste mohli spolupracovat na projektech v systému Git, je třeba vědět, jak manipulovat se vzdálenými repozitáři (remote repositories). Vzdálené repozitáře jsou verze vašeho projektu umístěné na Internetu nebo kdekoli v síti. Vzdálených repozitářů můžete mít hned několik, každý pro vás přitom bude buď pouze ke čtení (read-only) nebo ke čtení a zápisu (read write). Spolupráce s ostatními uživateli zahrnuje také správu těchto vzdálených repozitářů. Při sdílení práce musíte do těchto repozitářů data odesílat (push) a zase je z nich stahovat (pull). +Při správě vzdálených repozitářů musíte vědět, jak lze přidat vzdálený repozitář, jak odstranit vzdálený repozitář, který už není platný, jak spravovat různé vzdálené větve, jak je definovat jako sledované či nesledované a další věci. V této části se zaměříme právě na správu vzdálených repozitářů. -To see which remote servers you have configured, you can run the git remote command. It lists the shortnames of each remote handle you’ve specified. If you’ve cloned your repository, you should at least see origin — that is the default name Git gives to the server you cloned from: +### Zobrazení vzdálených serverů ### + +Chcete-li zjistit, jaké vzdálené servery máte nakonfigurovány, můžete použít příkaz `git remote`. Systém vypíše krátké názvy, přes které se se vzdálenými repozitáři manipuluje, a které jste dříve určili. Pokud byl váš repozitář vytvořen klonováním, měli byste vidět přinejmenším server *origin*. Jde o výchozí název, který Git dává serveru, z nějž jste repozitář klonovali. $ git clone git://github.com/schacon/ticgit.git - Initialized empty Git repository in /private/tmp/ticgit/.git/ - remote: Counting objects: 595, done. - remote: Compressing objects: 100% (269/269), done. - remote: Total 595 (delta 255), reused 589 (delta 253) - Receiving objects: 100% (595/595), 73.31 KiB | 1 KiB/s, done. - Resolving deltas: 100% (255/255), done. + Cloning into 'ticgit'... + remote: Reusing existing pack: 1857, done. + remote: Total 1857 (delta 0), reused 0 (delta 0) + Receiving objects: 100% (1857/1857), 374.35 KiB | 193.00 KiB/s, done. + Resolving deltas: 100% (772/772), done. + Checking connectivity... done. $ cd ticgit - $ git remote + $ git remote origin -You can also specify `-v`, which shows you the URL that Git has stored for the shortname to be expanded to: +Můžete rovněž zadat parametr `-v`, jenž zobrazí adresu URL, kterou má Git uloženou pro zkrácený název, který si přejete rozepsat. $ git remote -v - origin git://github.com/schacon/ticgit.git + origin git://github.com/schacon/ticgit.git (fetch) + origin git://github.com/schacon/ticgit.git (push) -If you have more than one remote, the command lists them all. For example, my Grit repository looks something like this. +Pokud používáte více než jeden vzdálený repozitář, příkaz je vypíše všechny. Například můj repozitář Grit vypadá takto: $ cd grit $ git remote -v @@ -800,11 +843,11 @@ If you have more than one remote, the command lists them all. For example, my Gr koke git://github.com/koke/grit.git origin git@github.com:mojombo/grit.git -This means we can pull contributions from any of these users pretty easily. But notice that only the origin remote is an SSH URL, so it’s the only one I can push to (we’ll cover why this is in Chapter 4). +To znamená, že mohu velmi snadno stáhnout příspěvky od kteréhokoli z těchto uživatelů. Ale všimněte si, že pouze vzdálený server origin je SSH URL, a je tedy jediným repozitářem, kam lze soubory odesílat (push; důvod objasníme v *kapitole 4*). -### Adding Remote Repositories ### +### Přidávání vzdálených repozitářů ### -I’ve mentioned and given some demonstrations of adding remote repositories in previous sections, but here is how to do it explicitly. To add a new remote Git repository as a shortname you can reference easily, run `git remote add [shortname] [url]`: +V předchozích částech už jsem se letmo dotkl přidávání vzdálených repozitářů. V této části se dostávám k tomu, jak přesně při přidávání postupovat. Chcete-li přidat nový vzdálený repozitář Git a zadat zkrácený název, přes který se můžete snadno odkazovat, spusťte příkaz `git remote add [zkrácený název] [url]`: $ git remote origin @@ -813,7 +856,7 @@ I’ve mentioned and given some demonstrations of adding remote repositories in origin git://github.com/schacon/ticgit.git pb git://github.com/paulboone/ticgit.git -Now you can use the string pb on the command line in lieu 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: +Řetězec `pb` nyní můžete používat na příkazovém řádku místo kompletní adresy URL. Pokud například chcete vyzvednout (fetch) všechny informace, které má Paul, ale vy je ještě nemáte ve svém repozitáři, můžete spustit příkaz `git fetch pb`: $ git fetch pb remote: Counting objects: 58, done. @@ -824,31 +867,31 @@ Now you can use the string pb on the command line in lieu of the whole URL. For * [new branch] master -> pb/master * [new branch] ticgit -> pb/ticgit -Paul’s master branch is accessible locally as `pb/master` — you can merge it into one of your branches, or you can check out a local branch at that point if you want to inspect it. +Paulova hlavní větev (master branch) je teď lokálně dostupná jako `pb/master`. Můžete ji začlenit (merge) do některé ze svých větví, nebo ji můžete zpřístupnit jako lokální větev (check out), jestliže si ji chcete prohlédnout. -### Fetching and Pulling from Your Remotes ### +### Vyzvedávání a stahování ze vzdálených repozitářů ### -As you just saw, to get data from your remote projects, you can run +Jak jste právě viděli, data ze vzdálených projektů můžete získat pomocí příkazu: - $ git fetch [remote-name] + $ git fetch [název vzdáleného repozitáře] -The command goes out to that remote project and pulls down all the data from that remote project that you don’t have yet. After you do this, you should have references to all the branches from that remote, which you can merge in or inspect at any time. (We’ll go over what branches are and how to use them in much more detail in Chapter 3.) +Příkaz zamíří do vzdáleného projektu a stáhne z něj všechna data, která ještě nemáte u sebe. Poté byste měli mít k dispozici odkazy na všechny větve tohoto vzdáleného projektu. Od toho okamžiku je můžete kdykoli slučovat nebo prohlížet. (Podrobněji se budeme větvím a jejich použití věnovat v *kapitole 3*.) -If you cloned a repository, the command automatically adds that remote repository under the name origin. So, `git fetch origin` fetches any new work that has been pushed to that server since you cloned (or last fetched from) it. It’s important to note that the fetch command pulls the data to your local repository — it doesn’t automatically merge it with any of your work or modify what you’re currently working on. You have to merge it manually into your work when you’re ready. +Pokud jste naklonovali repozitář, příkaz automaticky přidá tento vzdálený repozitář pod názvem *origin*. Takže příkaz `git fetch origin` vyzvedne veškerou novou práci, která byla na uvedený server poslána (push) od okamžiku, kdy jste odtud klonovali (nebo kdy jste odtud naposledy vyzvedávali práci). Měli bychom zmínit, že příkaz `fetch` stáhne data do vašeho lokálního repozitáře. V žádném případě ale data automaticky nesloučí s vaší prací ani jinak nezmění nic z toho, na čem právě pracujete. Sloučení s vaší prací musíte udělat ručně, až to uznáte za vhodné. -If you have a branch set up to track a remote branch (see the next section and Chapter 3 for more information), you can use the `git pull` command to automatically fetch and then merge a remote branch into your current branch. This may be an easier or more comfortable workflow for you; and by default, the `git clone` command automatically sets up your local master branch to track the remote master branch on the server you cloned from (assuming the remote has a master branch). Running `git pull` generally fetches data from the server you originally cloned from and automatically tries to merge it into the code you’re currently working on. +Pokud máte větev nastavenou ke sledování vzdálené větve (více informací naleznete v následující části a v *kapitole 3*), můžete použít příkaz `git pull`, který automaticky vyzvedne (fetch) a poté začlení (merge) vzdálenou větev do vaší aktuální větve. Tento postup pro vás může být snazší a pohodlnější. Standardně přitom příkaz `git clone` automaticky nastaví vaši lokální hlavní větev, aby sledovala vzdálenou hlavní větev na serveru, z kterého jste klonovali (za předpokladu, že má vzdálený server hlavní větev). Příkaz `git pull` většinou vyzvedne data ze serveru, z něhož jste původně klonovali, a automaticky se pokusí začlenit je do kódu, na němž právě pracujete. -### Pushing to Your Remotes ### +### Odesílání do vzdálených repozitářů ### -When you have your project at a point that you want to share, you have to push it upstream. The command for this is simple: `git push [remote-name] [branch-name]`. If you want to push your master branch to your `origin` server (again, cloning generally sets up both of those names for you automatically), then you can run this to push your work back up to the server: +Pokud se váš projekt nachází ve stavu, kdy ho chcete sdílet s ostatními, můžete ho odeslat (push) na vzdálený server. Příkaz pro tuto akci je jednoduchý: `git push [název vzdáleného repozitáře] [název větve]`. Pokud chcete poslat svou hlavní větev na server `origin` (i tady platí, že proces klonování vám nastaví názvy `master` i `origin` automaticky), můžete k odeslání své práce na server použít tento příkaz: $ git push origin master -This command works only if you cloned from a server to which you have write access and if nobody has pushed in the meantime. If you and someone else clone at the same time and they push upstream and then you push upstream, your push will rightly be rejected. You’ll have to pull down their work first and incorporate it into yours before you’ll be allowed to push. See Chapter 3 for more detailed information on how to push to remote servers. +Tento příkaz bude funkční, pouze pokud jste klonovali ze serveru, k němuž máte oprávnění pro zápis, a pokud sem od vašeho klonování nikdo neposílal svou práci. Pokud spolu s vámi provádí současně klonování ještě někdo další a ten poté svou práci odešle na server, vaše později odesílaná práce bude oprávněně odmítnuta. Nejprve musíte stáhnout práci ostatních a začlenit ji do své, teprve potom vám server umožní odeslání. Více informací o odesílání na vzdálené servery najdete v *kapitole 3*. -### Inspecting a Remote ### +### Prohlížení vzdálených repozitářů ### -If you want to see more information about a particular remote, you can use the `git remote show [remote-name]` command. If you run this command with a particular shortname, such as `origin`, you get something like this: +Jestliže chcete získat více informací o konkrétním vzdáleném repozitáři, můžete použít příkaz `git remote show [název vzdáleného repozitáře]`. Pokud použijete tento příkaz v kombinaci s konkrétním zkráceným názvem (např. `origin`), bude výstup vypadat zhruba následovně: $ git remote show origin * remote origin @@ -859,9 +902,9 @@ If you want to see more information about a particular remote, you can use the ` master ticgit -It lists the URL for the remote repository as well as the tracking branch information. The command helpfully tells you that if you’re on the master branch and you run `git pull`, it will automatically merge in the master branch on the remote after it fetches all the remote references. It also lists all the remote references it has pulled down. +Bude obsahovat adresu URL vzdáleného repozitáře a informace ke sledování větví. Příkaz vám mimo jiné sděluje, že pokud se nacházíte na hlavní větvi (branch `master`) a spustíte příkaz `git pull`, pak se po vyzvednutí všech vzdálených referencí (fetch) práce z hlavní větve na vzdáleném serveru automaticky začlení (merge). Součástí výpisu jsou také všechny vzdálené reference, které příkaz stáhl. -That is a simple example you’re likely to encounter. When you’re using Git more heavily, however, you may see much more information from `git remote show`: +S uvedeným jednoduchým případem se pravděpodobně setkáte. Pokud však Git používáte na intenzivněji, může vám příkaz `git remote show` zobrazit mnohem více informací: $ git remote show origin * remote origin @@ -885,40 +928,40 @@ That is a simple example you’re likely to encounter. When you’re using Git m Local branch pushed with 'git push' master:master -This command shows which branch is automatically pushed when you run `git push` on certain branches. It also shows you which remote branches on the server you don’t yet have, which remote branches you have that have been removed from the server, and multiple branches that are automatically merged when you run `git pull`. +Tento příkaz ukazuje, která větev bude automaticky odeslána, pokud spustíte příkaz `git push` na určitých větvích. Příkaz vám také oznámí, které vzdálené větve na serveru ještě nemáte, které vzdálené větve máte, ale ze serveru už byly odstraněny, a několik větví, které budou automaticky sloučeny, jestliže spustíte příkaz `git pull`. -### Removing and Renaming Remotes ### +### Odstraňování a přejmenovávání vzdálených repozitářů ### -If you want to rename a reference, in newer versions of Git you can run `git remote rename` to change a remote’s shortname. For instance, if you want to rename `pb` to `paul`, you can do so with `git remote rename`: +Chcete-li změnit zkrácené jméno vzdáleného repozitáře, můžete v novějších verzích systému Git spustit příkaz `git remote rename`. Pokud například chcete přejmenovat repozitář z `pb` na `paul`, můžete tak učinit příkazem `git remote rename`: $ git remote rename pb paul $ git remote origin paul -It’s worth mentioning that this changes your remote branch names, too. What used to be referenced at `pb/master` is now at `paul/master`. +Za zmínku stojí, že tímto příkazem změníte zároveň i názvy vzdálených větví. Z původní reference `pb/master` se tak nyní stává `paul/master`. -If you want to remove a reference for some reason — you’ve moved the server or are no longer using a particular mirror, or perhaps a contributor isn’t contributing anymore — you can use `git remote rm`: +Chcete-li, ať už z jakéhokoli důvodu, odstranit referenci (přesunuli jste například server nebo už nepoužíváte dané zrcadlo, nebo třeba přispěvatel přestal přispívat), můžete využít příkaz `git remote rm`: $ git remote rm paul $ git remote origin -## Tagging ## +## Značky ## -Like most VCSs, Git has the ability to tag specific points in history as being important. Generally, people use this functionality to mark release points (v1.0, and so on). In this section, you’ll learn how to list the available tags, how to create new tags, and what the different types of tags are. +Stejně jako většina systémů VCS nabízí i Git možnost označovat v historii určitá místa, jež považujete za důležitá. Tato funkce se nejčastěji používá k označení jednotlivých vydání (například `v1.0`). V této části vysvětlíme, jak pořídíte výpis všech dostupných značek, jak lze vytvářet značky nové a jaké typy značek se vám nabízejí. -### Listing Your Tags ### +### Výpis značek ### -Listing the available tags in Git is straightforward. Just type `git tag`: +Pořízení výpisu dostupných značek (tags) je v systému Git jednoduché. Stačí zadat příkaz `git tag`: $ git tag v0.1 v1.3 -This command lists the tags in alphabetical order; the order in which they appear has no real importance. +Tento příkaz vypíše značky v abecedním pořadí. Pořadí, v němž se značky vyskytují, není relevantní. -You can also search for tags with a particular pattern. The Git source repo, for instance, contains more than 240 tags. If you’re only interested in looking at the 1.4.2 series, you can run this: +Značky lze vyhledávat také pomocí konkrétní masky. Například zdrojový kód Git „repo“ obsahuje více než 240 značek. Pokud vás však zajímá pouze verze 1.4.2., můžete zadat: $ git tag -l 'v1.4.2.*' v1.4.2.1 @@ -926,13 +969,13 @@ You can also search for tags with a particular pattern. The Git source repo, for v1.4.2.3 v1.4.2.4 -### Creating Tags ### +### Vytváření značek ### -Git uses two main types of tags: lightweight and annotated. A lightweight tag is very much like a branch that doesn’t change — it’s just a pointer to a specific commit. Annotated tags, however, are stored as full objects in the Git database. They’re checksummed; contain the tagger name, e-mail, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG). It’s generally recommended that you create annotated tags so you can have all this information; but if you want a temporary tag or for some reason don’t want to keep the other information, lightweight tags are available too. +Git používá dva hlavní druhy značek: prosté (lightweight) a anotované (annotated). Prostá značka se velmi podobá větvi, která se nemění – je to pouze ukazatel na konkrétní revizi. Naproti tomu anotované značky jsou ukládány jako plné objekty v databázi Git. U anotovaných značek se provádí kontrolní součet. Obsahují jméno autora značky (tagger), e-mail a datum, nesou vlastní zprávu (tagging message) a mohou být podepsány (signed) a ověřeny (verified) v programu GNU Privacy Guard (GPG). Obecně se doporučuje používat v zájmu úplnosti informací spíše anotované značky. Pokud však vytváříte pouze dočasnou značku nebo z nějakého důvodu nechcete zadávat podrobnější informace, můžete využívat i prosté značky. -### Annotated Tags ### +### Anotované značky ### -Creating an annotated tag in Git is simple. The easiest way is to specify `-a` when you run the `tag` command: +Vytvoření anotované značky v systému Git je jednoduché. Nejjednodušším způsobem je zadat k příkazu `tag` parametr `-a`: $ git tag -a v1.4 -m 'my version 1.4' $ git tag @@ -940,9 +983,9 @@ Creating an annotated tag in Git is simple. The easiest way is to specify `-a` w v1.3 v1.4 -The `-m` specifies a tagging message, which is stored with the tag. If you don’t specify a message for an annotated tag, Git launches your editor so you can type it in. +Parametr `-m` udává zprávu značky, která bude uložena spolu se značkou. Pokud u anotované značky nezadáte žádnou zprávu, Git spustí textový editor, v němž zprávu zadáte. -You can see the tag data along with the commit that was tagged by using the `git show` command: +Informace značky se zobrazí spolu s revizí, kterou značka označuje, po zadání příkazu `git show`: $ git show v1.4 tag v1.4 @@ -950,6 +993,7 @@ You can see the tag data along with the commit that was tagged by using the `git Date: Mon Feb 9 14:45:11 2009 -0800 my version 1.4 + commit 15027957951b64cf874c3557a0f3547bd83b3ff6 Merge: 4a447f7... a6b4c97... Author: Scott Chacon @@ -957,18 +1001,18 @@ You can see the tag data along with the commit that was tagged by using the `git Merge branch 'experiment' -That shows the tagger information, the date the commit was tagged, and the annotation message before showing the commit information. +Příkaz zobrazí ještě před informacemi o revizi informace o autorovi značky, datu, kdy byla revize označena, a zprávu značky. -### Signed Tags ### +### Podepsané značky ### -You can also sign your tags with GPG, assuming you have a private key. All you have to do is use `-s` instead of `-a`: +Máte-li soukromý klíč, lze značky rovněž podepsat v programu GPG. Jediné, co pro to musíte udělat, je zadat místo parametru `-a` parametr `-s`: $ git tag -s v1.5 -m 'my signed 1.5 tag' You need a passphrase to unlock the secret key for user: "Scott Chacon " 1024-bit DSA key, ID F721C45A, created 2009-02-09 -If you run `git show` on that tag, you can see your GPG signature attached to it: +Pokud pro tuto značku spustíte příkaz `git show`, uvidíte k ní připojen svůj podpis GPG: $ git show v1.5 tag v1.5 @@ -990,11 +1034,11 @@ If you run `git show` on that tag, you can see your GPG signature attached to it Merge branch 'experiment' -A bit later, you’ll learn how to verify signed tags. +V dalších částech se naučíte, jak podepsané značky ověřovat. -### Lightweight Tags ### +### Prosté značky ### -Another way to tag commits is with a lightweight tag. This is basically the commit checksum stored in a file — no other information is kept. To create a lightweight tag, don’t supply the `-a`, `-s`, or `-m` option: +Další možností, jak označit revizi, je prostá značka. Prostá značka je v podstatě kontrolní součet revize uložený v souboru, žádné další informace neobsahuje. Chcete-li vytvořit prostou značku, nezadávejte ani jeden z parametrů `-a`, `-s` nebo `-m`: $ git tag v1.4-lw $ git tag @@ -1004,7 +1048,7 @@ Another way to tag commits is with a lightweight tag. This is basically the comm v1.4-lw v1.5 -This time, if you run `git show` on the tag, you don’t see the extra tag information. The command just shows the commit: +Pokud spustíte pro značku příkaz `git show` tentokrát, nezobrazí se k ní žádné další informace. Příkaz zobrazí pouze samotnou revizi: $ git show v1.4-lw commit 15027957951b64cf874c3557a0f3547bd83b3ff6 @@ -1014,9 +1058,9 @@ This time, if you run `git show` on the tag, you don’t see the extra tag infor Merge branch 'experiment' -### Verifying Tags ### +### Ověřování značek ### -To verify a signed tag, you use `git tag -v [tag-name]`. This command uses GPG to verify the signature. You need the signer’s public key in your keyring for this to work properly: +Chcete-li ověřit podepsanou značku, použijte příkaz `git tag -v [název značky]`. Tento příkaz využívá k ověření podpisu program GPG. Aby příkaz správně fungoval, musíte mít ve své klíčence veřejný klíč podepisujícího (signer). $ git tag -v v1.4.2.1 object 883653babd8ee7ea23e6a5c392bb739348b1eb61 @@ -1032,15 +1076,15 @@ To verify a signed tag, you use `git tag -v [tag-name]`. This command uses GPG t gpg: aka "[jpeg image of size 1513]" Primary key fingerprint: 3565 2A26 2040 E066 C9A7 4A7D C0C6 D9A4 F311 9B9A -If you don’t have the signer’s public key, you get something like this instead: +Pokud veřejný klíč podepisujícího nemáte, výstup bude vypadat následovně: gpg: Signature made Wed Sep 13 02:08:25 2006 PDT using DSA key ID F3119B9A gpg: Can't check signature: public key not found error: could not verify the tag 'v1.4.2.1' -### Tagging Later ### +### Dodatečné označení ### -You can also tag commits after you’ve moved past them. Suppose your commit history looks like this: +Revizi lze označit značkou i poté, co jste ji už opustili. Předpokládejme, že vaše historie revizí vypadá takto: $ git log --pretty=oneline 15027957951b64cf874c3557a0f3547bd83b3ff6 Merge branch 'experiment' @@ -1054,13 +1098,13 @@ You can also tag commits after you’ve moved past them. Suppose your commit his 964f16d36dfccde844893cac5b347e7b3d44abbc commit the todo 8a5cbc430f1a9c3d00faaeffd07798508422908a updated readme -Now, suppose you forgot to tag the project at v1.2, which was at the "updated rakefile" commit. You can add it after the fact. To tag that commit, you specify the commit checksum (or part of it) at the end of the command: +Nyní předpokládejme, že jste projektu zapomněli přidělit značku `v1.2`, která byla obsažena v revizi označené jako „updated rakefile“. Značku můžete přidat dodatečně. Pro označení revize značkou zadejte na konec příkazu kontrolní součet revize (nebo jeho část): - $ git tag -a v1.2 9fceb02 + $ git tag -a v1.2 -m 'version 1.2' 9fceb02 -You can see that you’ve tagged the commit: +Můžete se podívat, že jste revizi označil: - $ git tag + $ git tag v0.1 v1.2 v1.3 @@ -1081,9 +1125,9 @@ You can see that you’ve tagged the commit: updated rakefile ... -### Sharing Tags ### +### Sdílení značek ### -By default, the `git push` command doesn’t transfer tags to remote servers. You will have to explicitly push tags to a shared server after you have created them. This process is just like sharing remote branches – you can run `git push origin [tagname]`. +Příkaz `git push` nepřenáší značky na vzdálené servery automaticky. Pokud jste vytvořili značku, budete ji muset na sdílený server poslat explicitně. Tento proces je stejný jako sdílení vzdálených větví. Spusťte příkaz `git push origin [název značky]`. $ git push origin v1.5 Counting objects: 50, done. @@ -1093,7 +1137,7 @@ By default, the `git push` command doesn’t transfer tags to remote servers. Yo To git@github.com:schacon/simplegit.git * [new tag] v1.5 -> v1.5 -If you have a lot of tags that you want to push up at once, you can also use the `--tags` option to the `git push` command. This will transfer all of your tags to the remote server that are not already there. +Máte-li značek více a chcete je odeslat všechny najednou, můžete použít také parametr `--tags`, který se přidává k příkazu `git push`. Tento příkaz přenese na vzdálený server všechny vaše značky, které tam ještě nejsou. $ git push origin --tags Counting objects: 50, done. @@ -1107,62 +1151,62 @@ If you have a lot of tags that you want to push up at once, you can also use the * [new tag] v1.4-lw -> v1.4-lw * [new tag] v1.5 -> v1.5 -Now, when someone else clones or pulls from your repository, they will get all your tags as well. +Pokud nyní někdo bude klonovat nebo stahovat z vašeho repozitáře, stáhne rovněž všechny vaše značky. -## Tips and Tricks ## +## Tipy a triky ## -Before we finish this chapter on basic Git, a few little tips and tricks may make your Git experience a bit simpler, easier, or more familiar. Many people use Git without using any of these tips, and we won’t refer to them or assume you’ve used them later in the book; but you should probably know how to do them. +Než ukončíme tuto kapitolu věnovanou základům práce se systémem Git, přidáme ještě pár tipů a triků, které vám mohou usnadnit či zpříjemnit práci. Mnoho uživatelů pracuje se systémem Git, aniž by tyto triky znali a používali. V dalších částech knihy se už o nich nebudeme zmiňovat ani nebudeme předpokládat, že je používáte. Přesto pro vás mohou být užitečné. -### Auto-Completion ### +### Automatické dokončování ### -If you use the Bash shell, Git comes with a nice auto-completion script you can enable. Download the Git source code, and look in the `contrib/completion` directory; there should be a file called `git-completion.bash`. Copy this file to your home directory, and add this to your `.bashrc` file: +Jestliže používáte shell Bash, nabízí vám Git možnost zapnout si skript pro automatické dokončování. Stáhněte si jej ze zdrojových textů systému Git z https://github.com/git/git/blob/master/contrib/completion/git-completion.bash. Soubor nakopírujte tento do vašeho domovského adresáře a do souboru `.bashrc` přidejte: - source ~/.git-completion.bash + source ~/git-completion.bash -If you want to set up Git to automatically have Bash shell completion for all users, copy this script to the `/opt/local/etc/bash_completion.d` directory on Mac systems or to the `/etc/bash_completion.d/` directory on Linux systems. This is a directory of scripts that Bash will automatically load to provide shell completions. +Chcete-li nastavit Git tak, aby měl automaticky dokončování pro shell Bash pro všechny uživatele, zkopírujte u systému Mac tento skript do adresáře `/opt/local/etc/bash_completion.d`, nebo u systémů Linux do adresáře `/etc/bash_completion.d/`. Jde o adresář skriptů, ze kterého si Bash automaticky načítá podporu pro shellové dokončování. -If you’re using Windows with Git Bash, which is the default when installing Git on Windows with msysGit, auto-completion should be preconfigured. +Pokud používáte Git Bash v systému Windows (Git Bash je pro instalaci msysGit pod Windows výchozím programem), mělo by být automatické dokončování přednastaveno. -Press the Tab key when you’re writing a Git command, and it should return a set of suggestions for you to pick from: +Při zadávání příkazu Git stiskněte klávesu Tab a měla by se objevit nabídka, z níž můžete zvolit příslušné dokončení: $ git co commit config -In this case, typing git co and then pressing the Tab key twice suggests commit and config. Adding `m` completes `git commit` automatically. - -This also works with options, which is probably more useful. For instance, if you’re running a `git log` command and can’t remember one of the options, you can start typing it and press Tab to see what matches: +Pokud zadáte – stejně jako v našem příkladu nahoře – `git co` a dvakrát stisknete klávesu Tab, systém vám navrhne „commit“ a „config“. Doplníte-li ještě `m`, skript automaticky dokončí příkaz na `git commit`. + +Automatické dokončování pravděpodobně více využijete v případě parametrů. Pokud například zadáváte příkaz `git log` a nemůžete si vzpomenout na některý z parametrů, můžete zadat jeho začátek, stisknout klávesu Tab a podívat se, co by to mohlo přesně být: $ git log --s --shortstat --since= --src-prefix= --stat --summary -That’s a pretty nice trick and may save you some time and documentation reading. +Jedná se o užitečný trik, který vám může ušetřit čas a pročítání dokumentace. -### Git Aliases ### +### Aliasy Git ### -Git doesn’t infer your command if you type it in partially. If you don’t want to type the entire text of each of the Git commands, you can easily set up an alias for each command using `git config`. Here are a couple of examples you may want to set up: +Jestliže zadáte systému Git neúplný příkaz, systém ho neakceptuje. Pokud nechcete zadávat celý text příkazů Git, můžete pomocí `git config` jednoduše nastavit pro každý příkaz tzv. alias. Uveďme několik příkladů možného nastavení: $ git config --global alias.co checkout $ git config --global alias.br branch $ git config --global alias.ci commit $ git config --global alias.st status -This means that, for example, instead of typing `git commit`, you just need to type `git ci`. As you go on using Git, you’ll probably use other commands frequently as well; in this case, don’t hesitate to create new aliases. +To znamená, že například místo kompletního příkazu `git commit` stačí zadat pouze zkrácené `git ci`. Budete-li pracovat v systému Git častěji, pravděpodobně budete hojně využívat i jiné příkazy. V takovém případě neváhejte a vytvořte si nové aliasy. -This technique can also be very useful in creating commands that you think should exist. For example, to correct the usability problem you encountered with unstaging a file, you can add your own unstage alias to Git: +Tato metoda může být velmi užitečná také k vytváření příkazů, které by podle vás měly existovat. Pokud jste například narazili na problém s používáním příkazu pro vrácení souboru z oblasti připravených změn, můžete ho vyřešit zadáním vlastního aliasu: $ git config --global alias.unstage 'reset HEAD --' -This makes the following two commands equivalent: +Po zadání takového příkazu budete mít k dispozici dva ekvivalentní příkazy: $ git unstage fileA $ git reset HEAD fileA -This seems a bit clearer. It’s also common to add a `last` command, like this: +Příkaz unstage je o něco jasnější. Běžně se také přidává příkaz `last`: $ git config --global alias.last 'log -1 HEAD' -This way, you can see the last commit easily: - +Tímto způsobem snadno zobrazíte poslední revizi: + $ git last commit 66938dae3329c7aebe598c2246a8e6af90d04646 Author: Josh Goebel @@ -1172,10 +1216,10 @@ This way, you can see the last commit easily: Signed-off-by: Scott Chacon -As you can tell, Git simply replaces the new command with whatever you alias it for. However, maybe you want to run an external command, rather than a Git subcommand. In that case, you start the command with a `!` character. This is useful if you write your own tools that work with a Git repository. We can demonstrate by aliasing `git visual` to run `gitk`: +Chtělo by se tedy říci, že Git jednoduše nahradí nový příkaz jakýmkoli aliasem, který vytvoříte. Může se však stát, že budete chtít spustit externí příkaz, a ne dílčí příkaz Git. V takovém případě zadejte na začátek příkazu znak `!`. Tuto možnost využijete, pokud si píšete své vlastní nástroje, které fungují s repozitářem Git. Jako příklad můžeme uvést situaci, kdy nahradíte příkaz `git visual` aliasem `gitk`: - $ git config --global alias.visual "!gitk" + $ git config --global alias.visual '!gitk' -## Summary ## +## Shrnutí ## -At this point, you can do all the basic local Git operations — creating or cloning a repository, making changes, staging and committing those changes, and viewing the history of all the changes the repository has been through. Next, we’ll cover Git’s killer feature: its branching model. +V tomto okamžiku už tedy umíte v systému Git provádět všechny základní lokální operace: vytvářet a klonovat repozitáře, provádět změny, připravit je k zapsání i zapisovat nebo třeba zobrazit historii všech změn, které prošly repozitářem. V další kapitole se podíváme na exkluzivní funkci systému Git – na model větvení. diff --git a/cs/03-git-branching/01-chapter3.markdown b/cs/03-git-branching/01-chapter3.markdown index 120dcf512..95f3afe98 100644 --- a/cs/03-git-branching/01-chapter3.markdown +++ b/cs/03-git-branching/01-chapter3.markdown @@ -1,418 +1,426 @@ -# Git Branching # +# Větve v systému Git # -Nearly every VCS has some form of branching support. Branching means you diverge from the main line of development and continue to do work without messing with that main line. In many VCS tools, this is a somewhat expensive process, often requiring you to create a new copy of your source code directory, which can take a long time for large projects. +Téměř každý systém pro správu verzí podporuje do určité míry větvení. Větvení znamená, že se můžete odloučit od hlavní linie vývoje a pokračovat v práci, aniž byste hlavní linii zanášeli smetím. V mnoha VCS nástrojích se může jednat o poněkud náročný proces, který často vyžaduje vytvoření nové kopie adresáře se zdrojovým kódem. To může – zvláště u velkých projektů – trvat poměrně dlouho. -Some people refer to the branching model in Git as its “killer feature,” and it certainly sets Git apart in the VCS community. Why is it so special? The way Git branches is incredibly lightweight, making branching operations nearly instantaneous and switching back and forth between branches generally just as fast. Unlike many other VCSs, Git encourages a workflow that branches and merges often, even multiple times in a day. Understanding and mastering this feature gives you a powerful and unique tool and can literally change the way that you develop. +Někteří lidé mluví o modelu větvení v systému Git jako o převratné vlastnosti. Není sporu o tom, že je Git díky tomu ve skupině systémů pro správu verzí poměrně jedinečný. V čem je jeho větvení tak zvláštní? Větvení je v systému Git neuvěřitelně snadné a operace s ním související probíhají téměř okamžitě. A stejně rychlé je i přepínání mezi jednotlivými větvemi. Na rozdíl od ostatních systémů pro správu verzí vybízí Git ke způsobu práce s bohatým větvením a častým slučováním, a to i několikrát za den. Pokud tuto funkci pochopíte a zvládnete její ovládání, dostanete do ruky výkonný a unikátní nástroj, který doslova změní váš pohled na vývoj. -## What a Branch Is ## +## Co je to větev ## -To really understand the way Git does branching, we need to take a step back and examine how Git stores its data. As you may remember from Chapter 1, Git doesn’t store data as a series of changesets or deltas, but instead as a series of snapshots. +Abychom skutečně pochopili, jak funguje v systému Git větvení, budeme se muset vrátit o krok zpět a podívat se, jak Git ukládá data. Jak si možná vzpomínáte z kapitoly 1, Git neukládá data jako sérii změn nebo rozdílů, ale jako sérii snímků. -When you commit in Git, Git stores a commit object that contains a pointer to the snapshot of the content you staged, the author and message metadata, and zero or more pointers to the commit or commits that were the direct parents of this commit: zero parents for the first commit, one parent for a normal commit, and multiple parents for a commit that results from a merge of two or more branches. +Zapíšete-li v systému Git revizi, Git uloží objekt revize, obsahující ukazatel na snímek obsahu, který jste určili k zapsání, metadata o autorovi a zprávě a nula nebo více ukazatelů na revizi nebo revize, které byly přímými rodiči této revize: žádné rodiče nemá první revize, jednoho rodiče má běžná revize a několik rodičů mají revize, které vznikly sloučením ze dvou či více větví. -To visualize this, let’s assume that you have a directory containing three files, and you stage them all and commit. Staging the files checksums each one (the SHA-1 hash we mentioned in Chapter 1), stores that version of the file in the Git repository (Git refers to them as blobs), and adds that checksum to the staging area: +Pro ilustraci předpokládejme, že máte adresář se třemi soubory, které připravíte k zapsání a následně zapíšete. Při přípravě souborů k zapsání je pro každý z nich vypočítán kontrolní součet (o otisku SHA-1 jsme se zmínili v kapitole 1), daná verze souborů se uloží v repozitáři Git (Git na ně odkazuje jako na bloby) a přidá jejich kontrolní součet do oblasti připravených změn: $ git add README test.rb LICENSE $ git commit -m 'initial commit of my project' -When you create the commit by running `git commit`, Git checksums each subdirectory (in this case, just the root project directory) and stores those tree objects in the Git repository. Git then creates a commit object that has the metadata and a pointer to the root project tree so it can re-create that snapshot when needed. +Vytvoříte-li revizi příkazem `git commit`, provede Git kontrolní součet každého adresáře (v tomto případě pouze kořenového adresáře projektu) a uloží tyto objekty stromu v repozitáři Git. Poté vytvoří objekt revize s metadaty a ukazatelem na kořenový strom projektu, aby mohl v případě potřeby tento snímek obnovit. -Your Git repository now contains five objects: one blob for the contents of each of your three files, one tree that lists the contents of the directory and specifies which file names are stored as which blobs, and one commit with the pointer to that root tree and all the commit metadata. Conceptually, the data in your Git repository looks something like Figure 3-1. +Váš gitovský repozitář nyní obsahuje pět objektů: jeden blob pro obsah každého ze tří vašich souborů, jeden strom, který zaznamenává obsah adresáře a udává, které názvy souborů jsou uloženy jako který blob, a jeden objekt revize s ukazatelem na kořenový strom a se všemi metadaty revize. Data ve vašem repozitáři Git se dají schematicky znázornit jako na obrázku 3-1. -Insert 18333fig0301.png -Figure 3-1. Single commit repository data +Insert 18333fig0301.png +Obrázek 3-1. Repozitář s daty jedné revize -If you make some changes and commit again, the next commit stores a pointer to the commit that came immediately before it. After two more commits, your history might look something like Figure 3-2. +Jestliže v souborech provedete změny a zapíšete je, další revize uloží ukazatel na revizi, jež jí bezprostředně předcházela. Po dalších dvou revizích bude vaše historie vypadat jako na obrázku 3-2. -Insert 18333fig0302.png -Figure 3-2. Git object data for multiple commits +Insert 18333fig0302.png +Obrázek 3-2. Data objektů Git pro několik revizí -A branch in Git is simply a lightweight movable pointer to one of these commits. The default branch name in Git is master. As you initially make commits, you’re given a master branch that points to the last commit you made. Every time you commit, it moves forward automatically. +Větev je v systému Git jen snadno přemístitelným ukazatelem na jednu z těchto revizí. Výchozím názvem větve v systému Git je `master` (hlavní větev). Při prvním zapisování revizí dostanete hlavní větev, jež bude ukazovat na poslední revizi, kterou jste zapsali. Pokaždé, když zapíšete novou revizi, větev se automaticky posune vpřed. -Insert 18333fig0303.png -Figure 3-3. Branch pointing into the commit data’s history +Insert 18333fig0303.png +Obrázek 3-3. Větev ukazující do historie dat revizí -What happens if you create a new branch? Well, doing so creates a new pointer for you to move around. Let’s say you create a new branch called testing. You do this with the `git branch` command: +Co se stane, když vytvoříte novou větev? Ano, nová větev znamená vytvoření nového ukazatele, s nímž můžete pohybovat. Řekněme, že vytvoříte novou větev a nazvete ji testing. Učiníte tak příkazem `git branch`: $ git branch testing -This creates a new pointer at the same commit you’re currently on (see Figure 3-4). +Tento příkaz vytvoří nový ukazatel na stejné revizi, na níž se právě nacházíte (viz obrázek 3-4). -Insert 18333fig0304.png -Figure 3-4. Multiple branches pointing into the commit’s data history +Insert 18333fig0304.png +Obrázek 3-4. Několik větví ukazujících do historie dat revizí -How does Git know what branch you’re currently on? It keeps a special pointer called HEAD. Note that this is a lot different than the concept of HEAD in other VCSs you may be used to, such as Subversion or CVS. In Git, this is a pointer to the local branch you’re currently on. In this case, you’re still on master. The git branch command only created a new branch — it didn’t switch to that branch (see Figure 3-5). +Jak Git pozná, na jaké větvi se právě nacházíte? Používá speciální ukazatel zvaný HEAD. Nenechte se mást, tento HEAD je velmi odlišný od všech koncepcí v ostatních systémech pro správu verzí, na něž jste možná zvyklí, jako Subversion nebo CVS. V systému Git se jedná o ukazatel na lokální větev, na níž se právě nacházíte. V našem případě jste však stále ještě na hlavní větvi. Příkazem `git branch` jste pouze vytvořili novou větev, zatím jste na ni nepřepnuli (viz obrázek 3-5). -Insert 18333fig0305.png -Figure 3-5. HEAD file pointing to the branch you’re on +Insert 18333fig0305.png +Obrázek 3-5. Soubor HEAD ukazující na větev, na níž se nacházíte. -To switch to an existing branch, you run the `git checkout` command. Let’s switch to the new testing branch: +Chcete-li přepnout na existující větev, spusťte příkaz `git checkout`. My můžeme přepnout na novou větev testing: $ git checkout testing -This moves HEAD to point to the testing branch (see Figure 3-6). +Tímto příkazem přesunete ukazatel HEAD tak, že ukazuje na větev testing (viz obrázek 3-6). Insert 18333fig0306.png -Figure 3-6. HEAD points to another branch when you switch branches. +Obrázek 3-6. Soubor HEAD ukazuje po přepnutí na jinou větev. -What is the significance of that? Well, let’s do another commit: +A jaký to má smysl? Dobře, proveďme další revizi: $ vim test.rb $ git commit -a -m 'made a change' -Figure 3-7 illustrates the result. +Obrázek 3-7 ukazuje výsledek. -Insert 18333fig0307.png -Figure 3-7. The branch that HEAD points to moves forward with each commit. +Insert 18333fig0307.png +Obrázek 3-7. Větev, na niž ukazuje soubor HEAD, se posouvá vpřed s každou revizí. -This is interesting, because now your testing branch has moved forward, but your master branch still points to the commit you were on when you ran `git checkout` to switch branches. Let’s switch back to the master branch: +Výsledek je zajímavý z toho důvodu, že se větev `testing` posunula vpřed, zatímco větev `master` stále ukazuje na revizi, na níž jste se nacházeli v okamžiku, kdy jste spustili příkaz `git checkout` a přepnuli tím větve. Přepněme zpět na větev `master`. $ git checkout master -Figure 3-8 shows the result. +Výsledek ukazuje obrázek 3-8. -Insert 18333fig0308.png -Figure 3-8. HEAD moves to another branch on a checkout. +Insert 18333fig0308.png +Obrázek 3-8. Ukazatel HEAD se po příkazu git checkout přesune na jinou větev. -That command did two things. It moved the HEAD pointer back to point to the master branch, and it reverted the files in your working directory back to the snapshot that master points to. This also means the changes you make from this point forward will diverge from an older version of the project. It essentially rewinds the work you’ve done in your testing branch temporarily so you can go in a different direction. +Tento příkaz provedl dvě věci. Přemístil ukazatel `HEAD` zpět, takže nyní ukazuje na větev `master`, a vrátil soubory ve vašem pracovním adresáři zpět ke snímku, na nějž větev `master` ukazuje. To také znamená, že změny, které od teď provedete, se odštěpí od starší verze projektu. V podstatě dočasně vrátíte všechny změny, které jste provedli ve větvi testing, a vydáte se jiným směrem. -Let’s make a few changes and commit again: +Proveďme pár změn a zapišme další revizi: $ vim test.rb $ git commit -a -m 'made other changes' -Now your project history has diverged (see Figure 3-9). You created and switched to a branch, did some work on it, and then switched back to your main branch and did other work. Both of those changes are isolated in separate branches: you can switch back and forth between the branches and merge them together when you’re ready. And you did all that with simple `branch` and `checkout` commands. +Nyní se historie vašeho projektu rozdělila (viz obrázek 3-9). Vytvořili jste novou větev, přepnuli jste na ni, provedli jste v ní změny a poté jste přepnuli zpět na hlavní větev, v níž jste rovněž provedli změny. Oboje tyto změny jsou oddělené na samostatných větvích. Můžete mezi nimi přepínat tam a zpět, a až uznáte za vhodné, můžete je sloučit. To vše jste provedli pomocí jednoduchých příkazů `branch` a `checkout`. -Insert 18333fig0309.png -Figure 3-9. The branch histories have diverged. +Insert 18333fig0309.png +Obrázek 3-9. Historie větví se rozdělila. -Because a branch in Git is in actuality a simple file that contains the 40 character SHA-1 checksum of the commit it points to, branches are cheap to create and destroy. Creating a new branch is as quick and simple as writing 41 bytes to a file (40 characters and a newline). +Vzhledem k tomu, že větev v systému Git tvoří jeden jednoduchý soubor, obsahující 40 znaků kontrolního součtu SHA-1 revize, na niž ukazuje, je snadné větve vytvářet i odstraňovat. Vytvořit novou větev je právě tak snadné a rychlé jako zapsat 41 bytů do souboru (40 znaků a jeden znak pro nový řádek). -This is in sharp contrast to the way most VCS tools branch, which involves copying all of the project’s files into a second directory. This can take several seconds or even minutes, depending on the size of the project, whereas in Git the process is always instantaneous. Also, because we’re recording the parents when we commit, finding a proper merge base for merging is automatically done for us and is generally very easy to do. These features help encourage developers to create and use branches often. +Tato metoda se výrazně liší od způsobu, jakým probíhá větvení v ostatních nástrojích VCS, kde je nutné zkopírovat všechny soubory projektu do jiného adresáře. To může zabrat – podle velikosti projektu – několik sekund i minut, zatímco v systému Git probíhá tento proces vždy okamžitě. A protože při zapisování revize zaznamenáváme její rodiče, probíhá vyhledávání příslušné základny pro sloučení automaticky a je většinou velmi snadné. Tyto funkce slouží k tomu, aby se vývojáři nebáli vytvářet a používat nové větve. -Let’s see why you should do so. +Podívejme se, proč byste to měli dělat také tak. -## Basic Branching and Merging ## +## Základy větvení a slučování ## -Let’s go through a simple example of branching and merging with a workflow that you might use in the real world. You’ll follow these steps: +Vytvořme si jednoduchý příklad větvení a slučování s pracovním postupem, který můžete využít i v reálném životě. Budete provádět tyto kroky: -1. Do work on a web site. -2. Create a branch for a new story you’re working on. -3. Do some work in that branch. +1. Pracujete na webových stránkách. +2. Vytvoříte větev pro novou část stránek, v níž budete pracovat. +3. Vytvoříte práci v této větvi. -At this stage, you’ll receive a call that another issue is critical and you need a hotfix. You’ll do the following: +V tomto okamžiku vám zavolají, že se vyskytla jiná kritická chyba, která vyžaduje rychlou opravu (hotfix). Uděláte následující: -1. Revert back to your production branch. -2. Create a branch to add the hotfix. -3. After it’s tested, merge the hotfix branch, and push to production. -4. Switch back to your original story and continue working. +1. Vrátíte se zpět na produkční větev. +2. Vytvoříte větev pro přidání hotfixu. +3. Po úspěšném otestování začleníte větev s hotfixem a odešlete ji do produkce. +4. Přepnete zpět na svou původní část a pokračujete v práci. -### Basic Branching ### +### Základní větvení ### -First, let’s say you’re working on your project and have a couple of commits already (see Figure 3-10). +Řekněme, že pracujete na projektu a už jste vytvořili několik revizí (viz obrázek 3-10). -Insert 18333fig0310.png -Figure 3-10. A short and simple commit history +Insert 18333fig0310.png +Obrázek 3-10. Krátká a jednoduchá historie revizí -You’ve decided that you’re going to work on issue #53 in whatever issue-tracking system your company uses. To be clear, Git isn’t tied into any particular issue-tracking system; but because issue #53 is a focused topic that you want to work on, you’ll create a new branch in which to work. To create a branch and switch to it at the same time, you can run the `git checkout` command with the `-b` switch: +Rozhodli jste se, že budete pracovat na chybě č. 53, ať už vaše společnost používá jakýkoli systém sledování chyb. Přesněji řečeno, Git není začleněn do žádného konkrétního systému sledování chyb, ale protože je chyba č. 53 významná a chcete na ní pracovat, vytvoříte si pro ni novou větev. Abyste vytvořili novou větev a rovnou na ni přepnuli, můžete spustit příkaz `git checkout` s přepínačem `-b`: $ git checkout -b iss53 - Switched to a new branch "iss53" + Switched to a new branch 'iss53' -This is shorthand for +Tímto způsobem jste spojili dva příkazy: $ git branch iss53 $ git checkout iss53 -Figure 3-11 illustrates the result. +Obrázek 3-11 ukazuje výsledek. -Insert 18333fig0311.png -Figure 3-11. Creating a new branch pointer +Insert 18333fig0311.png +Obrázek 3-11. Vytvoření nového ukazatele na větev -You work on your web site and do some commits. Doing so moves the `iss53` branch forward, because you have it checked out (that is, your HEAD is pointing to it; see Figure 3-12): +Pracujete na webových stránkách a zapíšete několik revizí. S každou novou revizí se větev `iss53` posune vpřed, protože jste provedli její checkout (to znamená, že na ni přepnuli ukazuje HEAD – viz obrázek 3-12): $ vim index.html - $ git commit -a -m 'added a new footer [issue 53]' + $ git commit -a -m 'add a new footer [issue 53]' -Insert 18333fig0312.png -Figure 3-12. The iss53 branch has moved forward with your work. +Insert 18333fig0312.png +Obrázek 3-12. Větev iss53 se s vaší prací posouvá vpřed. -Now you get the call that there is an issue with the web site, and you need to fix it immediately. With Git, you don’t have to deploy your fix along with the `iss53` changes you’ve made, and you don’t have to put a lot of effort into reverting those changes before you can work on applying your fix to what is in production. All you have to do is switch back to your master branch. +V tomto okamžiku vám zavolají, že se na webových stránkách vyskytl problém, který musíte okamžitě vyřešit. Jelikož pracujete v systému Git, nemusíte svou opravu vytvářet uprostřed změn, které jste provedli v části `iss53`, ani nemusíte dělat zbytečnou práci, abyste všechny tyto změny vrátili, než budete moci začít pracovat na opravě produkční verze stránek. Jediné, co teď musíte udělat, je přepnout zpět na hlavní větev. -However, before you do that, note that if your working directory or staging area has uncommitted changes that conflict with the branch you’re checking out, Git won’t let you switch branches. It’s best to have a clean working state when you switch branches. There are ways to get around this (namely, stashing and commit amending) that we’ll cover later. For now, you’ve committed all your changes, so you can switch back to your master branch: +Než tak učiníte, zkontrolujte, zda nemáte v pracovním adresáři nebo v oblasti připravených změn nezapsané změny, které kolidují s větví, jejíž checkout provádíte. V takovém případě by vám Git přepnutí větví nedovolil. Při přepínání větví je ideální, pokud máte čistý pracovní stav. Existují způsoby, jak to obejít (jmenovitě odložení (stashing) a doplnění revize (commit amending)), těm se však budeme věnovat až později. Pro tuto chvíli jste zapsali všechny provedené změny a můžete přepnout zpět na hlavní větev. $ git checkout master - Switched to branch "master" + Switched to branch 'master' -At this point, your project working directory is exactly the way it was before you started working on issue #53, and you can concentrate on your hotfix. This is an important point to remember: Git resets your working directory to look like the snapshot of the commit that the branch you check out points to. It adds, removes, and modifies files automatically to make sure your working copy is what the branch looked like on your last commit to it. +V tomto okamžiku vypadá váš pracovní adresář přesně tak, jak vypadal, než jste začali pracovat na chybě č. 53, a vy se nyní můžete soustředit na rychlou opravu. Tento důležitý bod si zapamatujte: Git vždy vrátí pracovní adresář do stejného stavu, jak vypadal snímek revize, na niž ukazuje větev, jejíž checkout nyní provádíte. Automaticky budou přidány, odstraněny a upraveny soubory tak, aby byla vaše pracovní kopie totožná se stavem větve v okamžiku, kdy jste na ni zapsali poslední revizi. -Next, you have a hotfix to make. Let’s create a hotfix branch on which to work until it’s completed (see Figure 3-13): +Nyní přichází na řadu hotfix. Vytvořme větev s hotfixem, v níž budeme pracovat, dokud nebude oprava hotová (viz obrázek 3-13): - $ git checkout -b 'hotfix' - Switched to a new branch "hotfix" + $ git checkout -b hotfix + Switched to a new branch 'hotfix' $ vim index.html - $ git commit -a -m 'fixed the broken email address' - [hotfix]: created 3a0874c: "fixed the broken email address" - 1 files changed, 0 insertions(+), 1 deletions(-) + $ git commit -a -m 'fix the broken email address' + [hotfix 3a0874c] fix the broken email address + 1 files changed, 1 deletion(-) -Insert 18333fig0313.png -Figure 3-13. hotfix branch based back at your master branch point +Insert 18333fig0313.png +Obrázek 3-13. Větev „hotfix“ začleněná zpět v místě hlavní větve -You can run your tests, make sure the hotfix is what you want, and merge it back into your master branch to deploy to production. You do this with the `git merge` command: +Můžete spustit testy, abyste se ujistili, že hotfix splňuje všechny požadavky, a pak můžete větev začlenit (merge) zpět do hlavní větve, aby byla připravena do produkce. Učiníte tak příkazem `git merge`: $ git checkout master $ git merge hotfix Updating f42c576..3a0874c - Fast forward - README | 1 - - 1 files changed, 0 insertions(+), 1 deletions(-) + Fast-forward + README | 1 - + 1 file changed, 1 deletion(-) -You’ll notice the phrase "Fast forward" in that merge. Because the commit pointed to by the branch you merged in was directly upstream of the commit you’re on, Git moves the pointer forward. To phrase that another way, when you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together — this is called a "fast forward". +Při sloučení jste si možná všimli spojení „Fast forward“ (rychle vpřed). Jelikož revize, na niž ukazovala větev, do níž jste začleňovali, byla v přímé linii s revizí, na níž jste se nacházeli, Git přesunul ukazatel vpřed. Jinými slovy: pokud se pokoušíte sloučit jednu revizi s revizí druhou, k níž lze dospět následováním historie první revize, Git proces zjednoduší a přesune ukazatel vpřed, protože neexistuje žádná rozdílná práce, kterou by bylo třeba sloučit. Tomuto postupu se říká „rychle vpřed“. -Your change is now in the snapshot of the commit pointed to by the `master` branch, and you can deploy your change (see Figure 3-14). +Vaše změna je nyní obsažena ve snímku revize, na niž ukazuje hlavní větev `master`, a vy můžete pokračovat v provádění změn (viz obrázek 3-14). -Insert 18333fig0314.png -Figure 3-14. Your master branch points to the same place as your hotfix branch after the merge. +Insert 18333fig0314.png +Obrázek 3-14. Hlavní větev ukazuje po sloučení na stejné místo jako větev „hotfix“. -After that your super-important fix is deployed, you’re ready to switch back to the work you were doing before you were interrupted. However, first you’ll delete the `hotfix` branch, because you no longer need it — the `master` branch points at the same place. You can delete it with the `-d` option to `git branch`: +Poté, co jste dokončili práci na bezodkladné opravě, můžete přepnout zpět na práci, jíž jste se věnovali před telefonátem. Nejprve však smažete větev `hotfix`, kterou teď už nebudete potřebovat – větev `master` ukazuje na totéž místo. Větev smažete přidáním parametru `-d` k příkazu `git branch`: $ git branch -d hotfix - Deleted branch hotfix (3a0874c). + Deleted branch hotfix (was 3a0874c). -Now you can switch back to your work-in-progress branch on issue #53 and continue working on it (see Figure 3-15): +Nyní můžete přepnout zpět na větev s rozdělanou prací a pokračovat na chybě č. 53 (viz obrázek 3-15): $ git checkout iss53 - Switched to branch "iss53" + Switched to branch 'iss53' $ vim index.html - $ git commit -a -m 'finished the new footer [issue 53]' - [iss53]: created ad82d7a: "finished the new footer [issue 53]" - 1 files changed, 1 insertions(+), 0 deletions(-) + $ git commit -a -m 'finish the new footer [issue 53]' + [iss53 ad82d7a] finish the new footer [issue 53] + 1 file changed, 1 insertion(+) -Insert 18333fig0315.png -Figure 3-15. Your iss53 branch can move forward independently. +Insert 18333fig0315.png +Obrázek 3-15. Větev iss53 může nezávisle postupovat vpřed. -It’s worth noting here that the work you did in your `hotfix` branch is not contained in the files in your `iss53` branch. If you need to pull it in, you can merge your `master` branch into your `iss53` branch by running `git merge master`, or you can wait to integrate those changes until you decide to pull the `iss53` branch back into `master` later. +Za zmínku stojí, že práce, kterou jste udělali ve větvi `hotfix`, není obsažena v souborech ve větvi `iss53`. Pokud potřebujete tyto změny do větve vtáhnout, můžete začlenit větev `master` do větve `iss53` provedením příkazu `git merge master`. Druhou možností je s integrací změn vyčkat a provést ji až ve chvíli, kdy budete chtít větev `iss53` vtáhnout zpět do větve `master`. -### Basic Merging ### +### Základní slučování ### -Suppose you’ve decided that your issue #53 work is complete and ready to be merged into your `master` branch. In order to do that, you’ll merge in your `iss53` branch, much like you merged in your `hotfix` branch earlier. All you have to do is check out the branch you wish to merge into and then run the `git merge` command: +Předpokládejme, že jste dokončili práci na chybě č. 53 a nyní byste ji rádi začlenili do větve `master`. Učiníte tak začleněním větve `iss53`, které bude probíhat velmi podobně jako předchozí začlenění větve `hotfix`. Jediné, co pro to musíte udělat, je přepnout na větev, do níž chcete tuto větev začlenit, a spustit příkaz `git merge`. $ git checkout master $ git merge iss53 - Merge made by recursive. - README | 1 + - 1 files changed, 1 insertions(+), 0 deletions(-) + Auto-merging README + Merge made by the 'recursive' strategy. + README | 1 + + 1 file changed, 1 insertion(+) -This looks a bit different than the `hotfix` merge you did earlier. In this case, your development history has diverged from some older point. Because the commit on the branch you’re on isn’t a direct ancestor of the branch you’re merging in, Git has to do some work. In this case, Git does a simple three-way merge, using the two snapshots pointed to by the branch tips and the common ancestor of the two. Figure 3-16 highlights the three snapshots that Git uses to do its merge in this case. +Toto už se trochu liší od začlenění větve `hotfix`, které jste prováděli před chvílí. V tomto případě se historie vývoje od určitého bodu v minulosti rozbíhala. Vzhledem k tomu, že revize na větvi, na níž se nacházíte, není přímým předkem větve, kterou chcete začlenit, Git bude muset podniknout určité kroky. Git v tomto případě provádí jednoduché třícestné sloučení: vychází ze dvou snímků, na které ukazují větve, a jejich společného předka. Obrázek 3-16 označuje ony tři snímky, které Git v tomto případě použije ke sloučení. -Insert 18333fig0316.png -Figure 3-16. Git automatically identifies the best common-ancestor merge base for branch merging. +Insert 18333fig0316.png +Obrázek 3-16. Git automaticky identifikuje nejvhodnějšího společného předka jako základnu pro sloučení větví. -Instead of just moving the branch pointer forward, Git creates a new snapshot that results from this three-way merge and automatically creates a new commit that points to it (see Figure 3-17). This is referred to as a merge commit and is special in that it has more than one parent. +Git tentokrát neposune ukazatel větve vpřed, ale vytvoří nový snímek jako výsledek tohoto třícestného sloučení a automaticky vytvoří novou revizi, která bude na snímek ukazovat (viz obrázek 3-17). Takové revizi se říká revize sloučením (merge commit) a její zvláštností je to, že má více než jednoho rodiče. -It’s worth pointing out that Git determines the best common ancestor to use for its merge base; this is different than CVS or Subversion (before version 1.5), where the developer doing the merge has to figure out the best merge base for themselves. This makes merging a heck of a lot easier in Git than in these other systems. +Na tomto místě bych chtěl zopakovat, že Git určuje nejvhodnějšího společného předka, který bude použit jako základna pro sloučení, automaticky. Liší se tím od systému CVS i Subversion (před verzí 1.5), kde musí vývojář při slučování najít nejvhodnější základnu pro sloučení sám. Slučování větví je proto v systému Git o poznání jednodušší než v ostatních systémech. -Insert 18333fig0317.png -Figure 3-17. Git automatically creates a new commit object that contains the merged work. +Insert 18333fig0317.png +Obrázek 3-17. Git automaticky vytvoří nový objekt revize, který obsahuje sloučenou práci. -Now that your work is merged in, you have no further need for the `iss53` branch. You can delete it and then manually close the ticket in your ticket-tracking system: +Nyní, když jste svou práci sloučili, větev `iss53` už nebudete potřebovat. Můžete ji smazat a poté ručně zavřít tiket v systému sledování tiketů: $ git branch -d iss53 -### Basic Merge Conflicts ### +### Základní konflikty při slučování ### -Occasionally, this process doesn’t go smoothly. If you changed the same part of the same file differently in the two branches you’re merging together, Git won’t be able to merge them cleanly. If your fix for issue #53 modified the same part of a file as the `hotfix`, you’ll get a merge conflict that looks something like this: +Může se stát, že sloučení neproběhne bez problémů. Pokud jste tutéž část jednoho souboru změnili odlišně ve dvou větvích, které chcete sloučit, Git je nebude umět sloučit čistě. Pokud se oprava chyby č. 53 týkala stejné části souboru jako větev `hotfix`, dojde ke konfliktu při slučování (merge conflict). Vypadá zhruba takto: $ git merge iss53 Auto-merging index.html CONFLICT (content): Merge conflict in index.html Automatic merge failed; fix conflicts and then commit the result. -Git hasn’t automatically created a new merge commit. It has paused the process while you resolve the conflict. If you want to see which files are unmerged at any point after a merge conflict, you can run `git status`: +Git nepřistoupil k automatickému vytvoření nové revize sloučením. Prozatím pozastavil celý proces do doby, než konflikt vyřešíte. Chcete-li kdykoli po konfliktu zjistit, které soubory zůstaly nesloučeny, spusťte příkaz `git status`: - [master*]$ git status - index.html: needs merge - # On branch master - # Changed but not updated: - # (use "git add ..." to update what will be committed) - # (use "git checkout -- ..." to discard changes in working directory) - # - # unmerged: index.html - # + $ git status + On branch master + You have unmerged paths. + (fix conflicts and run "git commit") + + Unmerged paths: + (use "git add ..." to mark resolution) + + both modified: index.html + + no changes added to commit (use "git add" and/or "git commit -a") -Anything that has merge conflicts and hasn’t been resolved is listed as unmerged. Git adds standard conflict-resolution markers to the files that have conflicts, so you can open them manually and resolve those conflicts. Your file contains a section that looks something like this: +Vše, co při sloučení kolidovalo a nebylo vyřešeno, je označeno jako „unmerged“ (nesloučeno). Git přidává ke kolidujícím souborům standardní značky pro označení konfliktů (conflict-resolution markers), takže soubor můžete ručně otevřít a konflikty vyřešit. Jedna část vašeho souboru bude vypadat zhruba takto: - <<<<<<< HEAD:index.html + <<<<<<< HEAD ======= - >>>>>>> iss53:index.html + >>>>>>> iss53 -This means the version in HEAD (your master branch, because that was what you had checked out when you ran your merge command) is the top part of that block (everything above the `=======`), while the version in your `iss53` branch looks like everything in the bottom part. In order to resolve the conflict, you have to either choose one side or the other or merge the contents yourself. For instance, you might resolve this conflict by replacing the entire block with this: +To znamená, že verze ve větvi s ukazatelem HEAD (vaše hlavní větev – v té jste se nacházeli při provádění příkazu merge) je uvedena v horní části tohoto bloku (všechno nad oddělovačem `=======`), verze obsažená ve větvi `iss53` je vše, co se nachází v dolní části. Chcete-li vzniklý konflikt vyřešit, musíte buď vybrat jednu z obou stran, nebo konflikt sloučit sami. Tento konflikt můžete vyřešit například nahrazením celého bloku tímto textem: -This resolution has a little of each section, and I’ve fully removed the `<<<<<<<`, `=======`, and `>>>>>>>` lines. After you’ve resolved each of these sections in each conflicted file, run `git add` on each file to mark it as resolved. Staging the file marks it as resolved in Git. -If you want to use a graphical tool to resolve these issues, you can run `git mergetool`, which fires up an appropriate visual merge tool and walks you through the conflicts: +Toto řešení obsahuje trochu z každé části a zcela jsem odstranil řádky `<<<<<<<`, `=======` a `>>>>>>>`. Poté, co vyřešíte všechny tyto části ve všech kolidujících souborech, spusťte pro každý soubor příkaz `git add`, jímž ho označíte jako vyřešený. Připravení souboru k zápisu ho v systému Git označí jako vyřešený. +Chcete-li k vyřešení problémů použít grafický nástroj, můžete spustit příkaz `git mergetool`, kterým otevřete příslušný vizuální nástroj pro slučování, a ten vás všemi konflikty provede: $ git mergetool - merge tool candidates: kdiff3 tkdiff xxdiff meld gvimdiff opendiff emerge vimdiff - Merging the files: index.html + + This message is displayed because 'merge.tool' is not configured. + See 'git mergetool --tool-help' or 'git help config' for more details. + 'git mergetool' will now attempt to use one of the following tools: + opendiff kdiff3 tkdiff xxdiff meld tortoisemerge gvimdiff diffuse diffmerge ecmerge p4merge araxis bc3 codecompare vimdiff emerge + Merging: + index.html Normal merge conflict for 'index.html': - {local}: modified - {remote}: modified + {local}: modified file + {remote}: modified file Hit return to start merge resolution tool (opendiff): -If you want to use a merge tool other than the default (Git chose `opendiff` for me in this case because I ran the command on a Mac), you can see all the supported tools listed at the top after “merge tool candidates”. Type the name of the tool you’d rather use. In Chapter 7, we’ll discuss how you can change this default value for your environment. +Chcete-li použít jiný než výchozí nástroj pro slučování (Git mi v tomto případě vybral `opendiff`, protože jsem příkaz zadal v systému Mac), všechny podporované nástroje jsou uvedeny na začátku výstupu v části „merge tool candidates“ (možné nástroje pro slučování). Zadejte název nástroje, který chcete použít. V kapitole 7 probereme, jak lze tuto výchozí hodnotu pro vaše prostředí změnit. -After you exit the merge tool, Git asks you if the merge was successful. If you tell the script that it was, it stages the file to mark it as resolved for you. +Až nástroj pro slučování zavřete, Git se vás zeptá, zda sloučení proběhlo úspěšně. Pokud skriptu oznámíte, že ano, připraví soubor k zapsání a tím ho označí jako vyřešený. -You can run `git status` again to verify that all conflicts have been resolved: +Ještě jednou můžete spustit příkaz `git status`, abyste si ověřili, že byly všechny konflikty vyřešeny: $ git status - # On branch master - # Changes to be committed: - # (use "git reset HEAD ..." to unstage) - # - # modified: index.html - # + On branch master + Changes to be committed: + (use "git reset HEAD ..." to unstage) + + modified: index.html + -If you’re happy with that, and you verify that everything that had conflicts has been staged, you can type `git commit` to finalize the merge commit. The commit message by default looks something like this: +Pokud jste s výsledkem spokojeni a ujistili jste se, že všechny kolidující soubory jsou připraveny k zapsání, můžete zadat příkaz `git commit` a dokončit revizi sloučením. Zpráva revize má v takovém případě přednastavenu tuto podobu: Merge branch 'iss53' Conflicts: index.html # - # It looks like you may be committing a MERGE. + # It looks like you may be committing a merge. # If this is not correct, please remove the file - # .git/MERGE_HEAD + # .git/MERGE_HEAD # and try again. # -You can modify that message with details about how you resolved the merge if you think it would be helpful to others looking at this merge in the future — why you did what you did, if it’s not obvious. +Pokud myslíte, že to může být pro spolupracovníky, kteří si jednou budou toto sloučení prohlížet, užitečné, můžete tuto zprávu upravit a doplnit o podrobnosti, jak jste sloučení vyřešili – pokud to není zřejmé, můžete okomentovat, co jste udělali a proč právě takto. -## Branch Management ## +## Správa větví ## -Now that you’ve created, merged, and deleted some branches, let’s look at some branch-management tools that will come in handy when you begin using branches all the time. +Nyní, když jste vytvořili, sloučili a odstranili své první větve, můžeme se podívat na pár nástrojů ke správě větví, které se vám budou hodit, až začnete s větvemi pracovat pravidelně. -The `git branch` command does more than just create and delete branches. If you run it with no arguments, you get a simple listing of your current branches: +Příkaz `git branch` umí víc, než jen vytvářet a mazat větve. Pokud ho spustíte bez dalších parametrů, získáte prostý výpis všech aktuálních větví: $ git branch iss53 * master testing -Notice the `*` character that prefixes the `master` branch: it indicates the branch that you currently have checked out. This means that if you commit at this point, the `master` branch will be moved forward with your new work. To see the last commit on each branch, you can run `git branch –v`: +Všimněte si znaku `*`, který předchází větvi `master`. Označuje větev, na níž se právě nacházíte. Pokud tedy nyní zapíšete revizi, vaše nová práce posune vpřed větev `master`. Chcete-li zobrazit poslední revizi na každé větvi, spusťte příkaz `git branch -v`: $ git branch -v iss53 93b412c fix javascript issue * master 7a98805 Merge branch 'iss53' testing 782fd34 add scott to the author list in the readmes -Another useful option to figure out what state your branches are in is to filter this list to branches that you have or have not yet merged into the branch you’re currently on. The useful `--merged` and `--no-merged` options have been available in Git since version 1.5.6 for this purpose. To see which branches are already merged into the branch you’re on, you can run `git branch –merged`: +Další užitečnou funkcí ke zjištění stavu vašich větví je filtrování tohoto seznamu podle větví, které byly/nebyly začleněny do větve, na níž se právě nacházíte. K tomuto účelu slouží v systému Git od verze 1.5.6 užitečné příkazy `--merged` a `--no-merged`. Chcete-li zjistit, které větve už byly začleněny do větve, na níž se nacházíte, spusťte příkaz `git branch --merged`: $ git branch --merged iss53 * master -Because you already merged in `iss53` earlier, you see it in your list. Branches on this list without the `*` in front of them are generally fine to delete with `git branch -d`; you’ve already incorporated their work into another branch, so you’re not going to lose anything. +Jelikož už jste větev `iss53` začlenili, nyní se zobrazí ve výpisu. Větve v tomto seznamu, které nejsou označeny `*`, lze většinou snadno smazat příkazem `git branch -d`. Jejich obsah už jste převzali do jiné větve, a tak jejich odstraněním nepřijdete o žádnou práci. -To see all the branches that contain work you haven’t yet merged in, you can run `git branch --no-merged`: +Chcete-li zobrazit větve, které obsahují dosud nezačleněnou práci, spusťte příkaz `git branch --no-merged`: $ git branch --no-merged testing -This shows your other branch. Because it contains work that isn’t merged in yet, trying to delete it with `git branch -d` will fail: +Nyní se zobrazila jiná větev. Jelikož obsahuje práci, která ještě nebyla začleněna, bude pokus o její smazání příkazem `git branch -d` neúspěšný: $ git branch -d testing - error: The branch 'testing' is not an ancestor of your current HEAD. + error: The branch 'testing' is not fully merged. If you are sure you want to delete it, run 'git branch -D testing'. -If you really do want to delete the branch and lose that work, you can force it with `-D`, as the helpful message points out. +Pokud chcete větev skutečně odstranit a zahodit práci, kterou obsahuje, můžete si to vynutit parametrem `-D` (jak napovídá užitečná zpráva pod řádkem s chybovým hlášením). -## Branching Workflows ## +## Možnosti při práci s větvemi ## -Now that you have the basics of branching and merging down, what can or should you do with them? In this section, we’ll cover some common workflows that this lightweight branching makes possible, so you can decide if you would like to incorporate it into your own development cycle. +Teď, když jste absolvovali základní seznámení s větvemi a jejich slučováním, nabízí se otázka, k čemu je to vlastně dobré. Proto se v této části podíváme na některé běžné pracovní postupy, které vám neobyčejně snadné větvení umožňuje, a můžete se zamyslet nad tím, zda větve při své vývojářské práci využijete, či nikoli. -### Long-Running Branches ### +### Dlouhé větve ### -Because Git uses a simple three-way merge, merging from one branch into another multiple times over a long period is generally easy to do. This means you can have several branches that are always open and that you use for different stages of your development cycle; you can merge regularly from some of them into others. +Vzhledem k tomu, že Git používá jednoduché třícestné slučování, je velmi snadné začleňovat jednu větev do druhé i několikrát v rámci dlouhého časového intervalu. Můžete tak mít několik větví, které jsou stále otevřené a které používáte pro různé fáze vývojového cyklu. Pravidelně můžete začleňovat práci z jedné větve do ostatních. -Many Git developers have a workflow that embraces this approach, such as having only code that is entirely stable in their `master` branch — possibly only code that has been or will be released. They have another parallel branch named develop or next that they work from or use to test stability — it isn’t necessarily always stable, but whenever it gets to a stable state, it can be merged into `master`. It’s used to pull in topic branches (short-lived branches, like your earlier `iss53` branch) when they’re ready, to make sure they pass all the tests and don’t introduce bugs. +Mnoho vývojářů systému Git používá pracovní postup, kdy mají ve větvi `master` pouze kód, který je stoprocentně stabilní — třeba jen kód, který byl nebo bude součástí vydání. Kromě ní mají další paralelní větev, pojmenovanou `develop` nebo `next`, v níž skutečně pracují nebo testují stabilitu kódu. Tato větev nemusí být nutně stabilní, ale jakmile se dostane do stabilního stavu, může být začleněna do větve `master`. Do ní se vtahují tématické větve (ty dočasné, jako byla vaše větev `iss53`) ve chvíli, kdy jsou připravené a je jisté, že projdou všemi testy a nezavlečou chyby. -In reality, we’re talking about pointers moving up the line of commits you’re making. The stable branches are farther down the line in your commit history, and the bleeding-edge branches are farther up the history (see Figure 3-18). +Ve skutečnosti hovoříme o ukazatelích pohybujících se vzhůru po linii revizí, které zapisujete. Stabilní větve leží v linii historie revizí níže a nové, neověřené větve se nacházejí nad nimi (viz obrázek 3-18). -Insert 18333fig0318.png -Figure 3-18. More stable branches are generally farther down the commit history. +Insert 18333fig0318.png +Obrázek 3-18. Stabilnější větve většinou leží v historii revizí níže. -It’s generally easier to think about them as work silos, where sets of commits graduate to a more stable silo when they’re fully tested (see Figure 3-19). +Snáze si je můžeme představit jako pracovní zásobníky, v nichž se sada revizí dostává do stabilnějšího zásobníku, když úspěšně absolvovala testování (viz obrázek 3-19). -Insert 18333fig0319.png -Figure 3-19. It may be helpful to think of your branches as silos. +Insert 18333fig0319.png +Obrázek 3-19. Větve si můžeme představit jako zásobníky -You can keep doing this for several levels of stability. Some larger projects also have a `proposed` or `pu` (proposed updates) branch that has integrated branches that may not be ready to go into the `next` or `master` branch. The idea is that your branches are at various levels of stability; when they reach a more stable level, they’re merged into the branch above them. -Again, having multiple long-running branches isn’t necessary, but it’s often helpful, especially when you’re dealing with very large or complex projects. +Tento postup lze použít hned pro několik úrovní stability. Některé větší projekty mají také větev `proposed` nebo `pu` (proposed updates, návrh aktualizací) s integrovanými větvemi, které nemusí být nutně způsobilé k začlenění do větve `next` nebo `master`. Idea je taková, že se větve nacházejí na různé úrovni stability. Jakmile dosáhnou stability o stupeň vyšší, jsou začleněny do větve nad nimi. +Není nutné používat při práci několik dlouhých větví, ale často to může být užitečné, zejména pokud pracujete ve velmi velkých nebo komplexních projektech. -### Topic Branches ### +### Tematické větve ### -Topic branches, however, are useful in projects of any size. A topic branch is a short-lived branch that you create and use for a single particular feature or related work. This is something you’ve likely never done with a VCS before because it’s generally too expensive to create and merge branches. But in Git it’s common to create, work on, merge, and delete branches several times a day. +Naproti tomu tematické větve se vám budou hodit v projektech jakékoli velikosti. Tematická větev (topic branch) je krátkodobá větev, kterou vytvoříte a používáte pro jediný konkrétní účel nebo práci. Je to záležitost, do které byste se v jiném systému pro správu verzí asi raději nikdy nepustili, protože vytvářet a slučovat větve je v něm opravdu složité. V systému Git naopak není výjimkou vytvářet, používat, slučovat a mazat větve i několikrát denně. -You saw this in the last section with the `iss53` and `hotfix` branches you created. You did a few commits on them and deleted them directly after merging them into your main branch. This technique allows you to context-switch quickly and completely — because your work is separated into silos where all the changes in that branch have to do with that topic, it’s easier to see what has happened during code review and such. You can keep the changes there for minutes, days, or months, and merge them in when they’re ready, regardless of the order in which they were created or worked on. +Viděli jste to v předchozí části, kdy jste si vytvořili větve `iss53` a `hotfix`. Provedli jste v nich pár revizí a smazali jste je hned po začlenění změn do hlavní větve. Tato technika umožňuje rychlé a snadné kontextové přepínání. Protože je vaše práce rozdělena do zásobníků, kde všechny změny v jedné větvi souvisí s jedním tématem, je při kontrole kódu snazší dohledat, čeho se změny týkaly apod. Změny tu můžete uchovávat několik minut, dní i měsíců a začlenit je přesně ve vhodnou chvíli. Na pořadí, v jakém byly větve vytvořeny nebo vyvíjeny, nezáleží. -Consider an example of doing some work (on `master`), branching off for an issue (`iss91`), working on it for a bit, branching off the second branch to try another way of handling the same thing (`iss91v2`), going back to your master branch and working there for a while, and then branching off there to do some work that you’re not sure is a good idea (`dumbidea` branch). Your commit history will look something like Figure 3-20. +Uvažujme nyní následující situaci: pracujete na projektu v hlavní větvi (`master`), odvětvíme se z ní k vyřešení jednoho problému (`iss91`), chvíli na něm pracujete, ale vytvoříte ještě další větev, abyste zkusili jiné řešení stejné chyby (`iss91v2`). Pak se vrátíte zpět do hlavní větve, kde pokračujete v práci, a pak dostanete nápad, který by se možná mohl osvědčit, a tak pro něj vytvoříte další větev (`dumbidea`). Historie revizí bude vypadat zhruba jako na obrázku 3-20. -Insert 18333fig0320.png -Figure 3-20. Your commit history with multiple topic branches +Insert 18333fig0320.png +Obrázek 3-20. Historie revizí s několika tematickými větvemi -Now, let’s say you decide you like the second solution to your issue best (`iss91v2`); and you showed the `dumbidea` branch to your coworkers, and it turns out to be genius. You can throw away the original `iss91` branch (losing commits C5 and C6) and merge in the other two. Your history then looks like Figure 3-21. +Řekněme, že se nyní rozhodnete, že druhé řešení vašeho problému bude vhodnější (`iss91v2`). Dále jste také ukázali svůj nápad ve větvi `dumbidea` kolegům a ti ho považují za geniální. Původní větev `iss91` tak nyní můžete zahodit (s ní i revize C5 a C6) a začlenit zbylé dvě větve. Vaši historii v tomto stavu znázorňuje obrázek 3-21. -Insert 18333fig0321.png -Figure 3-21. Your history after merging in dumbidea and iss91v2 +Insert 18333fig0321.png +Obrázek 3-21. Vaše historie po začlenění větví „dumbidea“ a „iss91v2“ -It’s important to remember when you’re doing all this that these branches are completely local. When you’re branching and merging, everything is being done only in your Git repository — no server communication is happening. +Při tom všem, co nyní děláte, je důležité mít na paměti, že všechny tyto větve jsou čistě lokální. Veškeré větvení a slučování se odehrává pouze v repozitáři Git, neprobíhá žádná komunikace se serverem. -## Remote Branches ## +## Vzdálené větve ## -Remote branches are references to the state of branches on your remote repositories. They’re local branches that you can’t move; they’re moved automatically whenever you do any network communication. Remote branches act as bookmarks to remind you where the branches on your remote repositories were the last time you connected to them. +Vzdálené větve jsou reference (tj. odkazy) na stav větví ve vašich vzdálených repozitářích. Jsou to lokální větve, které nemůžete přesouvat. Přesouvají se automaticky při síťové komunikaci. Vzdálené větve slouží jako záložky, které vám připomínají, kde byly větve ve vzdálených repozitářích, když jste se k nim naposledy připojili. -They take the form `(remote)/(branch)`. For instance, if you wanted to see what the `master` branch on your `origin` remote looked like as of the last time you communicated with it, you would check the `origin/master` branch. If you were working on an issue with a partner and they pushed up an `iss53` branch, you might have your own local `iss53` branch; but the branch on the server would point to the commit at `origin/iss53`. +Vzdálené větve mají podobu `(vzdálený repozitář)/(větev)`. Pokud například chcete zjistit, jak vypadala větev `master` na vašem vzdáleném serveru `origin`, když jste s ní naposledy komunikovali, budete hledat větev `origin/master`. Pokud pracujete s kolegou na stejném problému a on odešle na server větev s názvem `iss53`, může se stát, že i vy máte jednu z lokálních větví pojmenovanou jako `iss53`. Větev na serveru však ukazuje na revizi označenou jako `origin/iss53`. -This may be a bit confusing, so let’s look at an example. Let’s say you have a Git server on your network at `git.ourcompany.com`. If you clone from this, Git automatically names it `origin` for you, pulls down all its data, creates a pointer to where its `master` branch is, and names it `origin/master` locally; and you can’t move it. Git also gives you your own `master` branch starting at the same place as origin’s `master` branch, so you have something to work from (see Figure 3-22). +Mohlo by to být trochu matoucí, takže si uveďme příklad. Řekněme, že máte v síti server Git označený `git.ourcompany.com`. Pokud provedete klonování z tohoto serveru, Git ho automaticky pojmenuje `origin`, stáhne z něj všechna data, vytvoří ukazatel, který bude označovat jeho větev `master`, a lokálně ji pojmenuje `origin/master`. Tuto větev nemůžete přesouvat. Git vám rovněž vytvoří vaši vlastní větev `master`, která bude začínat ve stejném místě jako větev `master` serveru `origin`. Máte tak definován výchozí bod pro svoji práci (viz obrázek 3-22). -Insert 18333fig0322.png -Figure 3-22. A Git clone gives you your own master branch and origin/master pointing to origin’s master branch. +Insert 18333fig0322.png +Obrázek 3-22. Příkaz git clone vám vytvoří vlastní hlavní větev a větev origin/master, ukazující na hlavní větev serveru origin. -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 (see Figure 3-23). +Pokud nyní budete pracovat na své lokální hlavní větvi a někdo z kolegů mezitím pošle svou práci na server `git.ourcompany.com` a aktualizuje jeho hlavní větev, budou se vaše historie vyvíjet odlišně. A dokud zůstanete od serveru origin odpojeni, váš ukazatel `origin/master` se nemůže přemístit (viz obrázek 3-23). -Insert 18333fig0323.png -Figure 3-23. Working locally and having someone push to your remote server makes each history move forward differently. +Insert 18333fig0323.png +Obrázek 3-23. Pokud pracujete lokálně a někdo jiný odešle svou práci na vzdálený server, obě historie se rozejdou. -To synchronize your work, you run a `git fetch origin` command. 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 (see Figure 3-24). +K synchronizaci své práce použijte příkaz `git fetch origin`. Tento příkaz zjistí, který server je `origin` (v našem případě je to `git.ourcompany.com`), vyzvedne z něj všechna data, která ještě nemáte, a aktualizuje vaši lokální databázi. Při tom přemístí ukazatel `origin/master` na novou, aktuálnější pozici (viz obrázek 3-24). -Insert 18333fig0324.png -Figure 3-24. The git fetch command updates your remote references. +Insert 18333fig0324.png +Obrázek 3-24. Příkaz `git fetch` aktualizuje vaše reference na vzdálený server. -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`. You can add it as a new remote reference to the project you’re currently working on by running the `git remote add` command as we covered in Chapter 2. Name this remote `teamone`, which will be your shortname for that whole URL (see Figure 3-25). +Abychom si mohli ukázat, jak se pracuje s několika vzdálenými servery a jak vypadají vzdálené větve takových vzdálených projektů, předpokládejme, že máte ještě další interní server Git, který při vývoji používá pouze jeden z vašich sprint teamů. Tento server se nachází na `git.team1.ourcompany.com`. Můžete ho přidat jako novou vzdálenou referenci k projektu, na němž právě pracujete – spusťte příkaz `git remote add` (viz kapitola 2). Pojmenujte tento vzdálený server jako `teamone`, což bude zkrácený název pro celou URL adresu (viz obrázek 3-25). -Insert 18333fig0325.png -Figure 3-25. Adding another server as a remote +Insert 18333fig0325.png +Obrázek 3-25. Přidání dalšího vzdáleného serveru. -Now, you can run `git fetch teamone` to fetch everything server has that you don’t have yet. Because that server is a subset of the data your `origin` server has right now, Git fetches no data but sets a remote branch called `teamone/master` to point to the commit that `teamone` has as its `master` branch (see Figure 3-26). +Nyní můžete spustit příkaz `git fetch teamone`, který ze vzdáleného serveru `teamone` vyzvedne vše, co ještě nemáte. Protože je tento server podmnožinou dat, která jsou právě na serveru `origin`, Git nevyzvedne žádná data, ale nastaví vzdálenou větev nazvanou `teamone/master` tak, aby ukazovala na revizi, kterou má server `teamone` nastavenou jako větev `master` (viz obrázek 3-26). -Insert 18333fig0326.png -Figure 3-26. You get a reference to teamone’s master branch position locally. +Insert 18333fig0326.png +Obrázek 3-26. Lokálně získáte referenci na pozici hlavní větve serveru teamone. -### Pushing ### +### Odesílání ### -When you want to share a branch with the world, you need to push it up to a remote that you have write access to. Your local branches aren’t automatically synchronized to the remotes you write to — you have to explicitly push the branches you want to share. That way, you can use private branches for work you don’t want to share, and push up only the topic branches you want to collaborate on. +Chcete-li svou větev sdílet s okolním světem, musíte ji odeslat na vzdálený server, k němuž máte oprávnění pro zápis. Vaše lokální větve nejsou automaticky synchronizovány se vzdálenými servery, na něž zapisujete – ty, které chcete sdílet, musíte explicitně odeslat. Tímto způsobem si můžete zachovat soukromé větve pro práci, kterou nehodláte sdílet, a odesílat pouze tematické větve, na nichž chcete spolupracovat. -If you have a branch named `serverfix` that you want to work on with others, you can push it up the same way you pushed your first branch. Run `git push (remote) (branch)`: +Máte-li větev s názvem `serverfix`, na níž chcete spolupracovat s ostatními, můžete ji odeslat stejným způsobem, jakým jste odesílali svou první větev. Spusťte příkaz `git push (server) (větev)`: $ git push origin serverfix Counting objects: 20, done. @@ -422,9 +430,9 @@ If you have a branch named `serverfix` that you want to work on with others, you To git@github.com:schacon/simplegit.git * [new branch] serverfix -> serverfix -This is a bit of a shortcut. Git automatically expands the `serverfix` branchname out to `refs/heads/serverfix:refs/heads/serverfix`, which means, “Take my serverfix local branch and push it to update the remote’s serverfix branch.” We’ll go over the `refs/heads/` part in detail in Chapter 9, but you can generally leave it off. You can also do `git push origin serverfix:serverfix`, which does the same thing — it says, “Take my serverfix and make it the remote’s serverfix.” You can use this format to push a local branch into a remote branch that is named differently. If you didn’t want it to be called `serverfix` on the remote, you could instead run `git push origin serverfix:awesomebranch` to push your local `serverfix` branch to the `awesomebranch` branch on the remote project. +Toto je zkrácená verze příkazu. Git automaticky rozšíří název větve `serverfix` na `refs/heads/serverfix:refs/heads/serverfix`, což znamená: „Vezmi mou lokální větev `serverfix` a odešli ji na vzdálený server, kde aktualizuje tamní větev `serverfix`.“ Části `refs/heads/` se budeme podrobněji věnovat v kapitole 9, pro většinu uživatelů však nebude zajímavá. Můžete rovněž zadat příkaz `git push origin serverfix:serverfix`, který provede totéž. Systému Git říká: „Vezmi mou větev `serverfix` a udělej z ní `serverfix` na vzdáleném serveru.“ Tento formát můžete použít k odeslání lokální větve do vzdálené větve, která se jmenuje jinak. Pokud jste nechtěli, aby se větev na vzdáleném serveru jmenovala `serverfix`, mohli jste zadat příkaz ve tvaru `git push origin serverfix:awesomebranch`. Vaše lokální větev `serverfix` by byla odeslána do větve `awesomebranch` ve vzdáleném projektu. -The next time one of your collaborators fetches from the server, they will get a reference to where the server’s version of `serverfix` is under the remote branch `origin/serverfix`: +Až bude příště některý z vašich spolupracovníků vyzvedávat data ze serveru, obdrží referenci o tom, kde se nachází serverová verze větve `serverfix` ve vzdálené větvi `origin/serverfix`: $ git fetch origin remote: Counting objects: 20, done. @@ -434,165 +442,165 @@ The next time one of your collaborators fetches from the server, they will get a From git@github.com:schacon/simplegit * [new branch] serverfix -> origin/serverfix -It’s important to note that when you do a fetch that brings down new remote branches, you don’t automatically have local, editable copies of them. In other words, in this case, you don’t have a new `serverfix` branch — you only have an `origin/serverfix` pointer that you can’t modify. +Tady je důležité upozornit, že pokud vyzvedáváte data a stáhnete s nimi i nové vzdálené větve, nemáte automaticky jejich lokální, editovatelné kopie. Jinak řečeno: v tomto případě nebudete mít novou větev `serverfix`, budete mít pouze ukazatel `origin/serverfix`, který nemůžete měnit. -To merge this work into your current working branch, you can run `git merge origin/serverfix`. If you want your own `serverfix` branch that you can work on, you can base it off your remote branch: +Chcete-li začlenit tato data do své aktuální pracovní větve, spusťte příkaz `git merge origin/serverfix`. Chcete-li mít vlastní větev `serverfix`, na níž budete pracovat, můžete ji ze vzdálené větve vyvázat: $ git checkout -b serverfix origin/serverfix - Branch serverfix set up to track remote branch refs/remotes/origin/serverfix. - Switched to a new branch "serverfix" + Branch serverfix set up to track remote branch serverfix from origin. + Switched to a new branch 'serverfix' -This gives you a local branch that you can work on that starts where `origin/serverfix` is. +Tímto způsobem získáte lokální větev, na níž můžete pracovat a která začíná na pozici `origin/serverfix`. -### Tracking Branches ### +### Sledující větve ### -Checking out a local branch from a remote branch automatically creates what is called a _tracking branch_. Tracking branches are local branches that have a direct relationship to a remote branch. If you’re on a tracking branch and type git push, Git automatically knows which server and branch to push to. Also, running `git pull` while on one of these branches fetches all the remote references and then automatically merges in the corresponding remote branch. +Checkoutem lokální větve ze vzdálené větve automaticky vytvoříte takzvanou *sledující větev* (angl. tracking branch). Sledující větve jsou lokální větve s přímým vztahem ke vzdálené větvi. Pokud se nacházíte na sledující větvi a zadáte příkaz `git push`, Git automaticky ví, na který server a do které větve má data odeslat. Také příkazem `git pull` zadaným na sledovací větvi vyzvednete všechny vzdálené reference a Git poté odpovídající vzdálenou větev automaticky začlení. -When you clone a repository, it generally automatically creates a `master` branch that tracks `origin/master`. That’s why `git push` and `git pull` work out of the box with no other arguments. However, you can set up other tracking branches if you wish — ones that don’t track branches on `origin` and don’t track the `master` branch. The simple case is the example you just saw, running `git checkout -b [branch] [remotename]/[branch]`. If you have Git version 1.6.2 or later, you can also use the `--track` shorthand: +Pokud klonujete repozitář, většinou se vytvoří větev `master`, která bude sledovat větev `origin/master`. To je také důvod, proč příkazy `git push` a `git pull` fungují samy od sebe i bez dalších parametrů. Pokud chcete, můžete nastavit i jiné sledující větve – takové, které nebudou sledovat větve na serveru `origin` a nebudou sledovat hlavní větev `master`. Jednoduchým případem je příklad, který jste právě viděli: spuštění příkazu `git checkout -b [větev] [vzdálený server]/[větev]`. Máte-li Git ve verzi 1.6.2 nebo novější, můžete použít také zkrácenou variantu `--track`: $ git checkout --track origin/serverfix - Branch serverfix set up to track remote branch refs/remotes/origin/serverfix. - Switched to a new branch "serverfix" + Branch serverfix set up to track remote branch serverfix from origin. + Switched to a new branch 'serverfix' -To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name: +Chcete-li nastavit lokální větev s jiným názvem, než má vzdálená větev, můžete jednoduše použít první variantu s odlišným názvem lokální větve: $ git checkout -b sf origin/serverfix - Branch sf set up to track remote branch refs/remotes/origin/serverfix. - Switched to a new branch "sf" + Branch sf set up to track remote branch serverfix from origin. + Switched to a new branch 'sf' -Now, your local branch sf will automatically push to and pull from origin/serverfix. +Vaše lokální větev `sf` bude nyní automaticky stahovat data ze vzdálené větve `origin/serverfix` a bude do ní i odesílat. -### Deleting Remote Branches ### +### Mazání vzdálených větví ### -Suppose you’re done with a remote branch — say, you and your collaborators are finished with a feature and have merged it into your remote’s `master` branch (or whatever branch your stable codeline is in). You can delete a remote branch using the rather obtuse syntax `git push [remotename] :[branch]`. If you want to delete your `serverfix` branch from the server, you run the following: +Předpokládejme, že už nepotřebujete jednu ze vzdálených větví. Spolu se svými spolupracovníky jste dokončili určitou funkci a začlenili jste ji do větve `master` na vzdáleném serveru (nebo do jakékoli jiné větve, kterou používáte pro stabilní kód). Vzdálenou větev nyní můžete smazat pomocí poněkud neohrabané syntaxe `git push [vzdálený server] :[větev]`. Chcete-li ze serveru odstranit větev `serverfix`, můžete to provést takto: $ git push origin :serverfix To git@github.com:schacon/simplegit.git - [deleted] serverfix -Boom. No more branch on your server. You may want to dog-ear this page, because you’ll need that command, and you’ll likely forget the syntax. A way to remember this command is by recalling the `git push [remotename] [localbranch]:[remotebranch]` syntax that we went over a bit earlier. If you leave off the `[localbranch]` portion, then you’re basically saying, “Take nothing on my side and make it be `[remotebranch]`.” +Šup! A větev je ze serveru pryč. Na této stránce si možná chcete ohnout rožek, protože tento příkaz budete určitě potřebovat, ale jeho syntaxi pravděpodobně zapomenete. Zapamatovat si jej ale můžete tak, že si vybavíte příkaz `git push [vzdálený server] [lokální větev]:[vzdálená větev]`, o kterém jsme se zmínili před chvílí. Pokud vynecháte složku `[lokální větev]`, pak v podstatě říkáte: „Neber na mé straně nic a toto nic teď bude `[vzdálená větev]`.“ -## Rebasing ## +## Přeskládání ## -In Git, there are two main ways to integrate changes from one branch into another: the `merge` and the `rebase`. In this section you’ll learn what rebasing is, how to do it, why it’s a pretty amazing tool, and in what cases you won’t want to use it. +V systému Git existují dvě základní možnosti, jak integrovat změny z jedné větve do druhé: sloučení (neboli začlenění) příkazem `merge` a přeskládání příkazem `rebase`. V této části se dozvíte, co to je přeskládání, jak ho provést, v čem spočívají výhody tohoto nástroje a v jakých případech ho rozhodně nepoužívat. -### The Basic Rebase ### +### Základní přeskládání ### -If you go back to an earlier example from the Merge section (see Figure 3-27), you can see that you diverged your work and made commits on two different branches. +Pokud se vrátíme k našemu dřívějšímu příkladu z části o slučování větví (viz obrázek 3-27), vidíme, že jsme svoji práci rozdělili a vytvářeli revize ve dvou různých větvích. -Insert 18333fig0327.png -Figure 3-27. Your initial diverged commit history +Insert 18333fig0327.png +Obrázek 3-27. Vaše původně rozdělená historie revizí -The easiest way to integrate the branches, as we’ve already covered, is the `merge` command. It performs a three-way merge between the two latest branch snapshots (C3 and C4) and the most recent common ancestor of the two (C2), creating a new snapshot (and commit), as shown in Figure 3-28. +Víme, že nejjednodušším způsobem, jak integrovat větve, je příkaz `merge`. Ten provede třícestné sloučení mezi dvěma posledními snímky (C3 a C4) a jejich nejmladším společným předkem (C2), přičemž vytvoří nový snímek (a novou revizi) – viz obrázek 3-28. -Insert 18333fig0328.png -Figure 3-28. Merging a branch to integrate the diverged work history +Insert 18333fig0328.png +Obrázek 3-28. Integrace rozdělené historie sloučením větví -However, there is another way: you can take the patch of the change that was introduced in C3 and reapply it on top of C4. In Git, this is called _rebasing_. With the `rebase` command, you can take all the changes that were committed on one branch and replay them on another one. +Existuje však ještě jiný způsob. Můžete vzít záplatu se změnou, kterou jste provedli revizí C3, a aplikovat ji na vrcholu revize C4. V systému Git se tato metoda nazývá *přeskládání* (rebasing). Příkazem `rebase` vezmete všechny změny, které byly zapsány na jedné větvi, a necháte je znovu provést na jiné větvi. -In this example, you’d run the following: +V našem případě tedy provedete následující: $ git checkout experiment $ git rebase master First, rewinding head to replay your work on top of it... Applying: added staged command -It works by going to the common ancestor of the two branches (the one you’re on and the one you’re rebasing onto), getting the diff introduced by each commit of the branch you’re on, saving those diffs to temporary files, resetting the current branch to the same commit as the branch you are rebasing onto, and finally applying each change in turn. Figure 3-29 illustrates this process. +Přeskládání funguje takto: systém najde společného předka obou větví (větve, na níž se nacházíte, a větve, na kterou přeskládáváte), provede příkaz diff pro všechny revize větve, na níž se nacházíte, uloží zjištěné rozdíly do dočasných souborů, vrátí aktuální větev na stejnou revizi jako větev, na kterou přeskládáváte, a nakonec po jedné aplikuje všechny změny. Tento proces je naznačen na obrázku 3-29. -Insert 18333fig0329.png -Figure 3-29. Rebasing the change introduced in C3 onto C4 +Insert 18333fig0329.png +Obrázek 3-29. Přeskládání změny provedené v revizi C3 na revizi C4 -At this point, you can go back to the master branch and do a fast-forward merge (see Figure 3-30). +Nyní můžete přejít zpět na hlavní větev a provést sloučení „rychle vpřed“ (viz obrázek 3-30). -Insert 18333fig0330.png -Figure 3-30. Fast-forwarding the master branch +Insert 18333fig0330.png +Obrázek 3-30. „Rychle vpřed“ po hlavní větvi -Now, the snapshot pointed to by C3 is exactly the same as the one that was pointed to by C5 in the merge example. There is no difference in the end product of the integration, but rebasing makes for a cleaner history. If you examine the log of a rebased branch, it looks like a linear history: it appears that all the work happened in series, even when it originally happened in parallel. +Snímek, na který nyní ukazuje revize C3', je zcela totožný se snímkem, na který v příkladu v části o slučování ukazovala C5. V koncových produktech integrace není žádný rozdíl, výsledkem přeskládání je však čistší historie. Pokud si prohlížíte log přeskládané větve, vypadá jako lineární historie – zdá se, jako by veškerá práce probíhala v jedné linii, ačkoli původně byla paralelní. -Often, you’ll do this to make sure your commits apply cleanly on a remote branch — perhaps in a project to which you’re trying to contribute but that you don’t maintain. In this case, you’d do your work in a branch and then rebase your work onto `origin/master` when you were ready to submit your patches to the main project. That way, the maintainer doesn’t have to do any integration work — just a fast-forward or a clean apply. +Tuto metodu budete často používat v situaci, kdy chcete mít jistotu, že byly vaše revize čistě aplikovány na vzdálenou větev – např. v projektu, do nějž chcete přidat příspěvek, který ale nespravujete. V takovém případě budete pracovat ve své větvi, a až budete mít připraveny záplaty k odeslání do hlavního projektu, přeskládáte svou práci na větev `origin/master`. Správce v tomto případě nemusí provádět žádnou integraci, provede pouze posun „rychle vpřed“ nebo čistou aplikaci. -Note that the snapshot pointed to by the final commit you end up with, whether it’s the last of the rebased commits for a rebase or the final merge commit after a merge, is the same snapshot — it’s only the history that is different. Rebasing replays changes from one line of work onto another in the order they were introduced, whereas merging takes the endpoints and merges them together. +Ještě jednou bychom chtěli upozornit, že snímek, na který ukazuje závěrečná revize – ať už se jedná o poslední z přeskládaných revizí po přeskládání, nebo poslední revizi sloučením jako výsledek začlenění – je vždy stejný. Jediné, co se liší, je historie. Přeskládání provede změny učiněné v jedné linii práce ještě jednou v jiné linii, a to v pořadí, v jakém byly provedeny. Sloučení naproti tomu vezme koncové body větví a sloučí je dohromady. -### More Interesting Rebases ### +### Zajímavější možnosti přeskládání ### -You can also have your rebase replay on something other than the rebase branch. Take a history like Figure 3-31, 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. +Opětovné provedení změn pomocí příkazu rebase můžete využít i jiným účelům než jen k přeskládání větve. Vezměme například historii na obrázku 3-31. Vytvořili jste novou tematickou větev (`server`), pomocí níž chcete do svého projektu přidat funkci na straně serveru, a zapsali jste revizi. Poté jste tuto větev opustili a začali pracovat na změnách na straně klienta (`client`). I tady jste zapsali několik revizí. Nakonec jste se vrátili na větev `server` a zapsali tu další revize. -Insert 18333fig0331.png -Figure 3-31. A history with a topic branch off another topic branch +Insert 18333fig0331.png +Obrázek 3-31. Historie s tematickou větví obsahující další tematickou větev. -Suppose you decide that you want to merge your client-side changes into your mainline for a release, but you want to hold off on the server-side changes until it’s tested further. You can take the changes on client that aren’t on server (C8 and C9) and replay them on your master branch by using the `--onto` option of `git rebase`: +Předpokládejme, že nyní chcete začlenit změny provedené na straně klienta do své hlavní linie k vydání, ale prozatím chcete počkat se změnami na straně serveru, dokud nebudou pečlivě otestovány. Můžete vzít změny na větvi client, které nejsou na větvi server (C8 a C9), a nechat je znovu provést na hlavní větvi. Použijte k tomu příkaz `git rebase` v kombinaci s parametrem `--onto`: $ git rebase --onto master server client -This basically says, “Check out the client branch, figure out the patches from the common ancestor of the `client` and `server` branches, and then replay them onto `master`.” It’s a bit complex; but the result, shown in Figure 3-32, is pretty cool. +Tím v podstatě říkáte: „Proveď checkout větve `client`, zjisti záplaty ze společného předka větví `client` a `server` a znovu je aplikuj na hlavní větev `master`.“ Postup je možná trochu složitý, ale výsledek, znázorněný na obrázku 3-32, stojí opravdu za to. -Insert 18333fig0332.png -Figure 3-32. Rebasing a topic branch off another topic branch +Insert 18333fig0332.png +Obrázek 3-32. Přeskládání tematické větve, která byla součástí jiné tematické větve 72. -Now you can fast-forward your master branch (see Figure 3-33): +Nyní můžete posunout hlavní větev „rychle vpřed“ (viz obrázek 3-33): $ git checkout master $ git merge client -Insert 18333fig0333.png -Figure 3-33. Fast-forwarding your master branch to include the client branch changes +Insert 18333fig0333.png +Obrázek 3-33. Posun hlavní větve rychle vpřed na konec změn přeskládaných z větve client -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 [basebranch] [topicbranch]` — which checks out the topic branch (in this case, `server`) for you and replays it onto the base branch (`master`): +Řekněme, že se později rozhodnete vtáhnout i větev server. Větev server můžete přeskládat na hlavní větev příkazem `git rebase [základna] [tematická větev]`. Příkaz provede checkout tematické větve (v tomto případě větve `server`) a přeskládá její změny na základnu (angl. base branch, v tomto případě `master`): $ git rebase master server -This replays your `server` work on top of your `master` work, as shown in Figure 3-34. +Příkaz provede změny obsažené ve větvi `server` ještě jednou na vrcholu větve `master`, jak je znázorněno na obrázku 3-34. -Insert 18333fig0334.png -Figure 3-34. Rebasing your server branch on top of your master branch +Insert 18333fig0334.png +Obrázek 3-34. Přeskládání větve server na vrcholu hlavní větve. -Then, you can fast-forward the base branch (`master`): +Poté se můžete přesunout „rychle vpřed“ po základně (větev `master`): $ git checkout master $ git merge server -You can remove the `client` and `server` branches because all the work is integrated and you don’t need them anymore, leaving your history for this entire process looking like Figure 3-35: +Poté můžete větev `client` i `server` smazat, protože všechna práce z nich je integrována a tyto větve už nebudete potřebovat. Vaše historie pak bude vypadat jako na obrázku 3-35: $ git branch -d client $ git branch -d server -Insert 18333fig0335.png -Figure 3-35. Final commit history +Insert 18333fig0335.png +Obrázek 3-35. Konečná historie revizí -### The Perils of Rebasing ### +### Rizika spojená s přeskládáním ### -Ahh, but the bliss of rebasing isn’t without its drawbacks, which can be summed up in a single line: +Přeskládání sice nabízí určité výhody, má však také svá úskalí. Ta se dají shrnout do jedné věty: -**Do not rebase commits that you have pushed to a public repository.** +**Neprovádějte přeskládání u revizí, které jste odeslali do veřejného repozitáře.** -If you follow that guideline, you’ll be fine. If you don’t, people will hate you, and you’ll be scorned by friends and family. +Budete-li se touto zásadou řídit, nemusíte se přeskládání obávat. V opačném případě vás čeká nenávist ostatních a rodina a přátelé vás zavrhnou. -When you rebase stuff, you’re abandoning existing commits and creating new ones that are similar but different. If you push commits somewhere and others pull them down and base work on them, and then you rewrite those commits with `git rebase` and push them up again, your collaborators will have to re-merge their work and things will get messy when you try to pull their work back into yours. +Při přeskládání dat zahodíte existující revize a vytvoříte nové, které jsou jim podobné, ale přesto jiné. Pokud odešlete svou práci, ostatní si ji stáhnou a založí na nich svou práci. A vy potom tyto revize přepíšete příkazem `git rebase` a znovu je odešlete, vaši spolupracovníci do ní budou muset znovu začlenit svou práci a ve všem nastane chaos, až se pokusíte natáhnout jejich práci zpět do své. -Let’s look at an example of how rebasing work that you’ve made public can cause problems. Suppose you clone from a central server and then do some work off that. Your commit history looks like Figure 3-36. +Podívejme se na malý příklad, jaké problémy může přeskládání již zveřejněných dat způsobit. Představme si situaci, kdy jste naklonovali repozitář z centrálního serveru a provedli jste v něm několik změn. Vaše historie revizí bude vypadat jako na obrázku 3-36. -Insert 18333fig0336.png -Figure 3-36. Clone a repository, and base some work on it. +Insert 18333fig0336.png +Obrázek 3-36. Naklonovali jste repozitář a provedli v něm změny. -Now, someone else does more work that includes a merge, and pushes that work to the central server. You fetch them and merge the new remote branch into your work, making your history look something like Figure 3-37. +Někdo jiný teď provede jiné úpravy, jejichž součástí bude i začlenění, a odešle svou práci na centrální server. Vy tyto změny vyzvednete a začleníte novou vzdálenou větev do své práce – vaše historie teď vypadá jako na obrázku 3-37. -Insert 18333fig0337.png -Figure 3-37. Fetch more commits, and merge them into your work. +Insert 18333fig0337.png +Obrázek 3-37. Vyzvedli jste další revize a začlenili je do své práce. -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. +Jenže osoba, která odeslala a začlenila své změny, se rozhodne vrátit a svou práci raději přeskládat. Provede příkaz `git push --force` a přepíše historii na serveru. Vy poté znovu vyzvednete data ze serveru a stáhnete nové revize. -Insert 18333fig0338.png -Figure 3-38. Someone pushes rebased commits, abandoning commits you’ve based your work on. +Insert 18333fig0338.png +Obrázek 3-38. Kdosi odeslal přeskládané revize a zahodil ty, na nichž jste založili svou práci. -At this point, you have to merge this work in again, even though you’ve already done so. Rebasing changes the SHA-1 hashes of these commits so to Git they look like new commits, when in fact you already have the C4 work in your history (see Figure 3-39). +V tuto chvíli vám nezbývá, než změny znovu začlenit do své práce, ačkoli už jste je jednou začlenili. Přeskládáním se změnily otisky SHA-1 těchto revizí, a Git je proto považuje za nové revize, přestože změny označené jako C4 už jsou ve skutečnosti ve vaší historii obsaženy (viz obrázek 3-39). -Insert 18333fig0339.png -Figure 3-39. You merge in the same work again into a new merge commit. +Insert 18333fig0339.png +Obrázek 3-39. Znovu jste začlenili stejnou práci do nové revize sloučením. -You have to merge that work in at some point so you can keep up with the other developer in the future. After you do that, your commit history will contain both the C4 and C4' commits, which have different SHA-1 hashes but introduce the same work and have the same commit message. If you run a `git log` when your history looks like this, you’ll see two commits that have the same author date and message, which will be confusing. Furthermore, if you push this history back up to the server, you’ll reintroduce all those rebased commits to the central server, which can further confuse people. +Vy musíte tyto změny ve vhodném okamžiku začlenit do své práce, abyste do budoucna neztratili kontakt s ostatními vývojáři. Vaše historie pak bude obsahovat revize C4 i C4’, které mají obě jiný otisk SHA-1, ale představují stejnou práci a nesou i stejnou zprávu k revizi. Pokud s takovouto historií spustíte příkaz `git log`, nastane zmatečná situace, kdy se zobrazí dvě revize se stejným datem autora i stejnou zprávou k revizi. Pokud pak tuto historii odešlete zpět na server, znovu provedete všechny tyto přeskládané revize na centrálním serveru, což bude zmatečné i pro vaše spolupracovníky. -If you treat rebasing as a way to clean up and work with commits before you push them, and if you only rebase commits that have never been available publicly, then you’ll be fine. If you rebase commits that have already been pushed publicly, and people may have based work on those commits, then you may be in for some frustrating trouble. +Budete-li používat přeskládání jako metodu vyčištění a práce s revizemi předtím, než je odešlete, a budete-li přeskládávat pouze revize, které dosud nikdy nebyly zveřejněny, nemusíte se žádných problémů obávat. Jestliže ale přeskládáte revize, které už byly zveřejněny a někdo na nich mohl založit svou práci, můžete si tím nepěkně zavařit. -## Summary ## +## Shrnutí ## -We’ve covered basic branching and merging in Git. You should feel comfortable creating and switching to new branches, switching between branches and merging local branches together. You should also be able to share your branches by pushing them to a shared server, working with others on shared branches and rebasing your branches before they are shared. +V této kapitole jsme se věnovali základům větvení a slučování. Neměli byste teď mít problém s vytvářením větví, přepínáním na nové i existující větve ani se slučováním lokálních větví. Měli byste také umět odeslat své větve ke sdílení na server, spolupracovat s ostatními na sdílených větvích a před odesláním větve přeskládat. diff --git a/cs/04-git-server/01-chapter4.markdown b/cs/04-git-server/01-chapter4.markdown index 7cb03e174..3dd7abd9b 100644 --- a/cs/04-git-server/01-chapter4.markdown +++ b/cs/04-git-server/01-chapter4.markdown @@ -1,89 +1,89 @@ -# Git on the Server # +# Git na serveru # -At this point, you should be able to do most of the day-to-day tasks for which you’ll be using Git. However, in order to do any collaboration in Git, you’ll need to have a remote Git repository. Although you can technically push changes to and pull changes from individuals’ repositories, doing so is discouraged because you can fairly easily confuse what they’re working on if you’re not careful. Furthermore, you want your collaborators to be able to access the repository even if your computer is offline — having a more reliable common repository is often useful. Therefore, the preferred method for collaborating with someone is to set up an intermediate repository that you both have access to, and push to and pull from that. We’ll refer to this repository as a "Git server"; but you’ll notice that it generally takes a tiny amount of resources to host a Git repository, so you’ll rarely need to use an entire server for it. +V této chvíli byste už měli zvládat většinu každodenních úkonů, pro něž se vyplatí Git používat. Abyste však mohli v systému Git spolupracovat s ostatními, budete potřebovat vzdálený repozitář Git. Technicky vzato sice můžete odesílat a stahovat změny z repozitářů jednotlivých spolupracovníků, tento postup ale nedoporučujeme, protože se může při troše neopatrnosti velmi snadno stát, že zapomenete, kdo na čem pracuje. Navíc chcete, aby měli vaši spolupracovníci do repozitáře přístup, i když je váš počítač vypnutý nebo odpojený – na společný repozitář bývá často lepší spolehnutí. Jako nejlepší metodu spolupráce s ostatními proto můžeme doporučit nastavení „neutrálního“ repozitáře, do nějž budete mít všichni přístup, budete do něj moci odesílat data a budete z něj moci stahovat. Tomuto repozitáři budeme říkat „gitový server“. Jak ale zjistíte, nebývá hostování gitového repozitáře nijak zvlášť náročné na zdroje, a tak nejspíš nebudete potřebovat celý server. -Running a Git server is simple. First, you choose which protocols you want your server to communicate with. The first section of this chapter will cover the available protocols and the pros and cons of each. The next sections will explain some typical setups using those protocols and how to get your server running with them. Last, we’ll go over a few hosted options, if you don’t mind hosting your code on someone else’s server and don’t want to go through the hassle of setting up and maintaining your own server. +Zprovoznění gitového serveru je jednoduché. Nejprve určíte, jakými protokoly má váš server komunikovat. První část této kapitoly se bude věnovat možným protokolům, jejich přednostem a nevýhodám. V dalších částech popíšeme některá typická nastavení pro použití těchto protokolů, a jak s nimi uvést server do provozu. Nakonec se podíváme na několik možností hostování pro případ, že nebudete mít chuť podstupovat martyrium s nastavováním a správou vlastního serveru a nevadí vám umístit svůj kód na cizí server. -If you have no interest in running your own server, you can skip to the last section of the chapter to see some options for setting up a hosted account and then move on to the next chapter, where we discuss the various ins and outs of working in a distributed source control environment. +Pokud víte, že nebudete chtít spravovat vlastní server, můžete přeskočit rovnou na poslední část této kapitoly a podívat se na možnosti nastavení hostovaného účtu. Pak přejděte na následující kapitolu, v níž se dočtete o detailech a záludnostech při práci v prostředí s distribuovanou správou zdrojového kódu. -A remote repository is generally a _bare repository_ — a Git repository that has no working directory. Because the repository is only used as a collaboration point, there is no reason to have a snapshot checked out on disk; it’s just the Git data. In the simplest terms, a bare repository is the contents of your project’s `.git` directory and nothing else. +Vzdálený repozitář je obvykle *holý repozitář* (bare repository), tj. gitový repozitář bez pracovního adresáře. Protože se repozitář používá pouze jako místo pro spolupráci, není žádný důvod, aby byl na disku načten konkrétní snímek. Jsou tu pouze uložena data systému Git. Jednoduše bychom mohli také říct, že holý repozitář je obsah adresáře `.git` vašeho projektu a nic víc. -## The Protocols ## +## Protokoly ## -Git can use four major network protocols to transfer data: Local, Secure Shell (SSH), Git, and HTTP. Here we’ll discuss what they are and in what basic circumstances you would want (or not want) to use them. +Git může k přenosu dat používat jeden ze čtyř hlavních síťových protokolů: Local, Secure Shell (SSH), Git nebo HTTP. V této části se podíváme na to, co jsou jednotlivé protokoly zač a za jakých okolností je (ne)vhodné je použít. -It’s important to note that with the exception of the HTTP protocols, all of these require Git to be installed and working on the server. +Neměli bychom zamlčet ani to, že s výjimkou protokolu HTTP všechny vyžadují, aby byl na serveru nainstalován a zprovozněn systém Git. -### Local Protocol ### +### Lokální protokol ### -The most basic is the _Local protocol_, in which the remote repository is in another directory on disk. This is often used if everyone on your team has access to a shared filesystem such as an 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. +Nejzákladnější variantou je *lokální protokol* (Local protocol), v němž je vzdálený repozitář uložen v jiném adresáři na disku. Často se využívá v případech, kdy mají všichni z vašeho týmu přístup k vašim sdíleným souborům, např. přes připojení systému NFS, nebo – v méně pravděpodobném případě – se všichni přihlašují na jednom počítači. Tato druhá varianta není právě ideální, protože všechny instance repozitáře s kódem jsou v takovém případě umístěny v jednom počítači, čímž se zvyšuje riziko nevratné ztráty dat. -If you have a shared mounted filesystem, then you can clone, push to, and pull from a local file-based repository. To clone a repository like this or to add one as a remote to an existing project, use the path to the repository as the URL. For example, to clone a local repository, you can run something like this: +Máte-li připojený sdílený systém souborů, můžete klonovat, odesílat a stahovat z lokálního souborového repozitáře (local file-based repository). Chcete-li takový repozitář naklonovat nebo přidat jako vzdálený repozitář do existujícího projektu, použijte jako URL cestu k repozitáři. K naklonování lokálního repozitáře můžete použít příkaz například v tomto tvaru: $ git clone /opt/git/project.git -Or you can do this: +Nebo můžete provést následující: $ git clone file:///opt/git/project.git -Git operates slightly differently if you explicitly specify `file://` at the beginning of the URL. If you just specify the path, Git tries to use hardlinks or directly copy the files it needs. If you specify `file://`, Git fires up the processes that it normally uses to transfer data over a network which is generally a lot less efficient method of transferring the data. The main reason to specify the `file://` prefix is if you want a clean copy of the repository with extraneous references or objects left out — generally after an import from another version-control system or something similar (see Chapter 9 for maintenance tasks). We’ll use the normal path here because doing so is almost always faster. +Pokud na začátek URL explicitně zadáte výraz `file://`, pracuje Git trochu jinak. Pokud pouze zadáte cestu a zdroj i cíl se nacházejí ve stejném systému souborů, pokusí se Git použít hardlinky na potřebné objekty. Pokud se nenacházejí ve stejném systému souborů, dojde k okopírování potřebných objektů pomocí standardních prostředků systému pro kopírování. Pokud zadáte výraz `file://`, Git spustí procesy, jež běžně používá k přenosu dat prostřednictvím sítě. Síť je většinou výrazně méně výkonnou metodou přenosu dat. Hlavním důvodem, proč zadat předponu `file://` je to, že tak získáte čistou kopii repozitáře bez nepotřebných referencí a objektů, například po importu z jiného verzovacího systému a podobně (úkony správy jsou popsány v kapitole 9). My budeme používat normální cestu, neboť tato metoda je téměř vždy rychlejší. -To add a local repository to an existing Git project, you can run something like this: +K přidání lokálního repozitáře do existujícího projektu Git můžete použít příkaz například v tomto tvaru: $ git remote add local_proj /opt/git/project.git -Then, you can push to and pull from that remote as though you were doing so over a network. +Poté můžete odesílat data a stahovat je z tohoto vzdáleného serveru, jako byste tak činili prostřednictvím sítě. -#### The Pros #### +#### Výhody #### -The pros of file-based repositories are that they’re simple and they use existing file permissions and network access. If you already have a shared filesystem to which your whole team has access, setting up a repository is very easy. You stick the bare repository copy somewhere everyone has shared access to and set the read/write permissions as you would for any other shared directory. We’ll discuss how to export a bare repository copy for this purpose in the next section, “Getting Git on a Server.” +Výhoda souborových repozitářů spočívá v tom, že jsou jednoduché a používají existující oprávnění k souborům a síťový přístup. Pokud už máte sdílený systém souborů, k němuž má přístup celý váš tým, je nastavení repozitáře velice jednoduché. Kopii holého repozitáře umístíte někam, kam mají všichni sdílený přístup, a nastavíte oprávnění ke čtení/zápisu stejně jako u jakéhokoli jiného sdíleného adresáře. O exportu kopie holého repozitáře pro tento účel se více dočtete v následující části „Jak umístit Git na server“. -This is also a nice option for quickly grabbing work from someone else’s working repository. If you and a co-worker are working on the same project and they want you to check something out, running a command like `git pull /home/john/project` is often easier than them pushing to a remote server and you pulling down. +Jedná se také o výbornou možnost, jak rychle získat práci z pracovního repozitáře někoho jiného. Pokud vy a váš kolega pracujete na společném projektu a vy potřebujete provést checkout kolegových dat, bývá například příkaz `git pull /home/john/project` jednodušší než odesílat data na vzdálený server a odsud je opět stahovat. -#### The Cons #### +#### Nevýhody #### -The cons of this method are that shared access is generally more difficult to set up and reach from multiple locations than basic network access. If you want to push from your laptop when you’re at home, you have to mount the remote disk, which can be difficult and slow compared to network-based access. +Nevýhodou této metody je, že nastavit a získat sdílený přístup z více umístění je většinou těžší než obyčejný síťový přístup. Budete-li chtít pracovat doma a odeslat data z notebooku, budete muset připojit vzdálený disk, což může být ve srovnání s přístupem prostřednictvím sítě složité a pomalé. -It’s also important to mention that this isn’t necessarily the fastest option if you’re using a shared mount of some kind. A local repository is fast only if you have fast access to the data. A repository on NFS is often slower than the repository over SSH on the same server, allowing Git to run off local disks on each system. +Zapomenout bychom neměli ani na to, že používáte-li sdílené připojení určitého druhu, nemusí být tato možnost vždy nutně nejrychlejší. Lokální repozitář je rychlý pouze v případě, že máte rychlý přístup k datům. Repozitář na NFS je často pomalejší než stejný repozitář nad SSH na tomtéž serveru, který ve všech systémech umožňuje spustit Git z lokálních disků. -### The SSH Protocol ### +### Protokol SSH ### -Probably the most common transport protocol for Git is SSH. This is because SSH access to servers is already set up in most places — and if it isn’t, it’s easy to do. SSH is also the only network-based protocol that you can easily read from and write to. The other two network protocols (HTTP and Git) are generally read-only, so even if you have them available for the unwashed masses, you still need SSH for your own write commands. SSH is also an authenticated network protocol; and because it’s ubiquitous, it’s generally easy to set up and use. +Patrně nejčastějším přenosovým protokolem pro systém Git je SSH. Je to z toho důvodu, že SSH přístup k serverům je na většině míst už nastaven, a pokud ne, není ho těžké nastavit. SSH je navíc jediným síťovým protokolem, z nějž lze snadno číst a do nějž lze snadno zapisovat. Oba zbývající síťové protokoly (HTTP i Git) jsou většinou určeny pouze ke čtení, a proto i když je dáváte k dispozici ostatním, pro sebe budete potřebovat SSH protokol pro příkazy zápisu. SSH je také síťovým protokolem s autentizací, a protože je hojně rozšířen, je jeho nastavení a používání většinou snadné. -To clone a Git repository over SSH, you can specify ssh:// URL like this: +Chcete-li naklonovat repozitář Git pomocí protokolu SSH, zadejte `ssh://` URL, například: - $ git clone ssh://user@server:project.git + $ git clone ssh://user@server/project.git + +Nebo můžete pro SSH protokol použít kratší zápis jako u scp: -Or you can not specify a protocol — Git assumes SSH if you aren’t explicit: - $ git clone user@server:project.git -You can also not specify a user, and Git assumes the user you’re currently logged in as. +Stejně tak nemusíte zadávat ani uživatele, Git automaticky použije uživatele, jehož účtem jste právě přihlášeni. -#### The Pros #### +#### Výhody #### -The pros of using SSH are many. First, you basically have to use it if you want authenticated write access to your repository over a network. Second, SSH is relatively easy to set up — SSH daemons are commonplace, many network admins have experience with them, and many OS distributions are set up with them or have tools to manage them. Next, access over SSH is secure — all data transfer is encrypted and authenticated. Last, like the Git and Local protocols, SSH is efficient, making the data as compact as possible before transferring it. +Používání protokolu SSH přináší mnoho výhod. Především byste ho měli používat vždy, když chcete v síti používat autentizovaný zápis do repozitáře. Zadruhé: protokol SSH se snadno nastavuje – SSH démoni jsou zcela běžní, správci sítě si s nimi většinou vědí rady a mnoho distribucí OS je má ve výchozí instalaci nebo poskytuje nástroje pro jejich správu. Z dalších výhod bychom měli zmínit také to, že přístup přes protokol SSH je bezpečný, veškerý přenos dat je šifrovaný a autentizovaný. A stejně jako protokoly Git a Local je i protokol SSH výkonný, protože data jsou před přenosem upravena do co nejkompaktnější podoby. -#### The Cons #### +#### Nevýhody #### -The negative aspect of SSH is that you can’t serve anonymous access of your repository over it. People must have access to your machine over SSH to access it, even in a read-only capacity, which doesn’t make SSH access conducive to open source projects. If you’re using it only within your corporate network, SSH may be the only protocol you need to deal with. If you want to allow anonymous read-only access to your projects, you’ll have to set up SSH for you to push over but something else for others to pull over. +Nevýhodou protokolu SSH je, že neumožňuje anonymní přístup do repozitáře. Chce-li někdo získat přístup do vašeho repozitáře, byť třeba jen ke čtení, musí mít přístup k vašemu počítači přes SSH. Proto se protokol SSH nehodí pro projekty s otevřeným zdrojovým kódem. Pokud repozitář používáte jen v rámci firemní sítě, bude pro vás protokol SSH zřejmě naprosto ideální. Pokud chcete povolit anonymní přístup pro čtení k vašim projektům, budete muset nastavit protokol SSH k odesílání svých dat, ale musíte přidat i jiný protokol, který budou ostatní používat pro stahování. -### The Git Protocol ### +### Protokol Git ### -Next is 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. In order for a repository to be served over the Git protocol, you must create the `git-export-daemon-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. You can enable push access; but given the lack of authentication, if you turn on push access, anyone on the internet who finds your project’s URL could push to your project. Suffice it to say that this is rare. +Dalším protokolem v pořadí je protokol Git. Je to speciální démon, který je distribuován spolu se systémem Git. Naslouchá na vyhrazeném portu (9418) a poskytuje podobnou službu jako protokol SSH, avšak bez jakékoliv autentizace. Chcete-li, aby byl repozitář zpřístupněn protokolem Git, musíte vytvořit soubor `git-daemon-export-ok`. Bez tohoto souboru nebude repozitář démonem zpřístupněn. Žádné jiné zabezpečení ale k dispozici není. Repozitář Git je buď dostupný pro všechny a všichni z něj mohou klonovat, nebo dostupný není. To znamená, že se přes tento protokol nedají odesílat žádné revize. Možnost odesílání lze zapnout, ale vzhledem k tomu, že protokol neumožňuje autentizaci, aktivované odesílání znamená, že kdokoli na internetu, kdo najde URL vašeho projektu, do něj bude moci odesílat data. Je jasné, že to většinou nechcete. -#### The Pros #### +#### Výhody #### -The Git protocol is the fastest transfer protocol available. If you’re serving a lot of traffic for a public project or serving a very large project that doesn’t require user authentication for read access, it’s likely that you’ll want to set up a Git daemon to serve your project. It uses the same data-transfer mechanism as the SSH protocol but without the encryption and authentication overhead. +Protokol Git je ze všech dostupných protokolů nejrychlejší. Potřebujete-li, aby protokol obsluhoval frekventovaný provoz u veřejného projektu nebo velmi velký projekt, u nějž není třeba ověřování identity uživatele ohledně oprávnění pro čtení, bude k obsluze nejvhodnější pravděpodobně právě démon Git. Používá stejný mechanismus přenosu dat jako protokol SSH, na rozdíl od něj ale není zpomalován šifrováním a ověřováním identity (autentizací). -#### The Cons #### +#### Nevýhody #### -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 access for the few developers who have push (write) access and have everyone else use `git://` for read-only access. -It’s also probably the most difficult protocol to set up. It must run its own daemon, which is custom — we’ll look at setting one up in the “Gitosis” section of this chapter — it requires `xinetd` 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. Behind big corporate firewalls, this obscure port is commonly blocked. +Nevýhodou protokolu Git je, že neprovádí autentizaci. Většinou není žádoucí, aby protokol Git tvořil jediný přístup k vašemu projektu. Protokol Git většinou využijete v kombinaci s přístupem přes SSH. Protokol SSH bude nastaven pro několik málo vývojářů s oprávněním k zápisu (odesílání dat) a všichni ostatní budou používat `git://` pro přístup pouze ke čtení. +Pravděpodobně se také jedná o protokol s nejobtížnějším nastavením. Vyžaduje spuštění vlastního démona – na jeho nastavení se podíváme v části „Gitosis“ této kapitoly – a dále konfiguraci `xinetd` nebo podobnou, což není zrovna procházka růžovou zahradou. Vyžaduje rovněž povolení přístupu k portu 9418 skrz firewall. Tento port nepatří mezi standardní porty, které by firemní firewally vždy povolovaly. Velkými podnikovými firewally je tento málo rozšířený port většinou blokován. -### The HTTP/S Protocol ### +### Protokol HTTP/S ### -Last we have the HTTP protocol. The beauty of the HTTP or HTTPS protocol is the simplicity of setting it up. Basically, all you have to do is put the bare Git repository under your HTTP document root and set up a specific `post-update` hook, and you’re done (See Chapter 7 for details on Git hooks). 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: +Na konec jsme si nechali protokol HTTP. Co je na protokolu HTTP nebo HTTPS sympatické, je jejich jednoduché nastavení. Jediné, co většinou stačí udělat, je umístit holý repozitář Git do kořenového adresáře HTTP a nastavit příslušný zásuvný modul `post-update` (zásuvné moduly Git viz kapitola 7). Tím je nastavení hotové. V tuto chvíli může každý, kdo má přístup na webový server, kam jste repozitář uložili, tento repozitář naklonovat. Chcete-li u svého repozitáře nastavit oprávnění pro čtení pomocí protokolu HTTP, proveďte následující: $ cd /var/www/htdocs/ $ git clone --bare /path/to/git_project gitproject.git @@ -91,107 +91,108 @@ Last we have the HTTP protocol. The beauty of the HTTP or HTTPS protocol is the $ mv hooks/post-update.sample hooks/post-update $ chmod a+x hooks/post-update -That’s all. The `post-update` hook that comes with Git by default runs the appropriate command (`git update-server-info`) to make HTTP fetching and cloning work properly. This command is run when you push to this repository over SSH; then, other people can clone via something like +A to je vše. Zásuvný modul `post-update`, který je standardně součástí systému Git, spustí příslušný příkaz (`git update-server-info`), který zajistí správné vyzvedávání a klonování dat přes protokol HTTP. Tento příkaz se spustí, když do tohoto repozitáře odesíláte data přes protokol SSH. Poté mohou ostatní klonovat třeba takto: $ git clone http://example.com/gitproject.git -In this particular case, we’re using the `/var/www/htdocs` path that is common for Apache setups, but you can use any static web server — just put the bare repository in its path. The Git data is served as basic static files (see Chapter 9 for details about exactly how it’s served). +V tomto konkrétním případě používáme cestu `/var/www/htdocs`, která je obvyklá u nastavení Apache, ale použít lze v podstatě jakýkoli statický webový server – stačí uložit holý repozitář do dané cesty. Data repozitáře Git jsou obsluhována jako obyčejné statické soubory (podrobnosti o přesném způsobu obsluhy naleznete v kapitole 9). -It’s possible to make Git push over HTTP as well, although that technique isn’t as widely used and requires you to set up complex WebDAV requirements. Because it’s rarely used, we won’t cover it in this book. If you’re interested in using the HTTP-push protocols, you can read about preparing a repository for this purpose at `http://www.kernel.org/pub/software/scm/git/docs/howto/setup-git-server-over-http.txt`. One nice thing about making Git push over HTTP is that you can use any WebDAV server, without specific Git features; so, you can use this functionality if your web-hosting provider supports WebDAV for writing updates to your web site. +Odesílat data do repozitáře Git je možné také přes protokol HTTP, avšak tento způsob není příliš rozšířený a vyžaduje nastavení komplexních požadavků protokolu WebDAV. Protože se tato možnost využívá zřídka, nebudeme se jí v této knize věnovat. Pokud vás zajímá používání protokolů HTTP k odesílání dat, více se o přípravě repozitáře k tomuto účelu dočtete na adrese: `http://www.kernel.org/pub/software/scm/git/docs/howto/setup-git-server-over-http.txt` (anglicky). Příjemným faktem na odesílání dat přes protokol HTTP je, že můžete použít jakýkoli server WebDAV i bez speciálních funkcí systému Git. Tuto možnost tak můžete využít, pokud váš poskytovatel webhostingu podporuje WebDAV pro zápis aktualizací na vaše webové stránky. -#### The Pros #### +#### Výhody #### -The upside of using the HTTP protocol is that it’s easy to set up. Running the handful of required commands gives you a simple way to give the world read access to your Git repository. It takes only a few minutes to do. The HTTP protocol also isn’t very resource intensive on your server. Because it generally uses a static HTTP server to serve all the data, a normal Apache server can serve thousands of files per second on average — it’s difficult to overload even a small server. +Pro používání protokolu HTTP mluví zejména jeho snadné nastavení. Vystačíte s několika málo příkazy, ale získáte jednoduchý způsob, jak nastavit oprávnění pro čtení repozitáře Git pro okolní svět. Celý postup nezabere víc než pár minut. Protokol HTTP navíc jen minimálně omezuje zdroje serveru. Vzhledem k tomu, že k obsluze všech dat používá většinou statický HTTP server, obslouží běžný server Apache průměrně několik tisíc souborů za sekundu. Ani malý server proto není snadné přetížit. -You can also serve your repositories read-only over HTTPS, which means you can encrypt the content transfer; or you can go so far as to make the clients use specific signed SSL certificates. Generally, if you’re going to these lengths, it’s easier to use SSH public keys; but it may be a better solution in your specific case to use signed SSL certificates or other HTTP-based authentication methods for read-only access over HTTPS. +Své repozitáře můžete zpřístupnit ke čtení prostřednictvím protokolu HTTPS, což znamená, že se přenášený obsah šifruje. Nebo můžete zajít ještě dál a vyžadovat, aby klienti používali konkrétní podepsané SSL certifikáty. Je pravda, že v takovém případě by už bylo jednodušší použít veřejné SSH klíče, ale ve vašem konkrétním případě může být použití podepsaných SSL certifikátů nebo jiné ověření identity na základě protokolu HTTP lepší metodou, jak zajistit přístup přes HTTPS pouze ke čtení. -Another nice thing is that HTTP is such a commonly used protocol that corporate firewalls are often set up to allow traffic through this port. +Z dalších výhod protokolu HTTP bychom mohli jmenovat i jeho značné rozšíření, díky čemuž jsou firemní firewally často nastaveny tak, že umožňují provoz přes standardní port protokolu HTTP. -#### The Cons #### +#### Nevýhody #### -The downside of serving your repository over HTTP is that it’s relatively inefficient for the client. It generally takes a lot longer to clone or fetch from the repository, and you often have a lot more network overhead and transfer volume over HTTP than with any of the other network protocols. Because it’s not as intelligent about transferring only the data you need — there is no dynamic work on the part of the server in these transactions — the HTTP protocol is often referred to as a _dumb_ protocol. For more information about the differences in efficiency between the HTTP protocol and the other protocols, see Chapter 9. +Nevýhodou obsluhy repozitáře přes protokol HTTP je poměrně nízká výkonnost pro klienta. Klonovat nebo vyzvedávat data z repozitáře trvá v případě protokolu HTTP obecně mnohem déle a vyžádá si většinou podstatně větší režii síťových operací a objem přenášených dat, než je tomu u ostatních síťových protokolů. Protože protokol není natolik inteligentní, aby přenášel pouze data, která potřebujete – v těchto transakcích se na straně serveru nesetkáte s dynamickou činností – je protokol HTTP často nazýván *dumb protocol* (hloupý protokol). Více informací o rozdílech ve výkonnosti mezi protokolem HTTP a ostatními protokoly najdete v kapitole 9. -## Getting Git on a Server ## +## Jak umístit Git na server ## -In order to initially set up any Git server, you have to export an existing repository into a new bare repository — a repository that doesn’t contain a working directory. This is generally straightforward to do. -In order to clone your repository to create a new bare repository, you run the clone command with the `--bare` option. By convention, bare repository directories end in `.git`, like so: +Pro úvodní nastavení serveru Git je třeba exportovat existující repozitář do nového, holého repozitáře (bare repository), tj. do repozitáře, který neobsahuje pracovní adresář. S tím obvykle nebývá problém. +Chcete-li naklonovat stávající repozitář, a vytvořit tak nový a holý, zadejte příkaz pro klonování s parametrem `--bare`. Je zvykem, že adresáře s holým repozitářem končí na `.git`, například: $ git clone --bare my_project my_project.git - Initialized empty Git repository in /opt/projects/my_project.git/ + Cloning into bare repository 'my_project.git'... + done. -The output for this command is a little confusing. Since `clone` is basically a `git init` then a `git fetch`, we see some output from the `git init` part, which creates an empty directory. The actual object transfer gives no output, but it does happen. You should now have a copy of the Git directory data in your `my_project.git` directory. +V adresáři `my_project.git` byste nyní měli mít kopii dat z adresáře Git. -This is roughly equivalent to something like +Je to přibližně stejné, jako byste zadali například: $ 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. +Bude tu sice pár menších rozdílů v konfiguračním souboru, ale pro náš účel můžeme příkazy považovat za ekvivalentní. Oba vezmou samotný repozitář Git (bez pracovního adresáře) a vytvoří pro něj samostatný adresář. -### Putting the Bare Repository on a Server ### +### Umístění holého repozitáře na 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. Let’s say you’ve set up a server called `git.example.com` that you have SSH access to, and you want to store all your Git repositories under the `/opt/git` directory. You can set up your new repository by copying your bare repository over: +Nyní, když máte vytvořenu holou kopii repozitáře, zbývá ji už jen umístit na server a nastavit protokoly. Řekněme, že jste nastavili server nazvaný `git.example.com`, k němuž máte SSH přístup, a všechny svoje repozitáře Git chcete uložit do adresáře `/opt/git`. Nový repozitář můžete nastavit zkopírováním holého repozitáře příkazem: $ scp -r my_project.git user@git.example.com:/opt/git -At this point, other users who have SSH access to the same server which has read-access to the `/opt/git` directory can clone your repository by running +V tomto okamžiku mohou všichni ostatní, kdo mají SSH přístup k tomuto serveru s oprávněním pro čtení k adresáři `/opt/git`, naklonovat váš repozitář příkazem: $ git clone user@git.example.com:/opt/git/my_project.git -If a user SSHs into a server and has write access to the `/opt/git/my_project.git` directory, they will also automatically have push access. Git will automatically add group write permissions to a repository properly if you run the `git init` command with the `--shared` option. +Pokud se uživatel dostane přes SSH na server a má oprávnění k zápisu do adresáře `/opt/git/my_project.git`, má automaticky také oprávnění k odesílání dat. Zadáte-li příkaz `git init` s parametrem `--shared`, Git automaticky nastaví příslušná oprávnění skupiny k zápisu. $ ssh user@git.example.com $ cd /opt/git/my_project.git $ git init --bare --shared -You see how easy it is to take a Git repository, create a bare version, and place it on a server to which you and your collaborators have SSH access. Now you’re ready to collaborate on the same project. +Vidíte, jak je jednoduché vzít repozitář Git, vytvořit jeho holou verzi a umístit ji na server, k níž máte vy i vaši spolupracovníci SSH přístup. Nic vám teď nebrání začít spolupracovat na projektu. -It’s important to note that this is literally all you need to do to run a useful Git server to which several people have access — just add SSH-able accounts on a server, and stick a bare repository somewhere that all those users have read and write access to. You’re ready to go — nothing else needed. +A to je skutečně vše, co je třeba ke spuštění serveru Git, k němuž bude mít přístup více lidí – na server stačí přidat SSH účty a umístit holý repozitář někam, kam budou mít všichni uživatelé oprávnění ke čtení i zápisu. Vše je připraveno, nic dalšího se od vás nevyžaduje. -In the next few sections, you’ll see how to expand to more sophisticated setups. This discussion will include not having to create user accounts for each user, adding public read access to repositories, setting up web UIs, using the Gitosis tool, and more. However, keep in mind that to collaborate with a couple of people on a private project, all you _need_ is an SSH server and a bare repository. +V dalších částech se podíváme na některé pokročilé možnosti nastavení. Dozvíte se v nich, jak se vyhnout nutnosti vytvářet uživatelské účty pro všechny uživatele, jak k repozitářům přiřadit veřejné oprávnění pro čtení, jak nastavit webová rozhraní nebo k čemu se používá nástroj Gitosis. To však nemění nic na tom, že ke spolupráci se skupinou lidí na soukromém projektu *vystačíte* s jedním SSH serverem a holým repozitářem. -### Small Setups ### +### Nastavení pro malou skupinu ### -If you’re a small outfit or are just trying out Git in your organization and have only a few developers, things can be simple for you. One of the most complicated aspects of setting up a Git server is user management. If you want some repositories to be read-only to certain users and read/write to others, access and permissions can be a bit difficult to arrange. +Pokud provádíte nastavení jen pro malý okruh lidí nebo jen zkoušíte Git ve své organizaci a nemáte mnoho vývojářů, mnoho věcí pro vás bude jednodušších. Jedním z nejsložitějších aspektů nastavení serveru Git je totiž správa uživatelů. Pokud chcete, aby byly určité repozitáře pro některé uživatele pouze ke čtení a pro jiné i k zápisu, může být nastavení přístupu a oprávnění poměrně náročné. -#### SSH Access #### +#### SSH přístup #### -If you already have a server to which all your developers have SSH access, it’s generally easiest to set up your first repository there, because you have to do almost no work (as we covered in the last section). If you want more complex access control type permissions on your repositories, you can handle them with the normal filesystem permissions of the operating system your server runs. +Jestliže už máte server, k němuž mají všichni vaši vývojáři SSH přístup, bude většinou nejjednodušší nastavit první repozitář tam, protože celé nastavení už tím máte v podstatě hotové (jak jsme ukázali v předchozí části). Pokud chcete pro své repozitáře nastavit komplexnější správu oprávnění, můžete je opatřit běžnými oprávněními k systému souborů, které vám nabízí operační systém daného serveru. -If you want to place your repositories on a server that doesn’t have accounts for everyone on your team whom you want to have write access, then you must set up SSH access for them. We assume that if you have a server with which to do this, you already have an SSH server installed, and that’s how you’re accessing the server. +Pokud chcete své repozitáře umístit na server, jenž nemá účty pro všechny členy vašeho týmu, kteří by měli mít oprávnění k zápisu, musíte pro ně nastavit SSH přístup. Předpokládáme, že pokud máte server, na němž to lze provést, máte už nainstalován server SSH a jeho prostřednictvím k serveru přistupujete. -There are a few ways you can give access to everyone on your team. The first is to set up accounts for everybody, which is straightforward but can be cumbersome. You may not want to run `adduser` and set temporary passwords for every user. +Existuje několik způsobů, jak umožnit přístup všem členům vašeho týmu. Prvním způsobem je nastavit účty pro všechny, což je sice přímočaré, ale může to být poněkud zdlouhavé. Možná nebudete mít chuť spouštět příkaz `adduser` (přidat uživatele) a nastavovat pro každého uživatele dočasná hesla. -A second method is to create a single 'git' user on the machine, ask every user who is to have write access to send you an SSH public key, and add that key to the `~/.ssh/authorized_keys` file of your new 'git' user. At that point, everyone will be able to access that machine via the 'git' user. This doesn’t affect the commit data in any way — the SSH user you connect as doesn’t affect the commits you’ve recorded. +Druhým způsobem je vytvořit na počítači jediného uživatele 'git', požádat všechny uživatele, kteří mají mít oprávnění k zápisu, aby vám poslali veřejný SSH klíč, a přidat tento klíč do souboru `~/.ssh/authorized_keys` vašeho nového uživatele 'git'. Nyní budou mít všichni přístup k tomuto počítači prostřednictvím uživatele 'git'. Tento postup nemá žádný vliv na data vašich revizí – SSH uživatel, jehož účtem se přihlašujete, neovlivní revize, které jste nahráli. -Another way to do it is to have your SSH server authenticate from an LDAP server or some other centralized authentication source that you may already have set up. As long as each user can get shell access on the machine, any SSH authentication mechanism you can think of should work. +Dalším možným způsobem je nechat ověřovat SSH přístupy LDAP serveru nebo jinému centralizovanému zdroji ověření, který už možná máte nastavený. Dokud má každý uživatel shellový přístup k počítači, měly by fungovat všechny mechanismy ověřování SSH, které vás jen napadnou. -## Generating Your SSH Public Key ## +## Vygenerování veřejného SSH klíče ## -That being said, many Git servers authenticate using SSH public keys. In order to provide a public key, each user in your system must generate one if they don’t already have one. This process is similar across all operating systems. -First, you should check to make sure you don’t already have a key. By default, a user’s SSH keys are stored in that user’s `~/.ssh` directory. You can easily check to see if you have a key already by going to that directory and listing the contents: +Mnoho serverů Git provádí ověřování totožnosti pomocí veřejných SSH klíčů. Aby vám mohli všichni uživatelé ve vašem systému poskytnout veřejný klíč, musí si ho každý z nich nechat vygenerovat (pokud klíč ještě nemá). Tento proces se napříč operačními systémy téměř neliší. +Nejprve byste se měli ujistit, že ještě žádný klíč nemáte. Uživatelské SSH klíče jsou standardně uloženy v adresáři `~/.ssh` daného uživatele. Nejsnazší způsob kontroly, zda už klíč vlastníte, je přejít do tohoto adresáře a zjistit jeho obsah: $ cd ~/.ssh $ ls authorized_keys2 id_dsa known_hosts config id_dsa.pub -You’re looking for a pair of files named something and something.pub, where the something is usually `id_dsa` or `id_rsa`. The `.pub` file is your public key, and the other file is your private key. If you don’t have these files (or you don’t even have a `.ssh` directory), you can create them by running a program called `ssh-keygen`, which is provided with the SSH package on Linux/Mac systems and comes with the MSysGit package on Windows: +Zobrazí se několik souborů s názvem `xxx` a `xxx.pub`, kde `xxx` je většinou `id_dsa` nebo `id_rsa`. Soubor `.pub` je váš veřejný klíč, druhý soubor je soukromý klíč. Pokud tyto soubory nemáte (nebo dokonce vůbec nemáte adresář `.ssh`), můžete si je vytvořit. Spusťte program `ssh-keygen`, který je v systémech Linux/Mac součástí balíčku SSH a v systému Windows součástí balíčku MSysGit: - $ ssh-keygen + $ ssh-keygen Generating public/private rsa key pair. - Enter file in which to save the key (/Users/schacon/.ssh/id_rsa): - Enter passphrase (empty for no passphrase): - Enter same passphrase again: + Enter file in which to save the key (/Users/schacon/.ssh/id_rsa): + Enter passphrase (empty for no passphrase): + Enter same passphrase again: Your identification has been saved in /Users/schacon/.ssh/id_rsa. Your public key has been saved in /Users/schacon/.ssh/id_rsa.pub. The key fingerprint is: 43:c5:5b:5f:b1:f1:50:43:ad:20:a6:92:6a:1f:9a:3a schacon@agadorlaptop.local -First it confirms where you want to save the key (`.ssh/id_rsa`), and then it asks twice for a passphrase, which you can leave empty if you don’t want to type a password when you use the key. +Program nejprve potvrdí, kam chcete klíč uložit (`.ssh/id_rsa`), a poté se dvakrát zeptá na přístupové heslo. Pokud nechcete při používání klíče zadávat heslo, můžete ho nyní nechat prázdné. -Now, each user that does this has to send their public key to you or whoever is administrating the Git server (assuming you’re using an SSH server setup that requires public keys). All they have to do is copy the contents of the `.pub` file and e-mail it. The public keys look something like this: +Každý uživatel, který si tímto způsobem nechá vygenerovat veřejný klíč, ho nyní pošle vám nebo jinému správci serveru Git (za předpokladu, že používáte nastavení SSH serveru vyžadující veřejné klíče). Stačí přitom zkopírovat obsah souboru `.pub` a odeslat ho e-mailem. Veřejné klíče mají zhruba tuto podobu: - $ cat ~/.ssh/id_rsa.pub + $ cat ~/.ssh/id_rsa.pub ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU GPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3 Pbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA @@ -199,18 +200,18 @@ Now, each user that does this has to send their public key to you or whoever is mZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx NrRFi9wrf+M7Q== schacon@agadorlaptop.local -For a more in-depth tutorial on creating an SSH key on multiple operating systems, see the GitHub guide on SSH keys at `http://github.com/guides/providing-your-ssh-key`. +Budete-li potřebovat podrobnější návod k vytvoření SSH klíče v různých operačních systémech, můžete se na vytváření SSH klíčů podívat do příručky GitHub: `http://github.com/guides/providing-your-ssh-key` (anglicky). -## Setting Up the Server ## +## Nastavení serveru ## -Let’s walk through setting up SSH access on the server side. In this example, you’ll use the `authorized_keys` method for authenticating your users. We also assume you’re running a standard Linux distribution like Ubuntu. First, you create a 'git' user and a `.ssh` directory for that user. +Projděme si nastavení SSH přístupu na straně serveru. V tomto příkladu použijeme k ověření identity uživatelů metodu `authorized_keys`. Předpokládáme také, že pracujete se standardní linuxovou distribucí, jako je např. Ubuntu. Nejprve vytvoříte uživatele 'git' a adresář `.ssh` pro tohoto uživatele. $ sudo adduser git $ su git $ cd $ mkdir .ssh -Next, you need to add some developer SSH public keys to the `authorized_keys` file for that user. Let’s assume you’ve received a few keys by e-mail and saved them to temporary files. Again, the public keys look something like this: +V dalším kroku musíte vložit veřejné SSH klíče od svých vývojářů do souboru `authorized_keys` pro tohoto uživatele. Předpokládejme, že jste e-mailem dostali několik klíčů a uložili jste je do dočasných souborů. Veřejné klíče vypadají opět nějak takto: $ cat /tmp/id_rsa.john.pub ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCB007n/ww+ouN4gSLKssMxXnBOvf9LGt4L @@ -220,20 +221,24 @@ Next, you need to add some developer SSH public keys to the `authorized_keys` fi O7TCUSBdLQlgMVOFq1I2uPWQOkOWQAHukEOmfjy2jctxSDBQ220ymjaNsHT4kgtZg2AYYgPq dAv8JggJICUvax2T9va5 gsg-keypair -You just append them to your `authorized_keys` file: +Vy nyní klíče přidáte do souboru `authorized_keys`: $ cat /tmp/id_rsa.john.pub >> ~/.ssh/authorized_keys $ cat /tmp/id_rsa.josie.pub >> ~/.ssh/authorized_keys $ cat /tmp/id_rsa.jessica.pub >> ~/.ssh/authorized_keys -Now, you can set up an empty repository for them by running `git init` with the `--bare` option, which initializes the repository without a working directory: +Autentizace vůči SSH, která je založená na klíči, obvykle vynucuje zvýšenou bezpečnost tím, že pro zúčastněné soubory vyžaduje omezená oprávnění. Aby SSH neodmítl pracovat, napište následující: + + $ chmod -R go= ~/.ssh + +Nyní pro ně můžete nastavit prázdný repozitář. Spusťte příkaz `git init` s parametrem `--bare`, který inicializuje repozitář bez pracovního adresáře: $ cd /opt/git $ mkdir project.git $ cd project.git $ git --bare init -Then, John, Josie, or Jessica can push the first version of their project into that repository by adding it as a remote and pushing up a branch. Note that someone must shell onto the machine and create a bare repository every time you want to add a project. Let’s use `gitserver` as the hostname of the server on which you’ve set up your 'git' user and repository. If you’re running it internally, and you set up DNS for `gitserver` to point to that server, then you can use the commands pretty much as is: +John, Josie a Jessica pak mohou do tohoto repozitáře odeslat první verzi svého projektu: přidají si ho jako vzdálený repozitář a odešlou do něj svou větev. Nezapomeňte, že pokaždé, když chcete vytvořit projekt, musí se k počítači někdo přihlásit a vytvořit holý repozitář. Pro server, na kterém jste nastavili uživatele 'git' a repozitář, můžeme použít název hostitele `gitserver`. Pokud server provozujete interně a nastavíte DNS pro `gitserver` tak, aby ukazovalo na tento server, můžete používat i takovéto příkazy: # on Johns computer $ cd myproject @@ -243,56 +248,62 @@ Then, John, Josie, or Jessica can push the first version of their project into t $ git remote add origin git@gitserver:/opt/git/project.git $ git push origin master -At this point, the others can clone it down and push changes back up just as easily: +Ostatní nyní mohou velmi snadno repozitář naklonovat i do něj odesílat změny: $ git clone git@gitserver:/opt/git/project.git + $ cd project $ vim README $ git commit -am 'fix for the README file' $ git push origin master -With this method, you can quickly get a read/write Git server up and running for a handful of developers. +Tímto způsobem lze rychle vytvořit a spustit server Git ke čtení i zápisu pro menší počet vývojářů. -As an extra precaution, you can easily restrict the 'git' user to only doing Git activities with a limited shell tool called `git-shell` that comes with Git. If you set this as your 'git' user’s login shell, then the 'git' user can’t have normal shell access to your server. To use this, specify `git-shell` instead of bash or csh for your user’s login shell. To do so, you’ll likely have to edit your `/etc/passwd` file: +Pro větší bezpečnost máte možnost využít nástroj `git-shell`, který je distribuován se systémem Git. Pomocí něj lze uživatele 'git' snadno omezit tak, aby mohl prováděl pouze operace systému Git. Pokud ho nastavíte jako přihlašovací shell uživatele 'git', pak nebude mít uživatel 'git' normální shellový přístup k vašemu serveru. Chcete-li nástroj použít, zadejte pro přihlašovací shell vašeho uživatele `git-shell` místo bash nebo csh. V takovém případě pravděpodobně budete muset upravit soubor `/etc/passwd`: $ sudo vim /etc/passwd -At the bottom, you should find a line that looks something like this: +Dole byste měli najít řádek, který vypadá asi takto: git:x:1000:1000::/home/git:/bin/sh -Change `/bin/sh` to `/usr/bin/git-shell` (or run `which git-shell` to see where it’s installed). The line should look something like this: +Změňte `/bin/sh` na `/usr/bin/git-shell` (nebo spusťte příkaz `which git-shell`, abyste viděli, kde je nainstalován). Řádek by měl vypadat takto: git:x:1000:1000::/home/git:/usr/bin/git-shell -Now, the 'git' user can only use the SSH connection to push and pull Git repositories and can’t shell onto the machine. If you try, you’ll see a login rejection like this: +Uživatel 'git' nyní může používat SSH připojení k odesílání a stahování repozitářů Git, ale nemůže se přihlásit k počítači. Pokud to zkusíte, zobrazí se zamítnutí přihlášení: $ ssh git@gitserver fatal: What do you think I am? A shell? Connection to gitserver closed. -## Public Access ## +## Veřejný přístup ## -What if you want anonymous read access to your project? Perhaps instead of hosting an internal private project, you want to host an open source project. Or maybe you have a bunch of automated build servers or continuous integration servers that change a lot, and you don’t want to have to generate SSH keys all the time — you just want to add simple anonymous read access. +A co když chcete u svého projektu nastavit anonymní oprávnění pro čtení? Nehostujete třeba interní soukromý projekt, ale „open source“ projekt. Nebo možná máte několik serverů průběžné integrace, které se neustále mění a vy nechcete stále generovat SSH klíče. Rádi byste vždy přidali jen obyčejné anonymní oprávnění pro čtení. -Probably the simplest way for smaller setups is to run a static web server with its document root where your Git repositories are, and then enable that `post-update` hook we mentioned in the first section of this chapter. Let’s work from the previous example. Say you have your repositories in the `/opt/git` directory, and an Apache server is running on your machine. Again, you can use any web server for this; but as an example, we’ll demonstrate some basic Apache configurations that should give you an idea of what you might need. +Patrně nejjednodušším způsobem pro menší týmy je spustit statický webový server s kořenovým adresářem dokumentů, v němž budou uloženy vaše Git repozitáře, a zapnout zásuvný modul `post-update`, o kterém jsme se zmínili už v první části této kapitoly. Můžeme pokračovat v našem předchozím příkladu. Řekněme, že máte repozitáře uloženy v adresáři `/opt/git` a na vašem počítači je spuštěn server Apache. Opět, můžete použít jakýkoli webový server. Pro názornost ale ukážeme některá základní nastavení serveru Apache, abyste získali představu, co vás může čekat. -First you need to enable the hook: +Nejprve ze všeho budete muset zapnout zásuvný modul: $ cd project.git $ mv hooks/post-update.sample hooks/post-update $ chmod a+x hooks/post-update -If you’re using a version of Git earlier than 1.6, the `mv` command isn’t necessary — Git started naming the hooks examples with the .sample postfix only recently. +Jaká je funkce zásuvného modulu `post-update`? V principu vypadá asi takto: -What does this `post-update` hook do? It looks basically like this: - - $ cat .git/hooks/post-update + $ cat .git/hooks/post-update #!/bin/sh + # + # An example hook script to prepare a packed repository for use over + # dumb transports. + # + # To enable this hook, rename this file to "post-update". + # + exec git-update-server-info -This means that when you push to the server via SSH, Git will run this command to update the files needed for HTTP fetching. +Znamená to, že až budete odesílat data na server prostřednictvím SSH, Git spustí tento příkaz a aktualizuje soubory vyžadované pro přístup přes HTTP. -Next, you need to add a VirtualHost entry to your Apache configuration with the document root as the root directory of your Git projects. Here, we’re assuming that you have wildcard DNS set up to send `*.gitserver` to whatever box you’re using to run all this: +Dále je třeba přidat záznam VirtualHost do konfigurace Apache s kořenovým adresářem dokumentů nastaveným jako kořenový adresář vašich projektů Git. Tady předpokládáme, že máte nastaveny zástupné znaky DNS (wildcard DNS) a můžete odeslat `*.gitserver` do kteréhokoli boxu, který používáte, a spustit následující: ServerName git.gitserver @@ -303,42 +314,42 @@ Next, you need to add a VirtualHost entry to your Apache configuration with the -You’ll also need to set the Unix user group of the `/opt/git` directories to `www-data` so your web server can read-access the repositories, because the Apache instance running the CGI script will (by default) be running as that user: +Budete také muset nastavit uživatelskou skupinu adresáře `/opt/git` na `www-data`. Váš webový server tak získá přístup pro čtení k repozitářům, protože instance Apache, která spouští CGI skript, bude (standardně) spuštěna s tímto uživatelem: $ chgrp -R www-data /opt/git -When you restart Apache, you should be able to clone your repositories under that directory by specifying the URL for your project: +Po restartování serveru Apache byste měli být schopni naklonovat své repozitáře v tomto adresáři. Zadejte adresu URL svého projektu: $ git clone http://git.gitserver/project.git -This way, you can set up HTTP-based read access to any of your projects for a fair number of users in a few minutes. Another simple option for public unauthenticated access is to start a Git daemon, although that requires you to daemonize the process - we’ll cover this option in the next section, if you prefer that route. +Tímto způsobem můžete během pár minut nastavit oprávnění pro čtení založené na protokolu HTTP pro větší počet uživatelů k jakémukoli svému projektu. Další jednoduchou možností nastavení veřejného neověřovaného přístupu je spustit démona Git. Pokud je pro vás tato cesta schůdnější, budeme se jí věnovat v následující části. ## GitWeb ## -Now that you have basic read/write and read-only access to your project, you may want to set up a simple web-based visualizer. Git comes with a CGI script called GitWeb that is commonly used for this. You can see GitWeb in use at sites like `http://git.kernel.org` (see Figure 4-1). +Nyní, když máte ke svému projektu nastavena základní oprávnění pro čtení/zápis a pouze pro čtení, možná budete chtít nastavit jednoduchou online vizualizaci. Git vám nabízí CGI skript s názvem GitWeb, který se k tomuto účelu běžně používá. V činnosti můžete GitWeb pozorovat například na stránkách `http://git.kernel.org` (viz obrázek 4-1). -Insert 18333fig0401.png -Figure 4-1. The GitWeb web-based user interface +Insert 18333fig0401.png +Obrázek 4-1. Online uživatelské rozhraní GitWeb -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 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. To start `instaweb` with a non-lighttpd handler, you can run it with the `--httpd` option. +Pokud vás zajímá, jak by GitWeb vypadal pro váš projekt, nabízí Git příkaz, jímž lze spustit dočasnou instanci. V systému je třeba mít lehký server typu `lighttpd` nebo `webrick`. V počítačích se systémem Linux je často nainstalován `lighttpd`. Spustit ho lze zadáním příkazu `git instaweb` v adresáři vašeho projektu. Pokud používáte OS Mac, v systému Leopard je předinstalován jazyk Ruby, a proto pro vás bude nejlepší variantou zřejmě server `webrick`. Chcete-li spustit `instaweb` s jiným správcem než `lighttpd`, použijte parametr `--httpd`: $ git instaweb --httpd=webrick [2009-02-21 10:02:21] INFO WEBrick 1.3.1 [2009-02-21 10:02:21] INFO ruby 1.8.6 (2008-03-03) [universal-darwin9.0] -That starts up an HTTPD server on port 1234 and then automatically starts a web browser that opens on that page. It’s pretty easy on your part. When you’re done and want to shut down the server, you can run the same command with the `--stop` option: +Tím spustíte HTTPD server na portu 1234 a automaticky se spustí webový prohlížeč, který otevře tuto stránku. Není to nic obtížného. Až skončíte a budete chtít server vypnout, spusťte stejný příkaz s parametrem `--stop`: $ git instaweb --httpd=webrick --stop -If you want to run the web interface on a server all the time for your team or for an open source project you’re hosting, you’ll need to set up the CGI script to be served by your normal web server. Some Linux distributions have a `gitweb` package that you may be able to install via `apt` or `yum`, so you may want to try that first. We’ll walk though installing GitWeb manually very quickly. First, you need to get the Git source code, which GitWeb comes with, and generate the custom CGI script: +Chcete-li trvale spustit webové rozhraní na serveru pro svůj tým nebo nebo pro open-source projekt, který hostujete, musíte nastavit CGI skript tak, aby byl obsluhován vaším běžným webovým serverem. Některé linuxové distribuce mají balíček `gitweb`, který by mělo být možné nainstalovat pomocí nástrojů `apt` nebo `yum`. Zkuste proto tuto možnost jako první. Ruční instalaci skriptu probereme velmi rychle. Nejprve je třeba získat zdrojový kód systému Git, s nímž je GitWeb distribuován, a vygenerovat uživatelský CGI skript: $ git clone git://git.kernel.org/pub/scm/git/git.git $ cd git/ $ make GITWEB_PROJECTROOT="/opt/git" \ - prefix=/usr gitweb/gitweb.cgi + prefix=/usr gitweb $ sudo cp -Rf gitweb /var/www/ -Notice that you have to tell the command where to find your Git repositories with the `GITWEB_PROJECTROOT` variable. Now, you need to make Apache use CGI for that script, for which you can add a VirtualHost: +Všimněte si, že musíte příkazu pomocí proměnné `GITWEB_PROJECTROOT` sdělit, kde najde repozitáře Git. Nyní musíte zajistit, aby server Apache používal CGI pro skript, pro který můžete přidat VirtualHost: ServerName gitserver @@ -353,65 +364,65 @@ Notice that you have to tell the command where to find your Git repositories wit -Again, GitWeb can be served with any CGI capable web server; if you prefer to use something else, it shouldn’t be difficult to set up. At this point, you should be able to visit `http://gitserver/` to view your repositories online, and you can use `http://git.gitserver` to clone and fetch your repositories over HTTP. +Znovu připomeňme, že GitWeb může být obsluhován jakýmkoli webovým serverem podporujícím CGI. Chcete-li používat jakýkoli jiný server, nemělo by být nastavení obtížné. V tomto okamžiku byste měli být schopni prohlížet své repozitáře online na adrese `http://gitserver/` a používat `http://git.gitserver` ke klonování a vyzvedávání repozitářů prostřednictvím protokolu HTTP. ## Gitosis ## -Keeping all users’ public keys in the `authorized_keys` file for access works well only for a while. When you have hundreds of users, it’s much more of a pain to manage that process. You have to shell onto the server each time, and there is no access control — everyone in the file has read and write access to every project. +Uchovávat veřejné klíče všech uživatelů v souboru `authorized_keys` není uspokojivým řešením na věčné časy. Musíte-li spravovat stovky uživatelů, je tento proces příliš náročný. Pokaždé se musíte přihlásit na server a k dispozici nemáte žádnou správu přístupu – všichni, kdo jsou uvedeni v souboru, mají ke každému projektu oprávnění pro čtení i pro zápis. -At this point, you may want to turn to a widely used software project called Gitosis. Gitosis is basically a set of scripts that help you manage the `authorized_keys` file as well as implement some simple access controls. The really interesting part is that the UI for this tool for adding people and determining access isn’t a web interface but a special Git repository. You set up the information in that project; and when you push it, Gitosis reconfigures the server based on that, which is cool. +Proto možná rádi přejdete na rozšířený softwarový projekt „Gitosis“. Gitosis je v podstatě sada skriptů usnadňující správu souboru `authorized_keys` a implementaci jednoduché správy přístupu. Nejzajímavější je na nástroji Gitosis jeho uživatelské rozhraní pro přidávání uživatelů a specifikaci přístupu – nejedná se totiž o webové rozhraní, ale o speciální repozitář Git. V tomto projektu nastavíte všechny informace, a až ho odešlete, Gitosis překonfiguruje server, který je na něm založen. To je jistě příjemné řešení. -Installing Gitosis isn’t the simplest task ever, but it’s not too difficult. It’s easiest to use a Linux server for it — these examples use a stock Ubuntu 8.10 server. +Instalace nástroje Gitosis sice nepatří mezi nejsnazší, ale není ani příliš složitá. Nejjednodušší je k ní použít linuxový server – tyto příklady používají běžný Ubuntu server 8.10. -Gitosis requires some Python tools, so first you have to install the Python setuptools package, which Ubuntu provides as python-setuptools: +Gitosis vyžaduje některé nástroje v jazyce Python, a proto první, co musíte udělat, je nainstalovat pythonovský balíček setuptools, který je v Ubuntu dostupný jako python-setuptools: $ apt-get install python-setuptools -Next, you clone and install Gitosis from the project’s main site: +Dále naklonujte a nainstalujte Gitosis z hlavní stránky projektu: - $ git clone git://eagain.net/gitosis.git + $ git clone https://github.com/tv42/gitosis.git $ cd gitosis $ sudo python setup.py install -That installs a couple of executables that Gitosis will use. Next, Gitosis wants to put its repositories under `/home/git`, which is fine. But you have already set up your repositories in `/opt/git`, so instead of reconfiguring everything, you create a symlink: +Tímto příkazem nainstalujete několik spustitelných souborů, které bude Gitosis používat. Gitosis dále vyžaduje, abyste jeho repozitáře uložili do adresáře `/home/git`. Vy už však máte repozitáře vytvořeny ve složce `/opt/git`, a tak místo toho, abyste museli vše překonfigurovat, vytvoříte symbolický odkaz: $ ln -s /opt/git /home/git/repositories -Gitosis is going to manage your keys for you, so you need to remove the current file, re-add the keys later, and let Gitosis control the `authorized_keys` file automatically. For now, move the `authorized_keys` file out of the way: +Gitosis teď bude spravovat klíče za vás. Proto je třeba, abyste odstranili aktuální soubor, klíče znovu přidali později a nechali Gitosis automaticky spravovat soubor `authorized_keys`. Pro tuto chvíli tedy odstraňte soubor `authorized_keys`: $ mv /home/git/.ssh/authorized_keys /home/git/.ssh/ak.bak -Next you need to turn your shell back on for the 'git' user, if you changed it to the `git-shell` command. People still won’t be able to log in, but Gitosis will control that for you. So, let’s change this line in your `/etc/passwd` file +Dále musíte znovu zapnout shell na uživatele 'git', jestliže jste ho změnili na příkaz `git-shell`. Uživatelé se stále ještě nebudou moci přihlásit, ale Gitosis za vás bude provádět správu. Takže v souboru `/etc/passwd` změňte následující řádek git:x:1000:1000::/home/git:/usr/bin/git-shell -back to this: +zpět na git:x:1000:1000::/home/git:/bin/sh -Now it’s time to initialize Gitosis. You do this by running the `gitosis-init` command with your personal public key. If your public key isn’t on the server, you’ll have to copy it there: +V tomto okamžiku můžeme inicializovat nástroj Gitosis. Učiníte tak spuštěním příkazu `gitosis-init` se svým osobním veřejným klíčem. Není-li váš veřejný klíč na serveru, musíte ho tam nakopírovat: $ sudo -H -u git gitosis-init < /tmp/id_dsa.pub Initialized empty Git repository in /opt/git/gitosis-admin.git/ Reinitialized existing Git repository in /opt/git/gitosis-admin.git/ -This lets the user with that key modify the main Git repository that controls the Gitosis setup. Next, you have to manually set the execute bit on the `post-update` script for your new control repository. +Uživatel s tímto klíčem poté bude moci měnit hlavní repozitář Git, kterým se ovládá nastavení nástroje Gitosis. Dále je třeba ručně nastavit právo spuštění na skriptu `post-update` pro nový řídicí repozitář. $ sudo chmod 755 /opt/git/gitosis-admin.git/hooks/post-update -You’re ready to roll. If you’re set up correctly, you can try to SSH into your server as the user for which you added the public key to initialize Gitosis. You should see something like this: +Teď to můžete rozjet. Pokud jste nastavení provedli správně, můžete vyzkoušet SSH přístup na server jako uživatel, pro kterého jste přidali veřejný klíč při inicializaci nástroje Gitosis. Mělo by se zobrazit asi následující: $ ssh git@gitserver PTY allocation request failed on channel 0 - fatal: unrecognized command 'gitosis-serve schacon@quaternion' + ERROR:gitosis.serve.main:Need SSH_ORIGINAL_COMMAND in environment. Connection to gitserver closed. -That means Gitosis recognized you but shut you out because you’re not trying to do any Git commands. So, let’s do an actual Git command — you’ll clone the Gitosis control repository: +To znamená, že vás Gitosis sice rozpoznal, ale nedovolí vám přístup, protože se nepokoušíte zadat žádný příkaz Git. Provedeme tedy skutečný příkaz systému Git a naklonujeme řídicí repozitář Gitosis: # on your local computer $ git clone git@gitserver:gitosis-admin.git -Now you have a directory named `gitosis-admin`, which has two major parts: +Nyní máte adresář s názvem `gitosis-admin`, sestávající ze dvou hlavních částí: $ cd gitosis-admin $ find . @@ -419,107 +430,257 @@ Now you have a directory named `gitosis-admin`, which has two major parts: ./keydir ./keydir/scott.pub -The `gitosis.conf` file is the control file you use to specify users, repositories, and permissions. The `keydir` directory is where you store the public keys of all the users who have any sort of access to your repositories — one file per user. The name of the file in `keydir` (in the previous example, `scott.pub`) will be different for you — Gitosis takes that name from the description at the end of the public key that was imported with the `gitosis-init` script. +Soubor `gitosis.conf` je řídicí soubor, který slouží ke specifikaci uživatelů, repozitářů a oprávnění. V adresáři `keydir` jsou pak uloženy veřejné klíče pro všechny uživatele, kteří mají (ať už jakýkoli) přístup k vašim repozitářům – jeden soubor pro každého uživatele. Název souboru v adresáři `keydir` (v předchozím příkladu `scott.pub`) bude ve vašem případě jiný. Gitosis převezme tento název z popisu na konci veřejného klíče, který byl importován spolu se skriptem `gitosis-init`. -If you look at the `gitosis.conf` file, it should only specify information about the `gitosis-admin` project that you just cloned: +Pokud se podíváte na soubor `gitosis.conf`, měl by udávat pouze informace o projektu `gitosis-admin`, který jste právě naklonovali: - $ cat gitosis.conf + $ cat gitosis.conf [gitosis] [group gitosis-admin] - writable = gitosis-admin members = scott + writable = gitosis-admin -It shows you that the 'scott' user — the user with whose public key you initialized Gitosis — is the only one who has access to the `gitosis-admin` project. +Tato informace znamená, že uživatel 'scott' – ten, jehož veřejným klíčem jste inicializovali Gitosis – je jediným uživatelem, který má přístup k projektu `gitosis-admin`. -Now, let’s add a new project for you. You’ll add a new section called `mobile` where you’ll list the developers on your mobile team and projects that those developers need access to. Because 'scott' is the only user in the system right now, you’ll add him as the only member, and you’ll create a new project called `iphone_project` to start on: +Nyní přidáme nový projekt. Přidáte novou část s názvem `mobile`, která bude obsahovat seznam vývojářů vašeho mobilního týmu a projektů, k nimž tito vývojáři potřebují přístup. Protože je v tuto chvíli jediným uživatelem v systému 'scott', přidáte ho jako jediného člena a vytvoříte pro něj nový projekt s názvem `iphone_project`: [group mobile] - writable = iphone_project members = scott + writable = iphone_project -Whenever you make changes to the `gitosis-admin` project, you have to commit the changes and push them back up to the server in order for them to take effect: +Pokaždé, když provedete změny v projektu `gitosis-admin`, musíte tyto změny zapsat a odeslat je zpět na server, aby nabyly účinnosti: $ git commit -am 'add iphone_project and mobile group' - [master]: created 8962da8: "changed name" - 1 files changed, 4 insertions(+), 0 deletions(-) - $ git push + [master 8962da8] add iphone_project and mobile group + 1 file changed, 4 insertions(+) + $ git push origin master Counting objects: 5, done. - Compressing objects: 100% (2/2), done. - Writing objects: 100% (3/3), 272 bytes, done. - Total 3 (delta 1), reused 0 (delta 0) - To git@gitserver:/opt/git/gitosis-admin.git + Compressing objects: 100% (3/3), done. + Writing objects: 100% (3/3), 272 bytes | 0 bytes/s, done. + Total 3 (delta 0), reused 0 (delta 0) + To git@gitserver:gitosis-admin.git fb27aec..8962da8 master -> master -You can make your first push to the new `iphone_project` project by adding your server as a remote to your local version of the project and pushing. You no longer have to manually create a bare repository for new projects on the server — Gitosis creates them automatically when it sees the first push: +Do nového projektu `iphone_project` teď můžete odeslat svá první data: přidejte do lokální verze projektu svůj server jako vzdálený repozitář a odešlete změny. Od této chvíle už nebudete muset ručně vytvářet holé repozitáře pro nové projekty na serveru. Gitosis je vytvoří automaticky, jakmile zjistí první odeslání dat: $ git remote add origin git@gitserver:iphone_project.git $ git push origin master Initialized empty Git repository in /opt/git/iphone_project.git/ Counting objects: 3, done. - Writing objects: 100% (3/3), 230 bytes, done. + Writing objects: 100% (3/3), 230 bytes | 0 bytes/s, done. Total 3 (delta 0), reused 0 (delta 0) To git@gitserver:iphone_project.git * [new branch] master -> master -Notice that you don’t need to specify the path (in fact, doing so won’t work), just a colon and then the name of the project — Gitosis finds it for you. +Všimněte si, že není třeba zadávat cestu (naopak, příkaz by pak nefungoval), pouze dvojtečku a za ní název projektu. Gitosis už projekt vyhledá. -You want to work on this project with your friends, so you’ll have to re-add their public keys. But instead of appending them manually to the `~/.ssh/authorized_keys` file on your server, you’ll add them, one key per file, into the `keydir` directory. How you name the keys determines how you refer to the users in the `gitosis.conf` file. Let’s re-add the public keys for John, Josie, and Jessica: +Na tomto projektu chcete spolupracovat s přáteli, a proto budete muset znovu přidat jejich veřejné klíče. Ale místo toho, abyste je vkládali ručně do souboru `~/.ssh/authorized_keys` na serveru, přidáte je do adresáře `keydir`, jeden soubor pro každý klíč. Jak tyto klíče pojmenujete, závisí na tom, jak jsou uživatelé označeni v souboru `gitosis.conf`. Přidejme znovu veřejné klíče pro uživatele Johna, Josie a Jessicu: $ cp /tmp/id_rsa.john.pub keydir/john.pub $ cp /tmp/id_rsa.josie.pub keydir/josie.pub $ cp /tmp/id_rsa.jessica.pub keydir/jessica.pub -Now you can add them all to your 'mobile' team so they have read and write access to `iphone_project`: +Nyní je můžete všechny přidat do týmu 'mobile', čímž získají oprávnění pro čtení i pro zápis k `iphone_project`: [group mobile] - writable = iphone_project members = scott john josie jessica + writable = iphone_project -After you commit and push that change, all four users will be able to read from and write to that project. +Až tuto změnu zapíšete a odešlete, všichni čtyři uživatelé budou moci z tohoto projektu číst a zapisovat do něj. -Gitosis has simple access controls as well. If you want John to have only read access to this project, you can do this instead: +Gitosis nabízí také jednoduchou správu přístupu. Pokud chcete, aby měl John u projektu pouze oprávnění pro čtení, můžete provést následující: [group mobile] - writable = iphone_project members = scott josie jessica + writable = iphone_project [group mobile_ro] - readonly = iphone_project members = john + readonly = iphone_project -Now John can clone the project and get updates, but Gitosis won’t allow him to push back up to the project. You can create as many of these groups as you want, each containing different users and projects. You can also specify another group as one of the members (using `@` as prefix), to inherit all of its members automatically: +John nyní může naklonovat projekt a stahovat jeho aktualizace, ale Gitosis mu neumožní, aby odesílal data zpět do projektu. Takových skupin můžete vytvořit libovolně mnoho. Každá může obsahovat různé uživatele a projekty. Jako jednoho ze členů skupiny můžete zadat také celou jinou skupinu (použijete pro ni předponu `@`). Všichni její členové se tím automaticky zdědí. [group mobile_committers] members = scott josie jessica [group mobile] - writable = iphone_project members = @mobile_committers + writable = iphone_project [group mobile_2] - writable = another_iphone_project members = @mobile_committers john + writable = another_iphone_project + +Máte-li jakékoli problémy, může vám pomoci zadání `loglevel=DEBUG` do části `[gitosis]`. Pokud jste odesláním nesprávné konfigurace ztratili oprávnění k odesílání dat, můžete ručně opravit soubor na serveru v adresáři `/home/git/.gitosis.conf` – jedná se o soubor, z nějž Gitosis načítá data. Po odeslání dat do projektu bude soubor `gitosis.conf`, který jste právě odeslali, umístěn do tohoto adresáře. Pokud soubor ručně upravíte, zůstane v této podobě až do dalšího úspěšného odeslání do projektu `gitosis-admin`. + +## Gitolite ## + +Tato podkapitola slouží k rychlému seznámení s Gitolite a uvádí základní pokyny pro instalaci a nastavení. Nemůže ale nahradit ohromný objem [dokumentace][gltoc], která se s Gitolite dodává. Tato podkapitola se může občas změnit, takže se možná chcete podívat na její [poslední verzi][gldpg]. + +[gldpg]: http://sitaramc.github.com/gitolite/progit.html +[gltoc]: http://sitaramc.github.com/gitolite/master-toc.html + +Gitolite je autorizační vrstva nad gitem, která při autentizaci spoléhá na `sshd` nebo `httpd`. (Připomeňme si: autentizace spočívá v rozpoznání uživatele, autorizací rozumíme rozhodování, zda má povolení k provádění toho, co se provést pokouší.) + +Gitolite umožňuje nastavit přístupová práva nejen na repozitáře (podobně jako Gitosis), ale také na větve a značky v každém repozitáři. To znamená, že lze nastavit, aby určití lidé mohli odesílat jen do určité větve (nebo určité značky; obecně „refs“), ale do jiné ne. + +### Instalace ### + +Instalace Gitolite je velmi jednoduchá a to i když si nepřečtete obsáhlou dokumentaci, která je k dispozici. Budete potřebovat účet na nějakém unixovém serveru. Pokud už jsou nainstalovány nástroje Git, Perl a SSH server kompatibilní s OpenSSH, nebudete potřebovat ani přístup root. V příkladech uvedených níže budeme používat účet `git` na serveru `gitserver`. + +Nástroj Gitolite je ve smyslu „serverového“ softwaru poněkud neobvyklý. Přístup se realizuje přes SSH, takže každá serverová userid je potenciálně „hostitelem gitolite“ (gitolite host). Teď si popíšeme nejjednodušší způsob instalace. V dokumentaci naleznete další metody. + +Začněte tím, že na serveru vytvoříte uživatele nazvaného `git` a přihlásíte se na něj. Z vaší pracovní stanice nakopírujte svůj veřejný SSH klíč (pokud jste spustili `ssh-keygen` s implicitními hodnotami, jde o soubor `~/.ssh/id_rsa.pub`) a přejmenujte jej na `.pub` (v příkladech budeme používat `scott.pub`). Potom proveďte následující příkazy: + + $ git clone git://github.com/sitaramc/gitolite + $ gitolite/install -ln + # assumes $HOME/bin exists and is in your $PATH + $ gitolite setup -pk $HOME/scott.pub + +Poslední příkaz vytvoří na serveru nový gitovský repozitář nazvaný `gitolite-admin`. + +Nakonec přejděte zpět na pracovní stanici a spusťte `git clone git@gitserver:gitolite-admin`. To je všechno! Nyní máte Gitolite nainstalovaný na serveru a v domácím adresáři vaší pracovní stanice máte také úplně nový repozitář `gitolite-admin`. Své nastavení Gitolite spravujete pomocí provádění změn v tomto repozitáři jejich odesíláním (push). + +### Přizpůsobení instalace ### + +Základní rychlá metoda instalace bude většině lidí vyhovovoat. V případě potřeby existují další možnosti přizpůsobení. Něco můžete změnit jednoduše editací rc souboru. Pokud to ale nestačí, naleznete víc v dokumentaci věnované přizpůsobení Gitolite. + +### Konfigurační soubor a pravidla přístupu ### + +Jakmile je instalace dokončena, přepněte se do repozitáře `gitolite-admin`, který jste naklonovali na váš počítač, a podívejte se co tam je: + + $ cd ~/gitolite-admin/ + $ ls + conf/ keydir/ + $ find conf keydir -type f + conf/gitolite.conf + keydir/scott.pub + $ cat conf/gitolite.conf + + repo gitolite-admin + RW+ = scott + + repo testing + RW+ = @all + +Všimněte si, že „scott“ (jméno veřejného klíče v dříve použitém příkazu `gitolite setup`) má práva pro čtení i zápis k repozitáři `gitolite-admin` a také stejnojmenný veřejný klíč. + +Přidávání dalších uživatelů je snadné. Pokud chceme přidat uživatele „alice“, získáme její veřejný klíč, pojmenujeme jej `alice.pub` a umístíme jej do adresáře `keydir`. Je součástí klonu repozitáře `gitolite-admin`, který jsme právě vytvořili na pracovní stanici. Přidáme, potvrdíme a odešleme změny (add, commit, push). Tím jsme dosáhli přidání uživatele. + +Syntaxe konfiguračního souboru pro Gitolite je dobře dokumentovaná, takže zde zdůrazníme jen pár věcí. + +Pro usnadnění můžete uživatele i repozitáře sdružovat do skupin. Jména skupin se chovají jako makra; když je definujete, je úplně jedno jestli jde o projekty nebo uživatele; rozdíl se pozná až v momentu, kdy „makro“ *použijete*. + + @oss_repos = linux perl rakudo git gitolite + @secret_repos = fenestra pear + + @admins = scott + @interns = ashok + @engineers = sitaram dilbert wally alice + @staff = @admins @engineers @interns + +Můžete nastavovat přístupová práva na úrovni referencí. Skupina interns může v následujícím případě odesílat pouze větev „int“. Skupina engineers mohou odesílat větve, jejichž názvy začínají na „eng-“ a značky, které začínají na „rc“ a pak následuje číslo. A skupina admins může dělat cokoliv (včetně vracení změn) v kterékoliv referenci. + + repo @oss_repos + RW int$ = @interns + RW eng- = @engineers + RW refs/tags/rc[0-9] = @engineers + RW+ = @admins + +Výraz za `RW` nebo `RW+` je regulární výraz (regex), se kterým se porovnává jméno odesílané reference (ref). Nazvěme jej tedy „refex“! Refex může mít samozřejmě mnohem více použití než je tady ukázáno, takže si dejte pozor ať to nepřeženete, zvláště pokud nejste kovaní v perlovských regulárních výrazech. + +Gitolite přidává prefix `refs/heads/` jako usnadnění syntaxe, pokud refex nezačíná na `refs/`, jak jste mohli odhadnout z příkladu. + +Důležitou vlastností syntaxe konfiguračního souboru je to, že všechna pravidla pro repozitáře nemusí být na jednom místě. Můžete nechat obecná nastavení, jako třeba pravidla pro všechny `oss_repos` z příkladu, a potom později přidávat pravidla pro více specifické případy. Např.: + + repo gitolite + RW+ = sitaram + +Toto pravidlo se pak přidá do skupiny pravidel repozitáře `gitolite`. + +Teď by vás mohlo zajímat, jak jsou vlastně pravidla pro přístup aplikována, pojďme se na to tedy krátce podívat. + +V Gitolite jsou dvě úrovně kontroly přístupů. První je úroveň repozitářů; jestliže máte práva na čtení (nebo zápis) *k jakékoliv* referenci v repozitáři, máte tím práva na čtení (nebo zápis) k tomuto repozitáři. Tohle je jediná možnost jakou měl nástroj Gitosis. + +Druhá úroveň se dá použít jen pro práva pro „zápis“ a vázána na větve nebo značky v repozitáři. Uživatelské jméno uživatele snažícího se o přístup (`W` nebo `+`) a jméno reference, kterou uživatel chce aktualizovat, jsou dané. Pravidla pro přístup jsou procházena postupně v pořadí, tak jak jsou uvedena v konfiguračním souboru a hledají se záznamy odpovídající této kombinaci uživatelského jména a reference (nezapomeňte ale, že refname se porovnává jako regulární výraz nikoliv jako pouhý řetězec). Jestliže je nalezen odpovídající záznam, odesílání je povoleno. Pokud není nalezeno nic, je přístup zamítnut. + +### Rozšířené řízení přístupu pravidly typu „odmítnutí“ ### + +Prozatím jsme si ukázali jen oprávnění nastavená na jednu z hodnot `R`, `RW` nebo `RW+`. Ale Gitolite dovoluje nastavení dalšího oprávnění: `-` s významem „odmítnutí“. To vám dává mnohem více možností, ale za cenu zvýšení složitosti. Popadnutí sítem pravidel už totiž není *jedinou* možností vedoucí k zamítnutí přístupu. *Záleží na pořadí pravidel!* + +Řekněme, že ve výše uvedené situaci budeme chtít, aby skupina engineers mohla vracet změny v jakékoliv větvi *s výjimkou* větví `master` a `integ`. Udělá se to následovně: + + RW master integ = @engineers + - master integ = @engineers + RW+ = @engineers + +Pravidla se budou opět procházet shora dolů až do momentu, kdy narazíte na shodu s vaším režimem přístupu nebo na pravidlo typu odmítnutí (deny). Odeslání do větve `master` nebo `integ`, která nevracejí zpět změny (non-rewind push), jsou povolena prvním pravidlem. Odeslání, která vracejí změny (rewind push) do těchto větví, neodpovídají prvnímu pravidlu. Porovnají se tedy s druhým pravidlem a na jeho základě budou zamítnuty. Jakékoliv odeslání (bez ohledu na to zda se jedná o vracení změn nebo ne) do jiných referencí než `master` nebo `integ` nebudou odpovídat ani prvnímu ani druhému pravidlu, a proto bude díky třetímu pravidlu povoleno. + +### Omezení odesílání změn vázané na soubory ### + +K omezení odesílání do určitých větví a určitými uživateli můžete přidat také omezení určující, které soubory mohou uživatelé měnit. Například soubor Makefile (a možná některé programy) by asi neměl kdokoliv měnit, protože je na něm závislá řada dalších věcí. Pokud se neupraví *správným způsobem*, něco by se pokazilo. Nástroji Gitolite můžeme říct: + + repo foo + RW = @junior_devs @senior_devs + + - VREF/NAME/Makefile = @junior_devs + +Uživatelé, kteří přecházejí ze starší verze Gitolite by si měli dát pozor na to, že v souvislosti s uvedeným rysem došlo k výrazné změně chování. Věnujte prosím pozornost detailům, které jsou uvedeny v příručce pro přechod k nové verzi. + +### Osobní větve ### + +Konečně Gitolite má také funkci, která se nazývá „osobní větve“ (nebo raději „jmenný prostor osobních větví“) a může být velmi užitečná v korporátním prostředí. + +Hodně výměny kódu probíhá v otevřeném gitovém světě metodou „prosím stáhněte si“. V korporátním prostředí ovšem nebývá jakýkoliv přístup bez prokázání totožnosti vítán a pracovní stanice vývojáře nemůže provádět autentizaci, takže můžete na centrální server odesílat, ale musíte požádat někoho jiného, když odtud chcete stahovat. + +To by za normálních okolností způsobilo stejný zmatek ve jménech větví jako v centralizovaných systémech správy verzí a navíc nastavování přístupových práv by administrátorovi přidalo práci. + +Gitolite vám umožní nadefinovat pro každého vývojáře jmenné prostory s prefixy „personal“ nebo „scratch“ (např. `refs/personal//*`). Podrobnosti hledejte v dokumentaci. + +### „Wildcard“ repozitáře ### + +Gitolite vám umožní určit repozitáře zástupnými znaky (wildcards; ve skutečnosti jde o perlovské regulární výrazy) -- jako například u náhodně vybraného příkladu `assignments/s[0-9][0-9]/a[0-9][0-9]`. Umožní nám též přidělit nový režim oprávnění (`C`), který uživatelům povoluje vytvářet repozitáře popsané zástupnými znaky, automaticky přidělí vlastnictví konkrétnímu uživateli, který jej vytvořil, umožní mu přidělit oprávnění `R` a `RW` dalším spolupracovníkům atd. Podrobnosti opět hledejte v dokumentaci. + +### Další vlastnosti ### + +Vysvětlení Gitolite završíme přehledem několika vlastností, které jsou detailně popsány v dokumentaci. + +**Logování:** Gitolite loguje všechny úspěšné přístupy. Jestliže máte volná pravidla pro přidělování oprávnění vracet změny (práva `RW+`) a stane se, že někdo takto „zkazí“ větev `master`, je tu ještě log soubor, který vám zachrání život, protože v něm můžete postižené SHA najít. + +**Přehledy uživatelských oprávnění:** Další příjemnou vlastností je to, co se stane, pokud se pouze pokusíte připojit pomocí SSH na server. Gitolite vám ukáže, ke kterým repozitářům máte přístup a s jakými oprávněními. Příklad: + + hello scott, this is git@git running gitolite3 v3.01-18-g9609868 on git 1.7.4.4 + + R anu-wsd + R entrans + R W git-notes + R W gitolite + R W gitolite-admin + R indic_web_input + R shreelipi_converter + +**Delegace:** Pro opravdu velké instalace můžete delegovat zodpovědnost za skupiny a repozitáře dalším lidem a nechat je spravovat jednotlivé části nezávisle. To snižuje vytížení hlavního administrátora, který tím přestává být úzkým místem správy. -If you have any issues, it may be useful to add `loglevel=DEBUG` under the `[gitosis]` section. If you’ve lost push access by pushing a messed-up configuration, you can manually fix the file on the server under `/home/git/.gitosis.conf` — the file from which Gitosis reads its info. A push to the project takes the `gitosis.conf` file you just pushed up and sticks it there. If you edit that file manually, it remains like that until the next successful push to the `gitosis-admin` project. +**Zrcadlení:** Gitolite vám pomůže se správou více zrcadel a při výpadku hlavního serveru můžete snadno přepnout na jiný. -## Git Daemon ## +## Démon Git ## -For public, unauthenticated read access to your projects, you’ll want to move past the HTTP protocol and start using the Git protocol. The main reason is speed. The Git protocol is far more efficient and thus faster than the HTTP protocol, so using it will save your users time. +Jestliže potřebujete ke svým projektům přístup pro čtení bez ověřování totožnosti, budete muset obejít protokol HTTP a začít používat protokol Git. Mluví pro něj především rychlost. Protokol Git je daleko výkonnější, a proto také rychlejší než protokol HTTP, takže uživatelům ušetří nějaký čas. -Again, this is for unauthenticated read-only access. If you’re running this on a server outside your firewall, it should only be used for projects that are publicly visible to the world. If the server you’re running it on is inside your firewall, you might use it for projects that a large number of people or computers (continuous integration or build servers) have read-only access to, when you don’t want to have to add an SSH key for each. +I v tomto případě se jedná o přístup pouze pro čtení bez ověřování totožnosti. Pokud protokol používáte na serveru mimo firewall, mělo by to být pouze u projektů, které jsou veřejně viditelné okolnímu světu. Pokud je server, na kterém protokol spouštíte, uvnitř firewallu, můžete ho používat u projektů, k nimž má přístup pro čtení velký počet lidí nebo počítačů (servery průběžné integrace nebo servery sestavení), jimž nechcete jednotlivě přiřazovat SSH klíče. -In any case, the Git protocol is relatively easy to set up. Basically, you need to run this command in a daemonized manner: +Ať tak či tak, na protokolu Git jistě oceníte jeho snadné nastavení. V podstatě je třeba spustit tento příkaz: git daemon --reuseaddr --base-path=/opt/git/ /opt/git/ -`--reuseaddr` allows the server to restart without waiting for old connections to time out, the `--base-path` option allows people to clone projects without specifying the entire path, and the path at the end tells the Git daemon where to look for repositories to export. If you’re running a firewall, you’ll also need to punch a hole in it at port 9418 on the box you’re setting this up on. +`--reuseaddr` umožňuje serveru restartování bez nutnosti čekat na vypršení časového limitu pro stará spojení, parametr `--base-path` umožňuje uživatelům klonovat projekty, aniž by museli zadávat celou cestu, a cesta na konci příkazu říká démonovi Git, kde má hledat repozitáře určené k exportu. Jestliže používáte bránu firewall, budete rovněž muset na ní povolit port 9418. -You can daemonize this process a number of ways, depending on the operating system you’re running. On an Ubuntu machine, you use an Upstart script. So, in the following file +Podle toho, jaký operační systém používáte, můžete přejít do režimu démon mnoha způsoby. U počítačů s Ubuntu můžete použít skript Upstart. Do souboru /etc/event.d/local-git-daemon -you put this script: +vložte tento skript: start on startup stop on shutdown @@ -530,181 +691,181 @@ you put this script: /opt/git/ respawn -For security reasons, it is strongly encouraged to have this daemon run as a user with read-only permissions to the repositories – you can easily do this by creating a new user 'git-ro' and running the daemon as them. For the sake of simplicity we’ll simply run it as the same 'git' user that Gitosis is running as. +Z bezpečnostních důvodů důrazně doporučujeme, aby byl tento démon spuštěn jako uživatel, který má k repozitářům oprávnění pouze pro čtení. To lze snadno zajistit vytvořením nového uživatele 'git-ro' a spuštěním démona v jeho roli. My ho pro zjednodušení spustíme jako uživatele 'git', kterého už využívá nástroj Gitosis. -When you restart your machine, your Git daemon will start automatically and respawn if it goes down. To get it running without having to reboot, you can run this: +Při restartování počítače se démon Git spustí automaticky. V případě pádu démona bude jeho činnost automaticky obnovena. Pokud nechcete počítač restartovat, spusťte tento příkaz: initctl start local-git-daemon -On other systems, you may want to use `xinetd`, a script in your `sysvinit` system, or something else — as long as you get that command daemonized and watched somehow. +V jiných systémech možná budete chtít použít `xinetd`, skript systému `sysvinit`, nebo podobný skript – můžete-li spouštět příkaz démonizovaný a sledovaný. -Next, you have to tell your Gitosis server which repositories to allow unauthenticated Git server-based access to. If you add a section for each repository, you can specify the ones from which you want your Git daemon to allow reading. If you want to allow Git protocol access for your iphone project, you add this to the end of the `gitosis.conf` file: +Dále budete muset svému serveru Gitosis sdělit, k jakým repozitářům si přejete povolit neautentizovaný serverový přístup Git. Pokud pro každý repozitář přidáte sekci, můžete určit repozitáře, z nichž si přejete dovolit démonovi Git načítat data. Chcete-li povolit přístup přes protokol Git k projektu `iphone_project`, přidejte ho na konec souboru `gitosis.conf`: [repo iphone_project] daemon = yes -When that is committed and pushed up, your running daemon should start serving requests for the project to anyone who has access to port 9418 on your server. +Po zapsání a odeslání této revize by měl váš spuštěný démon začít obsluhovat požadavky k projektu pro všechny, kdo mají přístup k portu 9418 na vašem serveru. -If you decide not to use Gitosis, but you want to set up a Git daemon, you’ll have to run this on each project you want the Git daemon to serve: +Pokud nechcete používat Gitosis, ale chcete nastavit démona Git, budete muset u každého projektu, který chcete obsluhovat démonem Git, provést následující: $ cd /path/to/project.git $ touch git-daemon-export-ok -The presence of that file tells Git that it’s OK to serve this project without authentication. +Přítomnost tohoto souboru systému Git sděluje, že si přejete obsluhovat tento projekt bez ověřování totožnosti. -Gitosis can also control which projects GitWeb shows. First, you need to add something like the following to the `/etc/gitweb.conf` file: +Gitosis může také určovat, jaké projekty bude zobrazovat GitWeb. Nejprve budete muset do souboru `/etc/gitweb.conf` vložit následující: $projects_list = "/home/git/gitosis/projects.list"; $projectroot = "/home/git/repositories"; $export_ok = "git-daemon-export-ok"; @git_base_url_list = ('git://gitserver'); -You can control which projects GitWeb lets users browse by adding or removing a `gitweb` setting in the Gitosis configuration file. For instance, if you want the iphone project to show up on GitWeb, you make the `repo` setting look like this: +Vložením nebo odstraněním nastavení `gitweb` z konfiguračního souboru Gitosis můžete určit, které projekty dovolí GitWeb uživatelům procházet. Pokud například chcete, aby GitWeb zobrazoval `iphone_project`, upravíte nastavení `repo` do této podoby: [repo iphone_project] daemon = yes gitweb = yes -Now, if you commit and push the project, GitWeb will automatically start showing your iphone project. +Pokud teď zapíšete a odešlete projekt, GitWeb začne automaticky zobrazovat `iphone_project`. -## Hosted Git ## +## Hostování projektů Git ## -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. +Pokud nemáte chuť absolvovat celý proces nastavování vlastního serveru Git, existuje několik možností hostování vašich projektů Git na externím specializovaném hostingovém místě. Toto řešení vám nabízí celou řadu výhod. Hostingové místo má většinou velmi rychlé nastavení, snadno se na něm zakládají projekty a nevyžaduje od vás správu ani monitoring serveru. Dokonce i když budete nastavovat a spouštět interně svůj vlastní server, budete možná přesto chtít použít veřejné hostingové místo pro otevřený zdrojový kód – komunita open source vývojářů si vás tak snáze najde a pomůže vám. -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: +V dnešní době můžete vybírat z velkého počtu možností hostingu. Každá má jiné klady a zápory. Aktuální seznam těchto míst najdete na následující stránce: - http://git.or.cz/gitwiki/GitHosting + https://git.wiki.kernel.org/index.php/GitHosting -Because we can’t cover all of them, and because I happen to work at one of them, we’ll use this section to walk through setting up an account and creating a new project at GitHub. This will give you an idea of what is involved. +Protože se tu nemůžeme věnovat všem možnostem a protože shodou okolností na jednom hostingovém místě pracuji, využijeme tuto část k tomu, abychom ukázali nastavení účtu a vytvoření nového projektu na serveru GitHub. Získáte tak představu, co všechno vás čeká. -GitHub is by far the largest open source Git hosting site and it’s also one of the very few that offers both public and private hosting options so you can keep your open source and private commercial code in the same place. In fact, we used GitHub to privately collaborate on this book. +GitHub je zdaleka největším hostingovým místem pro projekty Git s otevřeným zdrojovým kódem a je zároveň jedním z velmi mála těch, která nabízejí možnosti jak veřejného, tak soukromého hostingu. Na jednom místě tak můžete mít uložen jak otevřený zdrojový kód, tak soukromý komerční kód. Možnost soukromého použití GitHub jsme ostatně používali pro spolupráci při vzniku této knihy. ### GitHub ### -GitHub is slightly different than most code-hosting sites in the way that it namespaces projects. Instead of being primarily based on the project, GitHub is user centric. That means when I host my `grit` project on GitHub, you won’t find it at `github.com/grit` but instead at `github.com/schacon/grit`. There is no canonical version of any project, which allows a project to move from one user to another seamlessly if the first author abandons the project. +GitHub se nepatrně liší od většiny míst hostujících zdrojový kód ve způsobu, jak zachází se jmenným prostorem projektů. Ten tu není založen primárně na názvu projektu, ale na uživateli. To znamená, že pokud budu hostovat svůj projekt `grit` na serveru GitHub, nenajdete ho na adrese `github.com/grit`, ale jako `github.com/schacon/grit`. Neexistuje tu žádná standardní verze projektu, která by umožňovala kompletní přechod projektu z jednoho uživatele na druhého, jestliže první autor projekt ukončí. -GitHub is also a commercial company that charges for accounts that maintain private repositories, but anyone can quickly get a free account to host as many open source projects as they want. We’ll quickly go over how that is done. +GitHub je zároveň komerční společnost, jejíž finanční příjmy plynou z účtů spravujících soukromé repozitáře. Kdokoli si však může rychle založit bezplatný účet k hostování libovolného počtu projektů s otevřeným kódem. A právě u účtů se teď na chvíli zastavíme. -### Setting Up a User Account ### +### Založení uživatelského účtu ### -The first thing you need to do is set up a free user account. If you visit the Pricing and Signup page at `http://github.com/plans` and click the "Sign Up" button on the Free account (see figure 4-2), you’re taken to the signup page. +První věcí, kterou budete muset udělat, je vytvoření bezplatného uživatelské účtu. Jestliže na stránce „Pricing and Signup“ (`https://github.com/pricing`) kliknete u bezplatného účtu (Free) na tlačítko „Sign Up“ (viz obrázek 4-2), přejdete na registrační stránku. Insert 18333fig0402.png -Figure 4-2. The GitHub plan page +Obrázek 4-2. Výběr typu účtu na serveru GitHub -Here you must choose a username that isn’t yet taken in the system and enter an e-mail address that will be associated with the account and a password (see Figure 4-3). +Tady si budete muset zvolit uživatelské jméno, které zatím není v systému obsazeno, a zadat e-mailovou adresu, která bude přiřazena k účtu a heslu (viz obrázek 4-3). -Insert 18333fig0403.png -Figure 4-3. The GitHub user signup form +Insert 18333fig0403.png +Obrázek 4-3. Registrační formulář na serveru GitHub -If you have it available, this is a good time to add your public SSH key as well. We covered how to generate a new key earlier, in the "Simple Setups" section. Take the contents of the public key of that pair, and paste it into the SSH Public Key text box. Clicking the "explain ssh keys" link takes you to detailed instructions on how to do so on all major operating systems. -Clicking the "I agree, sign me up" button takes you to your new user dashboard (see Figure 4-4). +Po vyplnění osobních údajů nadešel vhodný čas k vložení vašeho veřejného klíče SSH. Jak vygenerovat nový klíč, jsme popsali výše, v části 4.3. Vezměte obsah veřejného klíče z daného páru a vložte ho do textového pole „SSH Public Key“. Kliknutím na odkaz „explain ssh keys“ přejdete na stránku s podrobnými instrukcemi, jak klíč vložit ve všech hlavních operačních systémech. +Kliknutím na tlačítko „I agree, sign me up“ přejdete na svůj nový uživatelský ovládací panel (viz obrázek 4-4). -Insert 18333fig0404.png -Figure 4-4. The GitHub user dashboard +Insert 18333fig0404.png +Obrázek 4-4. Uživatelský ovládací panel na serveru GitHub -Next you can create a new repository. +Jako další krok následuje vytvoření nového repozitáře. -### Creating a New Repository ### +### Vytvoření nového repozitáře ### -Start by clicking the "create a new one" link next to Your Repositories on the user dashboard. You’re taken to the Create a New Repository form (see Figure 4-5). +Začněte kliknutím na odkaz „create a new one“ (vytvořit nový) vedle nadpisu „Your Repositories“ na ovládacím panelu. Přejdete tím na formulář „Create a New Repository“ (viz obrázek 4-5). -Insert 18333fig0405.png -Figure 4-5. Creating a new repository on GitHub +Insert 18333fig0405.png +Obrázek 4-5. Vytvoření nového repozitáře na serveru GitHub -All you really have to do is provide a project name, but you can also add a description. When that is done, click the "Create Repository" button. Now you have a new repository on GitHub (see Figure 4-6). +Vše, co tu opravdu musíte udělat, je zadat název projektu. Kromě toho můžete přidat i jeho popis. Poté klikněte na tlačítko „Create Repository“ (Vytvořit repozitář). Nyní máte na serveru GitHub vytvořen nový repozitář (viz obrázek 4-6). -Insert 18333fig0406.png -Figure 4-6. GitHub project header information +Insert 18333fig0406.png +Obrázek 4-6. Záhlaví s informacemi o projektu na serveru GitHub -Since you have no code there yet, GitHub will show you instructions for how create a brand-new project, push an existing Git project up, or import a project from a public Subversion repository (see Figure 4-7). +Protože v něm ještě nemáte uložen žádný kód, GitHub vám nabízí instrukce, jak vytvořit zcela nový projekt, odeslat sem existující projekt Git nebo naimportovat projekt z veřejného repozitáře Subversion (viz obrázek 4-7). -Insert 18333fig0407.png -Figure 4-7. Instructions for a new repository +Insert 18333fig0407.png +Obrázek 4-7. Instrukce k novému repozitáři -These instructions are similar to what we’ve already gone over. To initialize a project if it isn’t already a Git project, you use +Tyto instrukce jsou podobné těm, které jsme už uváděli. K inicializaci projektu, pokud to ještě není projekt Git, použijte příkaz: $ git init $ git add . $ git commit -m 'initial commit' -When you have a Git repository locally, add GitHub as a remote and push up your master branch: +Pokud už máte lokální repozitář Git, přidejte GitHub jako vzdálený server a odešlete na něj svou hlavní větev: $ git remote add origin git@github.com:testinguser/iphone_project.git $ git push origin master -Now your project is hosted on GitHub, and you can give the URL to anyone you want to share your project with. In this case, it’s `http://github.com/testinguser/iphone_project`. You can also see from the header on each of your project’s pages that you have two Git URLs (see Figure 4-8). +Nyní je váš projekt hostován na serveru GitHub a vy můžete dát adresu URL komukoli, s kým chcete svůj projekt sdílet. V tomto případě je adresa `http://github.com/testinguser/iphone_project`. V záhlaví na stránce všech vašich projektů si můžete všimnout, že máte dvě adresy URL (viz obrázek 4-8). -Insert 18333fig0408.png -Figure 4-8. Project header with a public URL and a private URL +Insert 18333fig0408.png +Obrázek 4-8. Záhlaví projektu s veřejnou a soukromou adresou URL -The Public Clone URL is a public, read-only Git URL over which anyone can clone the project. Feel free to give out that URL and post it on your web site or what have you. +„Public Clone URL“ je veřejná adresa Git pouze pro čtení, na níž si může váš projekt kdokoli naklonovat. Nemusíte se bát poskytnout tuto adresu ostatním nebo ji třeba zveřejnit na svých webových stránkách. -The Your Clone URL is a read/write SSH-based URL that you can read or write over only if you connect with the SSH private key associated with the public key you uploaded for your user. When other users visit this project page, they won’t see that URL—only the public one. +„Your Clone URL“ je SSH adresa ke čtení a zápisu, přes níž můžete číst a zapisovat. To však pouze v případě, že se připojíte se soukromým klíčem SSH asociovaným s veřejným klíčem, který jste zadali pro svého uživatele. Navštíví-li tuto stránku projektu ostatní uživatelé, tuto adresu URL neuvidí, zobrazí se jim pouze veřejná adresa. -### Importing from Subversion ### +### Import ze systému Subversion ### -If you have an existing public Subversion project that you want to import into Git, GitHub can often do that for you. At the bottom of the instructions page is a link to a Subversion import. If you click it, you see a form with information about the import process and a text box where you can paste in the URL of your public Subversion project (see Figure 4-9). +Máte-li existující veřejný projekt Subversion, který byste rádi importovali do systému Git, GitHub vám s tím obvykle pomůže. Dole na stránce s instrukcemi najdete odkaz na import ze systému Subversion. Pokud na něj kliknete, zobrazí se formulář s informacemi o importu a textové pole, kam můžete vložit adresu URL svého veřejného projektu Subversion (viz obrázek 4-9). -Insert 18333fig0409.png -Figure 4-9. Subversion importing interface +Insert 18333fig0409.png +Obrázek 4-9. Rozhraní importu ze systému Subversion -If your project is very large, nonstandard, or private, this process probably won’t work for you. In Chapter 7, you’ll learn how to do more complicated manual project imports. +Proces nejspíš nebude fungovat, pokud je váš projekt příliš velký, nestandardní nebo soukromý. V kapitole 7 se dostaneme k tomu, jak lze ručně importovat složitější projekty. -### Adding Collaborators ### +### Přidávání spolupracovníků ### -Let’s add the rest of the team. If John, Josie, and Jessica all sign up for accounts on GitHub, and you want to give them push access to your repository, you can add them to your project as collaborators. Doing so will allow pushes from their public keys to work. +Nyní přidáme zbytek vašeho týmu. Pokud si John, Josie i Jessica zaregistrují účty na serveru GitHub a vy jim chcete udělit oprávnění k odesílání dat do svého repozitáře, můžete je do svého projektu přidat jako spolupracovníky. Spolupracovníci mohou odesílat data i na základě svých veřejných klíčů. -Click the "edit" button in the project header or the Admin tab at the top of the project to reach the Admin page of your GitHub project (see Figure 4-10). +Kliknutím na tlačítko „edit“ v záhlaví projektu nebo na záložce „Admin“ v horní části projektu se dostanete na stránku správy vašeho projektu na serveru GitHub (viz obrázek 4-10). -Insert 18333fig0410.png -Figure 4-10. GitHub administration page +Insert 18333fig0410.png +Obrázek 4-10. Stránka správy na serveru GitHub -To give another user write access to your project, click the “Add another collaborator” link. A new text box appears, into which you can type a username. As you type, a helper pops up, showing you possible username matches. When you find the correct user, click the Add button to add that user as a collaborator on your project (see Figure 4-11). +Chcete-li k svému projektu poskytnout oprávnění pro zápis ještě dalším uživatelům, klikněte na odkaz „Add another collaborator“ (Přidat dalšího spolupracovníka). Zobrazí se nové textové pole, do nějž můžete zadat jméno uživatele. Během psaní se zobrazuje pomocník, který vám navrhuje možná dokončení uživatelského jména. Poté, co najdete správného uživatele, klikněte na tlačítko „Add“. Tím uživatele přidáte jako spolupracovníka na svém projektu (viz obrázek 4-11). -Insert 18333fig0411.png -Figure 4-11. Adding a collaborator to your project +Insert 18333fig0411.png +Obrázek 4-11. Přidání spolupracovníka do projektu -When you’re finished adding collaborators, you should see a list of them in the Repository Collaborators box (see Figure 4-12). +Po přidání všech spolupracovníků byste měli vidět jejich seznam v poli „Repository Collaborators“ (viz obrázek 4-12). -Insert 18333fig0412.png -Figure 4-12. A list of collaborators on your project +Insert 18333fig0412.png +Obrázek 4-12. Seznam spolupracovníků na projektu -If you need to revoke access to individuals, you can click the "revoke" link, and their push access will be removed. For future projects, you can also copy collaborator groups by copying the permissions of an existing project. +Pokud potřebujete oprávnění pro některého z uživatelů zrušit, klikněte na odkaz „revoke“. Tím odstraníte jeho oprávnění k odesílání dat. U budoucích projektů budete také moci zkopírovat skupinu spolupracovníků zkopírováním oprávnění z existujícího projektu. -### Your Project ### +### Váš projekt ### -After you push your project up or have it imported from Subversion, you have a main project page that looks something like Figure 4-13. +Po odeslání projektu nebo jeho naimportování ze systému Subversion budete mít hlavní stránku projektu, která bude vypadat přibližně jako na obrázku 4-13. -Insert 18333fig0413.png -Figure 4-13. A GitHub main project page +Insert 18333fig0413.png +Obrázek 4-13. Hlavní stránka projektu na serveru GitHub -When people visit your project, they see this page. It contains tabs to different aspects of your projects. The Commits tab shows a list of commits in reverse chronological order, similar to the output of the `git log` command. The Network tab shows all the people who have forked your project and contributed back. The Downloads tab allows you to upload project binaries and link to tarballs and zipped versions of any tagged points in your project. The Wiki tab provides a wiki where you can write documentation or other information about your project. The Graphs tab has some contribution visualizations and statistics about your project. The main Source tab that you land on shows your project’s main directory listing and automatically renders the README file below it if you have one. This tab also shows a box with the latest commit information. +Navštíví-li váš projekt ostatní uživatelé, tuto stránku uvidí. Obsahuje několik záložek k různým aspektům vašich projektů. Záložka „Commits“ zobrazuje seznam revizí v obráceném chronologickém pořadí, podobně jako výstup příkazu `git log`. Záložka „Network“ zobrazuje všechny uživatele, kteří se odštěpili od vašeho projektu a zase do něj přispěli. Záložka „Downloads“ umožňuje nahrávat binární soubory k projektu a přidávat odkazy na tarbally a komprimované verze všech míst ve vašem projektu, které jsou označeny značkou (tagem). Záložka „Wiki“ vám nabízí stránku wiki, kam můžete napsat dokumentaci nebo jiné informace ke svému projektu. Záložka „Graphs“ graficky zobrazuje některé příspěvky a statistiky k vašemu projektu. Hlavní záložka „Source“, na níž se stránka otvírá, zobrazuje hlavní adresář vašeho projektu, a máte-li soubor README, automaticky pod adresářem projektu zobrazí jeho obsah. Tato záložka obsahuje rovněž pole s informacemi o poslední zapsané revizi. -### Forking Projects ### +### Štěpení projektů ### -If you want to contribute to an existing project to which you don’t have push access, GitHub encourages forking the project. When you land on a project page that looks interesting and you want to hack on it a bit, you can click the "fork" button in the project header to have GitHub copy that project to your user so you can push to it. +Chcete-li přispět do existujícího projektu, k němuž nemáte oprávnění pro odesílání, umožňuje GitHub rozštěpení projektu. Pokud se dostanete na zajímavou stránku projektu a chtěli byste se do projektu zapojit, můžete kliknout na tlačítko „fork“ (rozštěpit -- doslova vidlička) v záhlaví projektu a GitHub vytvoří kopii projektu pro vašeho uživatele. Do ní pak můžete odesílat revize. -This way, projects don’t have to worry about adding users as collaborators to give them push access. People can fork a project and push to it, and the main project maintainer can pull in those changes by adding them as remotes and merging in their work. +Díky tomu se projekty nemusí starat o přidávání uživatelů do role spolupracovníků, kteří by měli právo zápisu. Uživatelé mohou projekt rozštěpit a odesílat do něj revize. Hlavní správce projektu tyto změny natáhne tím, že je přidá jako vzdálené repozitáře a začlení jejich data. -To fork a project, visit the project page (in this case, mojombo/chronic) and click the "fork" button in the header (see Figure 4-14). +Chcete-li projekt rozštěpit, přejděte na stránku projektu (v tomto případě mojombo/chronic) a klikněte na tlačítko „fork“ v záhlaví (viz obrázek 4-14). -Insert 18333fig0414.png -Figure 4-14. Get a writable copy of any repository by clicking the "fork" button. +Insert 18333fig0414.png +Obrázek 4-14. Zapisovatelnou kopii jakéhokoli repozitáře získáte kliknutím na tlačítko „fork“. -After a few seconds, you’re taken to your new project page, which indicates that this project is a fork of another one (see Figure 4-15). +Po několika sekundách přejdete na novou stránku svého projektu, která oznamuje, že je tento projekt odštěpen (fork) z jiného projektu (viz obrázek 4-15). -Insert 18333fig0415.png -Figure 4-15. Your fork of a project +Insert 18333fig0415.png +Obrázek 4-15. Vaše rozštěpení projektu -### GitHub Summary ### +### Shrnutí k serveru GitHub ### -That’s all we’ll cover about GitHub, but it’s important to note how quickly you can do all this. You can create an account, add a new project, and push to it in a matter of minutes. If your project is open source, you also get a huge community of developers who now have visibility into your project and may well fork it and help contribute to it. At the very least, this may be a way to get up and running with Git and try it out quickly. +O serveru GitHub je to vše. Ještě jednou bych rád zdůraznil, že všechny tyto kroky lze provést opravdu velmi rychle. Vytvoření účtu, přidání nového projektu a odeslání prvních revizí je záležitostí několika minut. Je-li váš projekt otevřený zdrojový kód, získáte také obrovskou komunitu vývojářů, kteří nyní váš projekt uvidí, mohou ho rozštěpit a pomoci vám svými příspěvky. V neposlední řadě může být toto způsob, jak rychle zprovoznit a vyzkoušet systém Git. -## Summary ## +## Shrnutí ## -You have several options to get a remote Git repository up and running so that you can collaborate with others or share your work. +Existuje několik možností, jak vytvořit a zprovoznit vzdálený repozitář Git tak, abyste mohli spolupracovat s ostatními uživateli nebo sdílet svou práci. -Running your own server gives you a lot of control and allows you to run the server within your own firewall, but such a server generally requires a fair amount of your time to set up and maintain. If you place your data on a hosted server, it’s easy to set up and maintain; however, you have to be able to keep your code on someone else’s servers, and some organizations don’t allow that. +Provoz vlastního serveru vám dává celou řadu možností kontroly a umožňuje provozovat server za vaším firewallem. Nastavení a správa takového serveru však obvykle bývají časově náročné. Umístíte-li data na hostovaný server, je jejich nastavení a správa jednoduchá. Svůj zdrojový kód však v takovém případě ukládáte na cizím serveru, což některé organizace nedovolují. -It should be fairly straightforward to determine which solution or combination of solutions is appropriate for you and your organization. +Teď už byste se měli umět rozhodnout, které řešení nebo jaká kombinace řešení se pro vás a pro vaši organizaci hodí. diff --git a/cs/05-distributed-git/01-chapter5.markdown b/cs/05-distributed-git/01-chapter5.markdown index 6ceb05c30..da4cbf4b8 100644 --- a/cs/05-distributed-git/01-chapter5.markdown +++ b/cs/05-distributed-git/01-chapter5.markdown @@ -1,76 +1,76 @@ -# Distributed Git # +# Distribuovaný charakter systému 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. +Nyní máte vytvořen vzdálený repozitář Git jako místo, kde mohou všichni vývojáři sdílet zdrojový kód, a znáte základní příkazy systému Git pro práci v lokálním prostředí. Je čas podívat se na využití některých distribuovaných postupů, které vám Git nabízí. -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. +V této kapitole se dozvíte, jak pracovat se systémem Git v distribuovaném prostředí jako přispěvatel a zprostředkovatel integrace. Naučíte se tedy, jak úspěšně přispívat svým kódem do projektů a jak to učinit co nejjednodušeji pro vás i správce projektu. Dále se dozvíte, jak efektivně spravovat projekt, do nějž přispívá velký počet vývojářů. -## Distributed Workflows ## +## Distribuované pracovní postupy ## -Unlike Centralized Version Control Systems (CVCSs), the distributed nature of Git allows you to be far more flexible in how developers collaborate on projects. In centralized systems, every developer is a node working more or less equally on a central hub. In Git, however, every developer is potentially both a node and a hub — that is, every developer can both contribute code to other repositories and maintain a public repository on which others can base their work and which they can contribute to. This opens a vast range of workflow possibilities for your project and/or your team, so I’ll cover a few common paradigms that take advantage of this flexibility. I’ll go over the strengths and possible weaknesses of each design; you can choose a single one to use, or you can mix and match features from each. +Na rozdíl od centralizovaných systémů správy verzí (CVCS) umožňuje distribuovaný charakter systému Git mnohem větší flexibilitu při spolupráci vývojářů na projektech. V centralizovaných systémech představuje každý vývojář samostatný uzel, pracující více či méně na stejné úrovni vůči centrálnímu úložišti. Naproti tomu je v systému Git každý vývojář potenciálním uzlem i úložištěm, každý vývojář může přispívat kódem do jiných repozitářů i spravovat veřejný repozitář, na němž mohou ostatní založit svou práci a do nějž mohou přispívat. Tím se pro váš projekt a váš tým otvírá široké spektrum pracovních postupů. Zkusíme se tedy podívat na pár častých přístupů, které tato flexibilita umožňuje. Uvedeme jejich přednosti i eventuální slabiny. Budete si moci vybrat některý z postupů nebo je navzájem kombinovat a spojovat jejich vlastnosti. -### Centralized Workflow ### +### Centralizovaný pracovní postup ### -In centralized systems, there is generally a single collaboration model—the centralized workflow. One central hub, or repository, can accept code, and everyone synchronizes their work to it. A number of developers are nodes — consumers of that hub — and synchronize to that one place (see Figure 5-1). +V centralizovaných systémech je většinou možný pouze jediný model spolupráce, tzv. centralizovaný pracovní postup. Jedno centrální úložiště (hub) nebo repozitář přijímá zdrojový kód a každý podle něj synchronizuje svou práci. Několik vývojářů představuje jednotlivé uzly (nodes) – uživatele centrálního místa – které se podle tohoto místa synchronizují (viz obrázek 5-1). -Insert 18333fig0501.png -Figure 5-1. Centralized workflow +Insert 18333fig0501.png +Obrázek 5-1. Centralizovaný pracovní postup -This means that if two developers clone from the hub and both make changes, the first developer to push their changes back up can do so with no problems. The second developer must merge in the first one’s work before pushing changes up, so as not to overwrite the first developer’s changes. This concept is true in Git as it is in Subversion (or any CVCS), and this model works perfectly in Git. +To znamená, že pokud dva vývojáři klonují z centrálního úložiště a oba provedou změny, jen první z nich, který odešle své změny, to může provést bez komplikací. Druhý vývojář musí před odesláním svých změn začlenit práci prvního vývojáře do své, aby nepřepsal jeho změny. Tento koncept platí jak pro Git, tak pro Subversion (popř. jakýkoli CVCS). I v systému Git funguje bez problémů. -If you have a small team or are already comfortable with a centralized workflow in your company or team, you can easily continue using that workflow with Git. Simply set up a single repository, and give everyone on your team push access; Git won’t let users overwrite each other. If one developer clones, makes changes, and then tries to push their changes while another developer has pushed in the meantime, the server will reject that developer’s changes. They will be told that they’re trying to push non-fast-forward changes and that they won’t be able to do so until they fetch and merge. -This workflow is attractive to a lot of people because it’s a paradigm that many are familiar and comfortable with. +Pokud pracujete v malém týmu nebo už jste ve své společnosti nebo ve svém týmu zvyklí na centralizovaný pracovní postup, můžete v něm beze všeho pokračovat. Jednoduše vytvořte repozitář a přidělte všem ze svého týmu oprávnění k odesílání dat. Git neumožní uživatelům, aby se navzájem přepisovali. Pokud některý z vývojářů naklonuje data, provede změny a poté se je pokusí odeslat, a jiný vývojář mezitím odeslal svoje revize, server tyto změny odmítne. Git vývojáři při odmítnutí sdělí, že se pokouší odeslat změny, které nesměřují „rychle vpřed“, což není možné provést, dokud nevyzvedne a nezačlení (fetch and merge) stávající data z repozitáře. +Tento pracovní postup může být pro mnoho lidí zajímavý, protože je to schéma, které jsou zvyklí používat a jsou s ním spokojeni. -### Integration-Manager Workflow ### +### Pracovní postup s integračním manažerem ### -Because Git allows you to have multiple remote repositories, it’s possible to have a workflow where each developer has write access to their own public repository and read access to everyone else’s. This scenario often includes a canonical repository that represents the "official" project. To contribute to that project, you create your own public clone of the project and push your changes to it. Then, you can send a request to the maintainer of the main project to pull in your changes. They can add your repository as a remote, test your changes locally, merge them into their branch, and push back to their repository. The process works as follow (see Figure 5-2): +Protože Git umožňuje, abyste měli několik vzdálených repozitářů, lze použít pracovní postup, kdy má každý vývojář oprávnění k zápisu do vlastního veřejného repozitáře a oprávnění pro čtení k repozitářům všech ostatních. Tento scénář často zahrnuje jeden standardní repozitář, který reprezentuje „oficiální“ projekt. Chcete-li do tohoto projektu přispívat, vytvořte vlastní veřejný klon projektu a odešlete do něj změny, které jste provedli. Poté odešlete správci hlavního projektu žádost, aby do projektu natáhl vaše změny. Správce může váš repozitář přidat jako vzdálený repozitář, lokálně otestovat vaše změny, začlenit je do své větve a odeslat zpět do svého repozitáře. Postup práce je následující (viz obrázek 5-2): -1. The project maintainer pushes to their public repository. -2. A contributor clones that repository and makes changes. -3. The contributor pushes to their own public copy. -4. The contributor sends the maintainer an e-mail asking them to pull changes. -5. The maintainer adds the contributor’s repo as a remote and merges locally. -6. The maintainer pushes merged changes to the main repository. +1. Správce projektu odešle data do svého veřejného repozitáře. +2. Přispěvatel naklonuje tento repozitář a provede změny. +3. Přispěvatel odešle změny do své vlastní veřejné kopie. +4. Přispěvatel pošle správci e-mail s žádostí, aby natáhl změny do projektu. +5. Správce přidá repozitář přispěvatele jako vzdálený repozitář a provede lokální začlenění. +6. Správce odešle začleněné změny do hlavního repozitáře. -Insert 18333fig0502.png -Figure 5-2. Integration-manager workflow +Insert 18333fig0502.png +Obrázek 5-2. Pracovní postup s integračním manažerem -This is a very common workflow with sites like GitHub, where it’s easy to fork a project and push your changes into your fork for everyone to see. One of the main advantages of this approach is that you can continue to work, and the maintainer of the main repository can pull in your changes at any time. Contributors don’t have to wait for the project to incorporate their changes — each party can work at their own pace. +Tento pracovní postup je velmi rozšířený na serverech jako je GitHub, kde je snadné rozštěpit projekt a odeslat změny do své odštěpené části, kde jsou pro každého k nahlédnutí. Jednou z hlavních předností tohoto postupu je, že můžete pracovat bez přerušení a správce hlavního repozitáře může natáhnout vaše změny do projektu, kdykoli uzná za vhodné. Přispěvatelé nemusí čekat, až budou jejich změny začleněny do projektu – každá strana může pracovat svým tempem. -### Dictator and Lieutenants Workflow ### +### Pracovní postup s diktátorem a poručíky ### -This is a variant of a multiple-repository workflow. It’s generally used by huge projects with hundreds of collaborators; one famous example is the Linux kernel. Various integration managers are in charge of certain parts of the repository; they’re called lieutenants. All the lieutenants have one integration manager known as the benevolent dictator. The benevolent dictator’s repository serves as the reference repository from which all the collaborators need to pull. The process works like this (see Figure 5-3): +Jedná se o variantu pracovního postupu s více repozitáři. Většinou se používá u obřích projektů se stovkami spolupracovníků. Možná nejznámějším příkladem je vývoj jádra Linuxu. Několik různých integračních manažerů odpovídá za konkrétní části repozitáře – říká se jím poručíci (lieutenants). Všichni poručíci mají jednoho integračního manažera, kterému se říká „benevolentní diktátor“. Repozitář benevolentního diktátora slouží jako referenční repozitář, z nějž všichni spolupracovníci musí stahovat data. Postup práce je následující (viz obrázek 5-3): -1. Regular developers work on their topic branch and rebase their work on top of master. The master branch is that of the dictator. -2. Lieutenants merge the developers’ topic branches into their master branch. -3. The dictator merges the lieutenants’ master branches into the dictator’s master branch. -4. The dictator pushes their master to the reference repository so the other developers can rebase on it. +1. Stálí vývojáři pracují na svých tematických větvích a přeskládávají svou práci na vrchol hlavní větve. Hlavní větev je větev diktátora. +2. Poručíci začleňují tematické větve vývojářů do svých hlavních větví. +3. Diktátor začleňuje hlavní větve poručíků do své hlavní větve. +4. Diktátor odesílá svou hlavní větev do referenčního repozitáře, aby si na jeho základě mohli ostatní vývojáři přeskládat data. -Insert 18333fig0503.png -Figure 5-3. Benevolent dictator workflow +Insert 18333fig0503.png +Obrázek 5-3. Pracovní postup s benevolentním diktátorem -This kind of workflow isn’t common but can be useful in very big projects or in highly hierarchical environments, because as it allows the project leader (the dictator) to delegate much of the work and collect large subsets of code at multiple points before integrating them. +Tento typ pracovního postupu není sice obvyklý, ale může být užitečný u velmi velkých projektů nebo v silně hierarchizovaných prostředích, neboť umožňuje, aby vedoucí projektu (diktátor) velkou část práce delegoval. Pak sbírá velké kusy kódu, které integruje. -These are some commonly used workflows that are possible with a distributed system like Git, but you can see that many variations are possible to suit your particular real-world workflow. Now that you can (I hope) determine which workflow combination may work for you, I’ll cover some more specific examples of how to accomplish the main roles that make up the different flows. +Toto jsou tedy některé z běžně používaných pracovních postupů, které můžete využít v distribuovaných systémech, jako je například Git. Uvidíte ale, že na pozadí vašich konkrétních potřeb v reálných situacích lze vytvořit celou řadu variací na tyto postupy. Nyní, když už se (jak doufám) dokážete rozhodnout, která kombinace postupů pro vás bude ta nejvhodnější, ukážeme si některé konkrétní příklady, jak lze rozdělit hlavní role, z nichž vyplývají jednotlivé postupy práce. -## Contributing to a Project ## +## Přispívání do projektu ## -You know what the different workflows are, and you should have a pretty good grasp of fundamental Git usage. In this section, you’ll learn about a few common patterns for contributing to a project. +V tuto chvíli už znáte různé pracovní postupy a na velmi solidní úrovni byste měli ovládat základy systému Git. V této části ukážeme několik běžných schémat, podle nichž může přispívání do projektů probíhat. -The main difficulty with describing this process is that there are a huge number of variations on how it’s done. Because Git is very flexible, people can and do work together many ways, and it’s problematic to describe how you should contribute to a project — every project is a bit different. Some of the variables involved are active contributor size, chosen workflow, your commit access, and possibly the external contribution method. +Popsat tento proces není právě jednoduché, protože existuje obrovské množství variací, jak lze do projektů přispívat. Vzhledem k velké flexibilitě systému Git mohou uživatelé spolupracovat mnoha různými způsoby, a není proto snadné popsat, jak byste měli do projektu přispívat. Každý projekt je trochu jiný. Mezi proměnné patří v tomto procesu počet aktivních přispěvatelů, zvolený pracovní postup, vaše oprávnění pro odesílání revizí a případně i metoda externího přispívání. -The first variable is active contributor size. How many users are actively contributing code to this project, and how often? In many instances, you’ll have two or three developers with a few commits a day, or possibly less for somewhat dormant projects. For really large companies or projects, the number of developers could be in the thousands, with dozens or even hundreds of patches coming in each day. This is important because with more and more developers, you run into more issues with making sure your code applies cleanly or can be easily merged. Changes you submit may be rendered obsolete or severely broken by work that is merged in while you were working or while your changes were waiting to be approved or applied. How can you keep your code consistently up to date and your patches valid? +První proměnnou je počet aktivních přispěvatelů. Kolik uživatelů aktivně přispívá kódem do projektu a jak často? V mnoha případech budete mít dva nebo tři vývojáře přispívající několika málo revizemi denně, u projektů s nízkou prioritou možná i méně. V opravdu velkých společnostech a u velkých projektů se může počet vývojářů vyšplhat do tisíců a počet revizí se může pohybovat v desítkách i stovkách záplat denně. To je důležité zejména z toho hlediska, že s rostoucím počtem vývojářů se také zvětšují starosti s tím, aby byl kód aplikován čistě a aby ho bylo možné snadno začlenit. U změn, které postoupíte vyšší instanci, může docházet k zastarávání nebo vážnému narušení jinými daty, která byla začleněna během vaší práce nebo ve chvíli, kdy vaše změny čekaly na schválení či aplikaci. Jak lze důsledně udržovat kód aktuální a záplaty vždy platné? -The next variable is the workflow in use for the project. Is it centralized, with each developer having equal write access to the main codeline? Does the project have a maintainer or integration manager who checks all the patches? Are all the patches peer-reviewed and approved? Are you involved in that process? Is a lieutenant system in place, and do you have to submit your work to them first? +Další proměnnou je pracovní postup, který se u projektu využívá. Probíhá vývoj centralizovaně, má každý vývojář stejné oprávnění pro zápis do hlavní linie kódu? Má projekt svého správce nebo integračního manažera, který kontroluje všechny záplaty? Jsou všechny záplaty odborně posuzovány a schvalovány? Jste součástí tohoto procesu? Jsou součástí systému poručíci a musíte všechnu svou práci odesílat nejprve jim? -The next issue is your commit access. The workflow required in order to contribute to a project is much different if you have write access to the project than if you don’t. If you don’t have write access, how does the project prefer to accept contributed work? Does it even have a policy? How much work are you contributing at a time? How often do you contribute? +Další otázkou je vaše oprávnění k zapisování revizí. Pracovní postup při přispívání do projektu se velmi liší podle toho, zda máte, či nemáte oprávnění k zápisu do projektu. Pokud oprávnění k zápisu nemáte, jakou metodu projekt zvolí pro přijímání příspěvků? Má k tomu vůbec vyvinutou metodiku? Kolik práce představuje jeden váš příspěvek? A jak často přispíváte? -All these questions can affect how you contribute effectively to a project and what workflows are preferred or available to you. I’ll cover aspects of each of these in a series of use cases, moving from simple to more complex; you should be able to construct the specific workflows you need in practice from these examples. +Všechny tyto otázky mohou mít vliv na efektivní přispívání do projektu a určují, jaký pracovní postup je vůbec možný a který bude upřednostněn. Všem těmto aspektům bych se teď chtěl věnovat na sérii praktických příkladů, od těch jednodušších až po složité. Z uvedených příkladů byste si pak měli být schopni odvodit vlastní pracovní postup, který budete v praxi využívat. -### Commit Guidelines ### +### Pravidla pro revize ### -Before you start looking at the specific use cases, here’s a quick note about commit messages. Having a good guideline for creating commits and sticking to it makes working with Git and collaborating with others a lot easier. The Git project provides a document that lays out a number of good tips for creating commits from which to submit patches — you can read it in the Git source code in the `Documentation/SubmittingPatches` file. +Než se podíváme na konkrétní praktické příklady, přidávám malou poznámku o zprávách k revizím. Není od věci stanovit si a dodržovat kvalitní pravidla pro vytváření revizí. Výrazně vám mohou usnadnit práci v systému Git a spolupráci s kolegy. Projekt Git obsahuje dokument, v němž je navržena celá řada dobrých tipů pro vytváření revizí, z nichž se skládají jednotlivé záplaty. Dokument najdete ve zdrojovém kódu systému Git v souboru `Documentation/SubmittingPatches`. -First, you don’t want to submit any whitespace errors. Git provides an easy way to check for this — before you commit, run `git diff --check`, which identifies possible whitespace errors and lists them for you. Here is an example, where I’ve replaced a red terminal color with `X`s: +Především nechcete, aby revize obsahovaly chyby způsobené prázdnými znaky. Git nabízí snadný způsob, jak tyto chyby zkontrolovat. Před zapsáním revize zadejte příkaz `git diff --check`, který zkontroluje prázdné znaky a vypíše vám jejich seznam. Zde uvádím jeden příklad, v němž jsem červenou barvu terminálu nahradil znaky `X`: $ git diff --check lib/simplegit.rb:5: trailing whitespace. @@ -80,63 +80,63 @@ First, you don’t want to submit any whitespace errors. Git provides an easy wa lib/simplegit.rb:26: trailing whitespace. + def command(git_cmd)XXXX -If you run that command before committing, you can tell if you’re about to commit whitespace issues that may annoy other developers. +Spustíte-li tento příkaz před zapsáním revize, můžete se rozhodnout, zda chcete zapsat i problematické prázdné znaky, které mohou obtěžovat ostatní vývojáře. -Next, try to make each commit a logically separate changeset. If you can, try to make your changes digestible — don’t code for a whole weekend on five different issues and then submit them all as one massive commit on Monday. Even if you don’t commit during the weekend, use the staging area on Monday to split your work into at least one commit per issue, with a useful message per commit. If some of the changes modify the same file, try to use `git add --patch` to partially stage files (covered in detail in Chapter 6). The project snapshot at the tip of the branch is identical whether you do one commit or five, as long as all the changes are added at some point, so try to make things easier on your fellow developers when they have to review your changes. This approach also makes it easier to pull out or revert one of the changesets if you need to later. Chapter 6 describes a number of useful Git tricks for rewriting history and interactively staging files — use these tools to help craft a clean and understandable history. +Dále se snažte provádět každou revizi jako logicky samostatný soubor změn. Pokud je to možné, snažte se provádět stravitelné změny. Není právě ideální pracovat celý víkend na pěti různých problémech a v pondělí je všechny najednou odeslat v jedné velké revizi. I pokud nebudete během víkendu zapisovat revize, využijte v pondělí oblasti připravených změn a rozdělte svou práci alespoň do stejného počtu revizí, kolik je řešených problémů, a přidejte k nim vysvětlující zprávy. Pokud některé změny modifikují tentýž soubor, zkuste použít příkaz `git add --patch` a připravit soubory k zapsání po částech (podrobnosti v kapitole 6). Snímek projektu na vrcholu větve bude stejný, ať zapíšete jednu revizi, nebo pět (za předpokladu, že vložíte všechny změny). Snažte se proto usnadnit práci svým kolegům, kteří – možná – budou vaše změny kontrolovat. Díky tomuto přístupu také později snáze vyjmete nebo vrátíte některou z provedených změn, bude-li to třeba. Kapitola 6 popisuje několik užitečných triků, jak v systému Git přepsat historii a jak interaktivně připravovat soubory k zapsání. Používejte tyto nástroje k udržení čisté a srozumitelné historie. -The last thing to keep in mind is the commit message. Getting in the habit of creating quality commit messages makes using and collaborating with Git a lot easier. 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. It’s also a good idea to use the imperative present tense in these messages. In other words, use commands. Instead of "I added tests for" or "Adding tests for," use "Add tests for." -Here is a template originally written by Tim Pope at tpope.net: +Poslední věcí, na niž se vyplatí soustředit pozornost, jsou zprávy k revizím. Pokud si zvyknete vytvářet k revizím kvalitní zprávy, bude pro vás práce a kooperace v systému Git mnohem jednodušší. Zpráva by měla obvykle začínat samostatným řádkem o maximálně 50 znacích, v níž stručně popíšete soubor provedených změn. Za ním by měl následovat prázdný řádek a za ním podrobnější popis revize. Projekt Git vyžaduje, aby podrobnější popis revize obsahoval vaši motivaci ke změnám a vymezil jejich implementaci na pozadí předchozích kroků. Tuto zásadu je dobré dodržovat. Vytváříte-li zprávy k revizím v angličtině, často se také doporučuje používat rozkazovací způsob, tj. příkazy. Místo „I added tests for“ nebo „Adding tests for“ používejte raději „Add tests for“. +Zde uvádíme vzor, jehož autorem je Tim Pope a v originále je k nalezení na stránkách tpope.net: - Short (50 chars or less) summary of changes + Krátké (do 50 znaků) shrnutí změn - More detailed explanatory text, if necessary. Wrap it to about 72 - characters or so. In some contexts, the first line is treated as the - subject of an email and the rest of the text as the body. The blank - line separating the summary from the body is critical (unless you omit - the body entirely); tools like rebase can get confused if you run the - two together. + Podrobnější popis revize, je-li třeba. Snažte se nepřesáhnout + zhruba 72 znaků. V některých kontextech je první řádek koncipován + jako předmět e-mailu a zbytek textu jako jeho tělo. Prázdný řádek + oddělující shrnutí od těla zprávy je nezbytně nutný (pokud + nehodláte vypustit celé tělo). Spojení obou částí může zmást + některé nástroje, např. přeskládání. - Further paragraphs come after blank lines. + Další odstavce následují za prázdným řádkem. - - Bullet points are okay, too + - Můžete používat i odrážky. - - Typically a hyphen or asterisk is used for the bullet, preceded by a - single space, with blank lines in between, but conventions vary here + - Jako odrážka se nejčastěji používá pomlčka nebo hvězdička, před ně se vkládá + jedna mezera, mezi body výčtu prázdný řádek, avšak úzus tu není jednotný. -If all your commit messages look like this, things will be a lot easier for you and the developers you work with. The Git project has well-formatted commit messages — I encourage you to run `git log --no-merges` there to see what a nicely formatted project-commit history looks like. +Budou-li takto vypadat všechny vaše zprávy k revizím, usnadníte tím práci sobě i svým spolupracovníkům. Projekt Git obsahuje kvalitně naformátované zprávy k revizím. Mohu vám doporučit, abyste v něm zkusili zadat příkaz `git log --no-merges` a podívali se, jak vypadá pěkně naformátovaná historie revizí projektu. -In the following examples, and throughout most of this book, for the sake of brevity I don’t format messages nicely like this; instead, I use the `-m` option to `git commit`. Do as I say, not as I do. +Já v následujících příkladech stejně jako ve většině případů v této knize v rámci zestručnění neformátuji zprávy podle uvedených zásad, naopak používám parametr `-m` za příkazem `git commit`. Řiďte se, prosím, podle toho, co říkám, ne podle toho, co dělám. -### Private Small Team ### +### Malý soukromý tým ### -The simplest setup you’re likely to encounter is a private project with one or two other developers. By private, I mean closed source — not read-accessible to the outside world. You and the other developers all have push access to the repository. +Nejjednodušší sestavou, s níž se pravděpodobně setkáte, je soukromý projekt, na němž kromě vás pracují ještě jeden nebo dva vývojáři. Soukromým projektem myslím uzavřený zdrojový kód – okolní svět k němu nemá oprávnění pro čtení. Vy a vaši ostatní vývojáři máte všichni oprávnění odesílat změny do repozitáře. -In this environment, you can follow a workflow similar to what you might do when using Subversion or another centralized system. You still get the advantages of things like offline committing and vastly simpler branching and merging, but the workflow can be very similar; the main difference is that merges happen client-side rather than on the server at commit time. -Let’s see what it might look like when two developers start to work together with a shared repository. The first developer, John, clones the repository, makes a change, and commits locally. (I’m replacing the protocol messages with `...` in these examples to shorten them somewhat.) +V takovém prostředí můžete uplatnit podobný pracovní postup, na jaký jste možná zvyklí ze systému Subversion nebo jiného centralizovaného systému. Se systémem Git ale budete stále ještě ve výhodě v takových ohledech, jako je zapisování revizí offline a podstatně snazší větvení a slučování. Pracovní postup však bude velmi podobný. Hlavním rozdílem je to, že slučování probíhá na straně klienta, ne během zapisování revize na straně serveru. +Podívejme se, jak to může vypadat, když dva vývojáři začnou spolupracovat na projektu se sdíleným repozitářem. První vývojář, John, naklonuje repozitář, provede změny a zapíše lokální revizi. (V následujících příkladech nahrazuji zprávy protokolů třemi tečkami, abych je trochu zkrátil.) # John's Machine $ git clone john@githost:simplegit.git Initialized empty Git repository in /home/john/simplegit/.git/ ... $ cd simplegit/ - $ vim lib/simplegit.rb + $ vim lib/simplegit.rb $ git commit -am 'removed invalid default value' [master 738ee87] removed invalid default value 1 files changed, 1 insertions(+), 1 deletions(-) -The second developer, Jessica, does the same thing — clones the repository and commits a change: +Druhý vývojář, Jessica, učiní totéž – naklonuje repozitář a zapíše provedené změny: # Jessica's Machine $ git clone jessica@githost:simplegit.git Initialized empty Git repository in /home/jessica/simplegit/.git/ ... $ cd simplegit/ - $ vim TODO + $ vim TODO $ git commit -am 'add reset task' [master fbff5bc] add reset task 1 files changed, 1 insertions(+), 0 deletions(-) -Now, Jessica pushes her work up to the server: +Jessica nyní odešle svou práci na server: # Jessica's Machine $ git push origin master @@ -144,7 +144,7 @@ Now, Jessica pushes her work up to the server: To jessica@githost:simplegit.git 1edee6b..fbff5bc master -> master -John tries to push his change up, too: +Také John se pokusí odeslat své změny na server: # John's Machine $ git push origin master @@ -152,48 +152,48 @@ John tries to push his change up, too: ! [rejected] master -> master (non-fast forward) error: failed to push some refs to 'john@githost:simplegit.git' -John isn’t allowed to push because Jessica has pushed in the meantime. This is especially important to understand if you’re used to Subversion, because you’ll notice that the two developers didn’t edit the same file. Although Subversion automatically does such a merge on the server if different files are edited, in Git you must merge the commits locally. John has to fetch Jessica’s changes and merge them in before he will be allowed to push: +John nyní nesmí odeslat revize, protože mezitím odeslala své změny Jessica. To je třeba si uvědomit, zejména pokud jste zvyklí na systém Subversion. Oba vývojáři totiž neupravovali stejný soubor. Přestože Subversion provádí takové sloučení na serveru automaticky, pokud byly upraveny různé soubory, v systému Git musíte provést sloučení lokálně. John musí vyzvednout změny, které provedla Jessica, a začlenit je do své práce, než ji bude moci odeslat: $ git fetch origin ... From john@githost:simplegit + 049d078...fbff5bc master -> origin/master -At this point, John’s local repository looks something like Figure 5-4. +V tomto okamžiku vypadá Johnův lokální repozitář jako na obrázku 5-4. -Insert 18333fig0504.png -Figure 5-4. John’s initial repository +Insert 18333fig0504.png +Obrázek 5-4. Johnův výchozí repozitář -John has a reference to the changes Jessica pushed up, but he has to merge them into his own work before he is allowed to push: +John má referenci ke změnám, které odeslala Jessica, ale než bude moci sám odeslat svá data, bude muset začlenit její práci: $ git merge origin/master Merge made by recursive. TODO | 1 + 1 files changed, 1 insertions(+), 0 deletions(-) -The merge goes smoothly — John’s commit history now looks like Figure 5-5. +Sloučení probíhá hladce, Johnova historie revizí teď vypadá jako na obrázku 5-5. -Insert 18333fig0505.png -Figure 5-5. John’s repository after merging origin/master +Insert 18333fig0505.png +Obrázek 5-5. Johnův repozitář po začlenění větve `origin/master` -Now, John can test his code to make sure it still works properly, and then he can push his new merged work up to the server: +John nyní může otestovat svůj kód, aby se ujistil, že stále pracuje správně, a pak může odeslat svou novou sloučenou práci na server: $ git push origin master ... To john@githost:simplegit.git fbff5bc..72bbc59 master -> master -Finally, John’s commit history looks like Figure 5-6. +Johnova historie revizí bude nakonec vypadat jako na obrázku 5-6. -Insert 18333fig0506.png -Figure 5-6. John’s history after pushing to the origin server +Insert 18333fig0506.png +Obrázek 5-6. Johnova historie po odeslání revize na server origin -In the meantime, Jessica has been working on a topic branch. She’s created a topic branch called `issue54` and done three commits on that branch. She hasn’t fetched John’s changes yet, so her commit history looks like Figure 5-7. +Jessica mezitím pracovala na tematické větvi. Vytvořila tematickou větev s názvem `issue54` a zapsala do ní tři revize. Zatím ještě nevyzvedla Johnovy změny, a proto její historie revizí vypadá jako na obrázku 5-7. -Insert 18333fig0507.png -Figure 5-7. Jessica’s initial commit history +Insert 18333fig0507.png +Obrázek 5-7. Výchozí historie revizí – Jessica -Jessica wants to sync up with John, so she fetches: +Jessica chce synchronizovat svou práci s Johnem, a proto vyzvedne jeho data: # Jessica's Machine $ git fetch origin @@ -201,12 +201,12 @@ Jessica wants to sync up with John, so she fetches: From jessica@githost:simplegit fbff5bc..72bbc59 master -> origin/master -That pulls down the work John has pushed up in the meantime. Jessica’s history now looks like Figure 5-8. +Tím stáhne práci, kterou mezitím odeslal John. Historie revizí Jessicy teď vypadá jako na obrázku 5-8. -Insert 18333fig0508.png -Figure 5-8. Jessica’s history after fetching John’s changes +Insert 18333fig0508.png +Obrázek 5-8. Historie Jessicy po vyzvednutí Johnových změn -Jessica thinks her topic branch is ready, but she wants to know what she has to merge her work into so that she can push. She runs `git log` to find out: +Jessica považuje svou tematickou větev za dokončenou, ale chce vědět, do čeho má svou práci začlenit, aby mohla změny odeslat. Spustí proto příkaz `git log`: $ git log --no-merges origin/master ^issue54 commit 738ee872852dfaa9d6634e0dea7a324040193016 @@ -215,13 +215,13 @@ Jessica thinks her topic branch is ready, but she wants to know what she has to removed invalid default value -Now, Jessica can merge her topic work into her master branch, merge John’s work (`origin/master`) into her `master` branch, and then push back to the server again. First, she switches back to her master branch to integrate all this work: +Jessica nyní může začlenit tematickou větev do své větve `master`, začlenit (merge) i Johnovu práci (`origin/master`) do své větve `master` a vše odeslat zpět na server. Nejprve se přepne zpět na svou větev `master`, aby do ní mohla vše integrovat: $ git checkout master Switched to branch "master" Your branch is behind 'origin/master' by 2 commits, and can be fast-forwarded. -She can merge either `origin/master` or `issue54` first — they’re both upstream, so the order doesn’t matter. The end snapshot should be identical no matter which order she chooses; only the history will be slightly different. She chooses to merge in `issue54` first: +Jako první může začlenit buď větev `origin/master` nebo `issue54`. Obě směřují vpřed, a tak jejich pořadí nehraje žádnou roli. Konečný snímek bude stejný, ať zvolí jakékoli pořadí, mírně se bude lišit jen historie revizí. Jessica se rozhodne začlenit jako první větev `issue54`: $ git merge issue54 Updating fbff5bc..4af4298 @@ -230,7 +230,7 @@ She can merge either `origin/master` or `issue54` first — they’re both upstr lib/simplegit.rb | 6 +++++- 2 files changed, 6 insertions(+), 1 deletions(-) -No problems occur; as you can see it, was a simple fast-forward. Now Jessica merges in John’s work (`origin/master`): +Tento postup je bezproblémový. Jak vidíte, šlo o jednoduchý posun „rychle vpřed“. Nyní Jessica začlení Johnovu práci (`origin/master`): $ git merge origin/master Auto-merging lib/simplegit.rb @@ -238,35 +238,35 @@ No problems occur; as you can see it, was a simple fast-forward. Now Jessica mer lib/simplegit.rb | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-) -Everything merges cleanly, and Jessica’s history looks like Figure 5-9. +Začlenění proběhne čistě a historie Jessicy bude vypadat jako na obrázku 5-9. -Insert 18333fig0509.png -Figure 5-9. Jessica’s history after merging John’s changes +Insert 18333fig0509.png +Obrázek 5-9. Historie Jessicy po začlenění Johnových změn -Now `origin/master` is reachable from Jessica’s `master` branch, so she should be able to successfully push (assuming John hasn’t pushed again in the meantime): +Větev `origin/master` teď má Jessica dostupnou ze své větve `master`, takže může svou práci úspěšně odeslat (za předpokladu, že John mezitím neodeslal další revize): $ git push origin master ... To jessica@githost:simplegit.git 72bbc59..8059c15 master -> master -Each developer has committed a few times and merged each other’s work successfully; see Figure 5-10. +Všichni vývojáři zapsali několik revizí a úspěšně začlenili práci ostatních do své – viz obrázek 5-10. -Insert 18333fig0510.png -Figure 5-10. Jessica’s history after pushing all changes back to the server +Insert 18333fig0510.png +Obrázek 5-10. Historie Jessicy po odeslání všech změn zpět na server -That is one of the simplest workflows. You work for a while, generally in a topic branch, and merge into your master branch when it’s ready to be integrated. When you want to share that work, you merge it into your own master branch, then fetch and merge `origin/master` if it has changed, and finally push to the `master` branch on the server. The general sequence is something like that shown in Figure 5-11. +Toto je jeden z nejjednodušších pracovních postupů. Po určitou dobu pracujete, obvykle na nějaké tematické větvi, a když je připravena k integraci, začleníte ji do své větve `master`. Chcete-li tuto práci sdílet, začleníte ji do své větve `master`. Poté vyzvednete (fetch) a začleníte (merge) větev `origin/master`, jestliže se změnila. Nakonec odešlete všechna data do větve `master` na serveru. Obecná posloupnost kroků je naznačena na obrázku 5-11. -Insert 18333fig0511.png -Figure 5-11. General sequence of events for a simple multiple-developer Git workflow +Insert 18333fig0511.png +Obrázek 5-11. Obecná posloupnost kroků u jednoduchého pracovního postupu s více vývojáři v systému Git -### Private Managed Team ### +### Soukromý řízený tým ### -In this next scenario, you’ll look at contributor roles in a larger private group. You’ll learn how to work in an environment where small groups collaborate on features and then those team-based contributions are integrated by another party. +V následujícím scénáři se podíváme na role přispěvatelů ve větší soukromé skupině. Naučíte se, jak pracovat v prostředí, v němž na jednotlivých úkolech spolupracují malé skupiny a tyto týmové příspěvky jsou poté integrovány druhou stranou. -Let’s say that John and Jessica are working together on one feature, while Jessica and Josie are working on a second. In this case, the company is using a type of integration-manager workflow where the work of the individual groups is integrated only by certain engineers, and the `master` branch of the main repo can be updated only by those engineers. In this scenario, all work is done in team-based branches and pulled together by the integrators later. +Řekněme, že John a Jessica spolupracují na jednom úkolu a Jessica a Josie spolupracují na jiném. Společnost v tomto případě používá typ pracovního postupu s integračním manažerem, kdy práci jednotlivých skupin integrují pouze někteří technici a větev `master` hlavního repozitáře mohou aktualizovat pouze oni. V tomto scénáři se veškerá práce provádí ve větvích jednotlivých týmů a později je spojována zprostředkovateli integrace. -Let’s follow Jessica’s workflow as she works on her two features, collaborating in parallel with two different developers in this environment. Assuming she already has her repository cloned, she decides to work on `featureA` first. She creates a new branch for the feature and does some work on it there: +Sledujme pracovní postup Jessicy pracující na dvou úkolech a spolupracující v tomto prostředí paralelně s dvěma různými vývojáři. Protože už má naklonovaný repozitář, rozhodne se pracovat nejprve na úkolu A – `featureA`. Vytvoří si pro něj novou větev a udělá v ní určité penzum práce. # Jessica's Machine $ git checkout -b featureA @@ -276,21 +276,21 @@ Let’s follow Jessica’s workflow as she works on her two features, collaborat [featureA 3300904] add limit to log function 1 files changed, 1 insertions(+), 1 deletions(-) -At this point, she needs to share her work with John, so she pushes her `featureA` branch commits up to the server. Jessica doesn’t have push access to the `master` branch — only the integrators do — so she has to push to another branch in order to collaborate with John: +V tomto okamžiku potřebuje sdílet svou práci s Johnem, a tak odešle revize své větve `featureA` na server. Jessica nemá oprávnění pro odesílání dat do větve `master` (ten mají pouze zprostředkovatelé integrace), a proto musí své revize odeslat do jiné větve, aby mohla s Johnem spolupracovat: $ git push origin featureA ... To jessica@githost:simplegit.git * [new branch] featureA -> featureA -Jessica e-mails John to tell him that she’s pushed some work into a branch named `featureA` and he can look at it now. While she waits for feedback from John, Jessica decides to start working on `featureB` with Josie. To begin, she starts a new feature branch, basing it off the server’s `master` branch: +Jessica pošle Johnovi e-mail s informací, že odeslala svou práci do větve pojmenované `featureA` a že se na ni může podívat. Zatímco čeká na zpětnou vazbu od Johna, rozhodne se, že začne pracovat spolu s Josie na úkolu `featureB`. Začne tím, že založí novou větev, která bude založena na větvi `master` ze serveru: # Jessica's Machine $ git fetch origin $ git checkout -b featureB origin/master Switched to a new branch "featureB" -Now, Jessica makes a couple of commits on the `featureB` branch: +Jessica nyní vytvoří několik revizí ve větvi `featureB`: $ vim lib/simplegit.rb $ git commit -am 'made the ls-tree function recursive' @@ -301,19 +301,19 @@ Now, Jessica makes a couple of commits on the `featureB` branch: [featureB 8512791] add ls-files 1 files changed, 5 insertions(+), 0 deletions(-) -Jessica’s repository looks like Figure 5-12. +Repozitář Jessicy vypadá jako na obrázku 5-12. -Insert 18333fig0512.png -Figure 5-12. Jessica’s initial commit history +Insert 18333fig0512.png +Obrázek 5-12. Výchozí historie revizí – Jessica -She’s ready to push up her work, but gets an e-mail from Josie that a branch with some initial work on it was already pushed to the server as `featureBee`. Jessica first needs to merge those changes in with her own before she can push to the server. She can then fetch Josie’s changes down with `git fetch`: +Jessica je připravena odeslat svou práci, ale dostane e-mail od Josie, že již na server odeslala větev `featureBee`, v níž už je část práce hotová. Než bude Jessica moci odeslat svou práci na server, bude do ní nejprve muset začlenit práci Josie. Změny, které Josie provedla, vyzvedne příkazem `git fetch`: $ git fetch origin ... From jessica@githost:simplegit * [new branch] featureBee -> origin/featureBee -Jessica can now merge this into the work she did with `git merge`: +Nyní může Jessica začlenit tyto změny do své práce pomocí příkazu `git merge`: $ git merge origin/featureBee Auto-merging lib/simplegit.rb @@ -321,23 +321,23 @@ Jessica can now merge this into the work she did with `git merge`: lib/simplegit.rb | 4 ++++ 1 files changed, 4 insertions(+), 0 deletions(-) -There is a bit of a problem — she needs to push the merged work in her `featureB` branch to the `featureBee` branch on the server. She can do so by specifying the local branch followed by a colon (:) followed by the remote branch to the `git push` command: +Tady nastává určitý problém. Musí odeslat práci začleněnou ve své větvi `featureB` do větve `featureBee` na serveru. Může tak učinit příkazem `git push` s určením lokální větve, za níž bude následovat dvojtečka (:) a za ní vzdálená větev: $ git push origin featureB:featureBee ... To jessica@githost:simplegit.git fba9af8..cd685d1 featureB -> featureBee -This is called a _refspec_. See Chapter 9 for a more detailed discussion of Git refspecs and different things you can do with them. +Říká se tomu *refspec*. Více o vzorcích refspec systému Git a různých možnostech, k nimž je lze využít, najdete v kapitole 9. -Next, John e-mails Jessica to say he’s pushed some changes to the `featureA` branch and ask her to verify them. She runs a `git fetch` to pull down those changes: +Poté pošle John Jessice e-mail, že odeslal několik změn do větve `featureA`, a poprosí ji, aby je ověřila. Jessica spustí příkaz `git fetch`, jímž tyto změny stáhne. $ git fetch origin ... From jessica@githost:simplegit 3300904..aad881d featureA -> origin/featureA -Then, she can see what has been changed with `git log`: +Poté si může příkazem `git log` prohlédnout, co všechno bylo změněno: $ git log origin/featureA ^featureA commit aad881d154acdaeb2b6b18ea0e827ed8a6d671e6 @@ -346,7 +346,7 @@ Then, she can see what has been changed with `git log`: changed log output to 30 from 25 -Finally, she merges John’s work into her own `featureA` branch: +Nakonec začlení Johnovu práci do své vlastní větve `featureA`: $ git checkout featureA Switched to branch "featureA" @@ -356,36 +356,36 @@ Finally, she merges John’s work into her own `featureA` branch: lib/simplegit.rb | 10 +++++++++- 1 files changed, 9 insertions(+), 1 deletions(-) -Jessica wants to tweak something, so she commits again and then pushes this back up to the server: +Jessica by ráda něco vylepšila, a proto vytvoří novou revizi a odešle ji zpět na server: $ git commit -am 'small tweak' - [featureA ed774b3] small tweak + [featureA 774b3ed] small tweak 1 files changed, 1 insertions(+), 1 deletions(-) $ git push origin featureA ... To jessica@githost:simplegit.git - 3300904..ed774b3 featureA -> featureA + 3300904..774b3ed featureA -> featureA -Jessica’s commit history now looks something like Figure 5-13. +Historie revizí Jessicy bude nyní vypadat jako na obrázku 5-13. -Insert 18333fig0513.png -Figure 5-13. Jessica’s history after committing on a feature branch +Insert 18333fig0513.png +Obrázek 5-13. Historie Jessicy po zapsání revizí do větve s úkolem -Jessica, Josie, and John inform the integrators that the `featureA` and `featureBee` branches on the server are ready for integration into the mainline. After they integrate these branches into the mainline, a fetch will bring down the new merge commits, making the commit history look like Figure 5-14. +Jessica, Josie a John pošlou zprávu zprostředkovatelům integrace, že větve `featureA` a `featureBee` jsou na serveru připraveny k integraci do hlavní linie. Poté, co budou tyto větve do hlavní linie integrovány, vyzvednutím dat bude možné stáhnout nové revize vzniklé začleněním změn a historie revizí bude vypadat jako na obrázku 5-14. -Insert 18333fig0514.png -Figure 5-14. Jessica’s history after merging both her topic branches +Insert 18333fig0514.png +Obrázek 5-14. Historie Jessicy po začlenění obou jejích tematických větví -Many groups switch to Git because of this ability to have multiple teams working in parallel, merging the different lines of work late in the process. The ability of smaller subgroups of a team to collaborate via remote branches without necessarily having to involve or impede the entire team is a huge benefit of Git. The sequence for the workflow you saw here is something like Figure 5-15. +Mnoho skupin přechází na systém Git právě kvůli této možnosti paralelní spolupráce několika týmů a následného slučování různých linií práce. Možnost, aby několik menších podskupin jednoho týmu spolupracovalo prostřednictvím vzdálených větví a aby si práce nevyžádala účast celého týmu nebo nebránila ostatním v jiné práci, je velkou devízou systému Git. Posloupnost kroků vypadá v případě pracovního postupu, který jsme si právě ukázali, jako na obrázku 5-15. -Insert 18333fig0515.png -Figure 5-15. Basic sequence of this managed-team workflow +Insert 18333fig0515.png +Obrázek 5-15. Základní posloupnost kroků u pracovního postupu v řízeném týmu -### Public Small Project ### +### Malý veřejný projekt ### -Contributing to public projects is a bit different. Because you don’t have the permissions to directly update branches on the project, you have to get the work to the maintainers some other way. This first example describes contributing via forking on Git hosts that support easy forking. The repo.or.cz and GitHub hosting sites both support this, and many project maintainers expect this style of contribution. The next section deals with projects that prefer to accept contributed patches via e-mail. +Přispívání do veřejných projektů se poněkud liší. Protože nemáte oprávnění aktualizovat větve projektu přímo, musíte svou práci doručit správcům jinak. První příklad popisuje, jak se přispívá s využitím rozštěpení na hostitelských serverech Git, které podporují snadné štěpení. Jak server repo.or.cz, tak místa pro hostování podporují štěpení a mnoho správců projektů tento styl přispívání vyžaduje. Další část se pak zabývá projekty, u nichž je upřednostňováno doručování záplat e-mailem. -First, you’ll probably want to clone the main repository, create a topic branch for the patch or patch series you’re planning to contribute, and do your work there. The sequence looks basically like this: +Nejprve patrně bude nutné, abyste naklonovali hlavní repozitář, vytvořili tematickou větev pro záplatu nebo sérii záplat, které hodláte vytvořit, a udělali v nich zamýšlenou práci. Posloupnost příkazů bude tedy následující: $ git clone (url) $ cd project @@ -395,19 +395,19 @@ First, you’ll probably want to clone the main repository, create a topic branc $ (work) $ git commit -You may want to use `rebase -i` to squash your work down to a single commit, or rearrange the work in the commits to make the patch easier for the maintainer to review — see Chapter 6 for more information about interactive rebasing. +Možná budete chtít využít příkaz `rebase -i` a zkomprimovat svou práci do jediné revize nebo přeorganizovat práci v revizích tak, aby byla kontrola záplaty pro správce jednodušší – další informace o interaktivním přeskládání najdete v kapitole 6. -When your branch work is finished and you’re ready to contribute it back to the maintainers, go to the original project page and click the "Fork" button, creating your own writable fork of the project. You then need to add in this new repository URL as a second remote, in this case named `myfork`: +Až budete s prací ve větvi hotovi a budete ji chtít poslat zpět správcům, přejděte na původní stránku projektu a klikněte na tlačítko „Fork“, jímž vytvoříte vlastní odštěpenou větev projektu, do níž budete moci zapisovat. Poté bude třeba, abyste tuto novou adresu URL repozitáře přidali jako druhý vzdálený repozitář, v tomto případě pojmenovaný `myfork`: $ git remote add myfork (url) -You need to push your work up to it. It’s easiest to push the remote branch you’re working on up to your repository, rather than merging into your master branch and pushing that up. The reason is that if the work isn’t accepted or is cherry picked, you don’t have to rewind your master branch. If the maintainers merge, rebase, or cherry-pick your work, you’ll eventually get it back via pulling from their repository anyhow: +Do něj teď musíte odeslat svou práci. Lepším řešením bude odeslat vzdálenou větev, na níž pracujete, do svého repozitáře, než ji začlenit do hlavní větve a tu pak celou odeslat. Důvod je prostý: pokud nebude vaše práce přijata nebo bude převzata částečně, nebudete muset vracet změny začleněné do vaší hlavní větve. Pokud správci začlení či přeskládají vaši práci (nebo její část), získáte ji zpět stažením z repozitáře: $ git push myfork featureA -When your work has been pushed up to your fork, you need to notify the maintainer. This is often called a pull request, and you can either generate it via the website — GitHub has a "pull request" button that automatically messages the maintainer — or run the `git request-pull` command and e-mail the output to the project maintainer manually. +Až svou práci odešlete do odštěpené větve, budete na ni muset upozornit správce. Tomu se říká „žádost o natažení“ (angl. pull request). Můžete ji vygenerovat buď na webové stránce – server GitHub má tlačítko „pull request“, které automaticky odešle správci upozornění – nebo můžete zadat příkaz `git request-pull` a jeho výstup e-mailem ručně odeslat správci projektu. -The `request-pull` command takes the base branch into which you want your topic branch pulled and the Git repository URL you want them to pull from, and outputs a summary of all the changes you’re asking to be pulled in. For instance, if Jessica wants to send John a pull request, and she’s done two commits on the topic branch she just pushed up, she can run this: +Příkaz `request-pull` vezme základní větev (základnu), do níž chcete natáhnout svou tematickou větev, a adresu URL repozitáře Git, z nějž chcete práci natáhnout, a vytvoří shrnutí všech změn, které by měl správce podle vaší žádosti natáhnout. Pokud chce například Jessica poslat Johnovi žádost o natažení a vytvořila předtím dvě revize v tematické větvi, kterou právě odeslala, může zadat tento příkaz: $ git request-pull origin/master myfork The following changes since commit 1edee6b1d61823a2de3b09c160d7080b8d1b3a40: @@ -425,9 +425,9 @@ The `request-pull` command takes the base branch into which you want your topic lib/simplegit.rb | 10 +++++++++- 1 files changed, 9 insertions(+), 1 deletions(-) -The output can be sent to the maintainer—it tells them where the work was branched from, summarizes the commits, and tells where to pull this work from. +Výstup příkazu lze odeslat správci. Sdělí mu, odkud daná větev pochází, podá mu přehled o revizích a řekne mu, odkud lze práci stáhnout. -On a project for which you’re not the maintainer, it’s generally easier to have a branch like `master` always track `origin/master` and to do your work in topic branches that you can easily discard if they’re rejected. Having work themes isolated into topic branches also makes it easier for you to rebase your work if the tip of the main repository has moved in the meantime and your commits no longer apply cleanly. For example, if you want to submit a second topic of work to the project, don’t continue working on the topic branch you just pushed up — start over from the main repository’s `master` branch: +U projektů, u nichž nejste v roli správce, je většinou jednodušší, aby vaše větev `master` stále sledovala větev `origin/master` a abyste práci prováděli v tematických větvích, jichž se můžete beze všeho vzdát v případě, že budou odmítnuty. Jednotlivé úkoly izolované v tematických větvích mají také tu výhodu, že snáze přeskládáte svou práci, jestliže se průběžně posouvá konec hlavního repozitáře a vaše revize už nelze aplikovat čistě. Pokud například chcete do projektu přispět druhým tématem, nerozvíjejte svou práci v tematické větvi, kterou jste právě odeslali. Začněte znovu od začátku z větve `master` hlavního repozitáře: $ git checkout -b featureB origin/master $ (work) @@ -436,25 +436,25 @@ On a project for which you’re not the maintainer, it’s generally easier to h $ (email maintainer) $ git fetch origin -Now, each of your topics is contained within a silo — similar to a patch queue — that you can rewrite, rebase, and modify without the topics interfering or interdepending on each other as in Figure 5-16. +Nyní mají obě vaše témata samostatný zásobník – podobně jako řada záplat – které můžete přepsat, přeskládat a upravit, aniž by se tím obě témata navzájem ovlivňovala nebo omezovala (viz obrázek 5-16). -Insert 18333fig0516.png -Figure 5-16. Initial commit history with featureB work +Insert 18333fig0516.png +Obrázek 5-16. Výchozí historie revizí s větví featureB -Let’s say the project maintainer has pulled in a bunch of other patches and tried your first branch, but it no longer cleanly merges. In this case, you can try to rebase that branch on top of `origin/master`, resolve the conflicts for the maintainer, and then resubmit your changes: +Řekněme, že správce projektu natáhl do projektu několik jiných záplat a nyní vyzkoušel vaši první větev, jenže tu už nelze čistě začlenit. V takovém případě můžete zkusit přeskládat tuto větev na vrcholu větve `origin/master`, vyřešit za správce vzniklé konflikty a poté své změny ještě jednou odeslat: $ git checkout featureA $ git rebase origin/master - $ git push –f myfork featureA + $ git push -f myfork featureA -This rewrites your history to now look like Figure 5-17. +Tím přepíšete svou historii, která teď bude vypadat jako na obrázku 5-17. -Insert 18333fig0517.png -Figure 5-17. Commit history after featureA work +Insert 18333fig0517.png +Obrázek 5-17. Historie revizí s větví featureA -Because you rebased the branch, you have to specify the `–f` to your push command in order to be able to replace the `featureA` branch on the server with a commit that isn’t a descendant of it. An alternative would be to push this new work to a different branch on the server (perhaps called `featureAv2`). +Protože jste větev přeskládali, musíte k příkazu git push přidat parametr `-f`, abyste mohli větev `featureA` na serveru nahradit revizí, která není jejím potomkem. Druhou možností je odeslat tuto novou práci do jiné větve na serveru (nazvané např. `featureAv2`). -Let’s look at one more possible scenario: the maintainer has looked at work in your second branch and likes the concept but would like you to change an implementation detail. You’ll also take this opportunity to move the work to be based off the project’s current `master` branch. You start a new branch based off the current `origin/master` branch, squash the `featureB` changes there, resolve any conflicts, make the implementation change, and then push that up as a new branch: +Podívejme se ještě na jeden pravděpodobnější scénář: Správce se podíval na práci ve vaší druhé větvi, váš koncept se mu líbí, ale rád by, abyste změnili jeden implementační detail. Vy tuto příležitost využijete zároveň k tomu, abyste práci přesunuli tak, aby byla založena na aktuálním stavu projektu ve větvi `master`. Začnete vytvořením nové větve z aktuální větve `origin/master`, zkomprimujete do ní změny z větve `featureB`, vyřešíte všechny konflikty, provedete změnu v implementaci a to vše odešlete jako novou větev: $ git checkout -b featureBv2 origin/master $ git merge --no-commit --squash featureB @@ -462,18 +462,18 @@ Let’s look at one more possible scenario: the maintainer has looked at work in $ git commit $ git push myfork featureBv2 -The `--squash` option takes all the work on the merged branch and squashes it into one non-merge commit on top of the branch you’re on. The `--no-commit` option tells Git not to automatically record a commit. This allows you to introduce all the changes from another branch and then make more changes before recording the new commit. +Parametr `--squash` (komprimovat) vezme všechnu vaši práci v začleněné větvi a zkomprimuje ji do jedné revize, která nevznikla jako výsledek sloučení a leží na vrcholu větve, na níž se právě nacházíte. Parametr `--no-commit` říká systému Git, aby revizi automaticky nezaznamenával. To vám umožní provést všechny změny z jiné větve a poté udělat více změn, než zaznamenáte novou revizi. -Now you can send the maintainer a message that you’ve made the requested changes and they can find those changes in your `featureBv2` branch (see Figure 5-18). +Nyní můžete správci oznámit, že jste provedli požadované změny a že je najde ve vaší větvi `featureBv2` (viz obrázek 5-18). -Insert 18333fig0518.png -Figure 5-18. Commit history after featureBv2 work +Insert 18333fig0518.png +Obrázek 5-18. Historie revizí s větví featureBv2 -### Public Large Project ### +### Velký veřejný projekt ### -Many larger projects have established procedures for accepting patches — you’ll need to check the specific rules for each project, because they will differ. However, many larger public projects accept patches via a developer mailing list, so I’ll go over an example of that now. +Mnoho větších projektů si vytvořilo vlastní, odlišné procedury k doručování záplat. U každého projektu se tak budete muset informovat o konkrétních pravidlech. U mnoha větších veřejných projektů se však záplaty doručují na základě poštovní konference vývojářů, a proto se teď zaměřím na tento případ. -The workflow is similar to the previous use case — you create topic branches for each patch series you work on. The difference is how you submit them to the project. Instead of forking the project and pushing to your own writable version, you generate e-mail versions of each commit series and e-mail them to the developer mailing list: +Pracovní postup je podobný jako v předchozím případě. Pro každou sérii záplat, na níž pracujete, vytvoříte samostatnou tematickou větev. Liší se to, jak je budete doručovat do projektu. Místo toho, abyste rozštěpili projekt a odeslali své změny do vlastní zapisovatelné verze, vygenerujete e-mailovou verzi každé série revizí a pošlete je e-mailem do poštovní konference vývojářů: $ git checkout -b topicA $ (work) @@ -481,15 +481,15 @@ The workflow is similar to the previous use case — you create topic branches f $ (work) $ git commit -Now you have two commits that you want to send to the mailing list. You use `git format-patch` to generate the mbox-formatted files that you can e-mail to the list — it turns each commit into an e-mail message with the first line of the commit message as the subject and the rest of the message plus the patch that the commit introduces as the body. The nice thing about this is that applying a patch from an e-mail generated with `format-patch` preserves all the commit information properly, as you’ll see more of in the next section when you apply these commits: +Nyní máte dvě revize, které chcete odeslat do poštovní konference. Pro vygenerování emailových zpráv ve formátu mbox použijte příkaz `git format-patch`. Každá revize se přetransformuje na e-mailovou zprávu, jejíž předmět bude tvořit první řádek zprávy k revizi a tělo e-mailu bude tvořeno zbytkem zprávy a samotnou záplatou. Výhodou tohoto postupu je, že aplikace záplaty z e-mailu, který byl vygenerován příkazem `format-patch`, v pořádku uchová všechny informace o revizi. Podrobněji si to ukážeme v následující části, až budeme aplikovat tyto revize: $ git format-patch -M origin/master 0001-add-limit-to-log-function.patch 0002-changed-log-output-to-30-from-25.patch -The `format-patch` command prints out the names of the patch files it creates. The `-M` switch tells Git to look for renames. The files end up looking like this: +Příkaz `format-patch` vypíše názvy souborů záplaty, kterou vytváří. Přepínač `-M` řekne systému Git, aby zkontroloval případné přejmenování. Soubory nakonec vypadají takto: - $ cat 0001-add-limit-to-log-function.patch + $ cat 0001-add-limit-to-log-function.patch From 330090432754092d704da8e76ca5c05c198e71a8 Mon Sep 17 00:00:00 2001 From: Jessica Smith Date: Sun, 6 Apr 2008 10:17:23 -0700 @@ -514,14 +514,14 @@ The `format-patch` command prints out the names of the patch files it creates. T end def ls_tree(treeish = 'master') - -- + -- 1.6.2.rc1.20.g8c5b.dirty -You can also edit these patch files to add more information for the e-mail list that you don’t want to show up in the commit message. If you add text between the `--` line and the beginning of the patch (the `lib/simplegit.rb` line), then developers can read it; but applying the patch excludes it. +Tyto soubory záplaty můžete také upravit a přidat k nim další informace určené pro seznam příjemců e-mailu, u nichž nechcete, aby byly obsaženy ve zprávě k revizi. Přidáte-li text mezi řádek `---` a začátek záplaty (řádek `lib/simplegit.rb`), vývojářům se zobrazí, ale aplikace záplaty ho obsahovat nebude. -To e-mail this to a mailing list, you can either paste the file into your e-mail program or send it via a command-line program. Pasting the text often causes formatting issues, especially with "smarter" clients that don’t preserve newlines and other whitespace appropriately. Luckily, Git provides a tool to help you send properly formatted patches via IMAP, which may be easier for you. I’ll demonstrate how to send a patch via Gmail, which happens to be the e-mail agent I use; you can read detailed instructions for a number of mail programs at the end of the aforementioned `Documentation/SubmittingPatches` file in the Git source code. +Chcete-li e-mail odeslat do poštovní konference, můžete soubor buď vložit do svého e-mailového programu, nebo ho odeslat pomocí příkazového řádku. Vložení textu může často způsobovat problémy s formátováním, zvlášť v případě některých „chytřejších“ klientů, kteří správně nezachovávají nové řádky a jiné prázdné znaky. Git naštěstí nabízí nástroj, který vám pomůže odeslat správně formátované patche pomocí protokolu IMAP. Já budu dokumentovat odeslání záplaty na příkladu Gmailu, který používám jako svého e-mailového agenta. Podrobné instrukce pro celou řadu poštovních programů najdete na konci již dříve zmíněného souboru `Documentation/SubmittingPatches` ve zdrojovém kódu systému Git. -First, you need to set up the imap section in your `~/.gitconfig` file. You can set each value separately with a series of `git config` commands, or you can add them manually; but in the end, your config file should look something like this: +Nejprve je třeba nastavit sekci „imap“ v souboru `~/.gitconfig`. Každou hodnotu můžete nastavit zvlášť pomocí série příkazů `git config` nebo můžete vložit hodnoty ručně. Na konci by ale měl váš soubor config vypadat přibližně takto: [imap] folder = "[Gmail]/Drafts" @@ -531,20 +531,39 @@ First, you need to set up the imap section in your `~/.gitconfig` file. You can port = 993 sslverify = false -If your IMAP server doesn’t use SSL, the last two lines probably aren’t necessary, and the host value will be `imap://` instead of `imaps://`. -When that is set up, you can use `git send-email` to place the patch series in the Drafts folder of the specified IMAP server: +Pokud váš server IMAP nepoužívá SSL, dva poslední řádky zřejmě nebudou vůbec třeba a hodnota hostitele bude `imap://`, a nikoli `imaps://`. +Až toto nastavení dokončíte, můžete použít příkaz `git imap-send`, jímž umístíte sérii záplat (patch) do složky Koncepty (Drafts) zadaného serveru IMAP: + + $ cat *.patch |git imap-send + Resolving imap.gmail.com... ok + Connecting to [74.125.142.109]:993... ok + Logging in... + sending 2 messages + 100% (2/2) done + +V tomto okamžiku byste měli být schopni přejít do složky Drafts, změnit pole To na mailing list, do kterého záplatu posíláte, případně pole CC na správce nebo na osobu zodpovědnou za tuto část, a odeslat. + +Záplaty můžete odesílat i přes SMTP server. Stejně jako v předchozím případu můžete nastavit sérií příkazů `git config` každou hodnotu zvlášť, nebo je můžete vložit ručně do sekce sendemail souboru `~/.gitconfig`: + + [sendemail] + smtpencryption = tls + smtpserver = smtp.gmail.com + smtpuser = user@gmail.com + smtpserverport = 587 + +Jakmile je to hotové, můžete záplaty odeslat příkazem `git send-email`: $ git send-email *.patch 0001-added-limit-to-log-function.patch 0002-changed-log-output-to-30-from-25.patch - Who should the emails appear to be from? [Jessica Smith ] + Who should the emails appear to be from? [Jessica Smith ] Emails will be sent from: Jessica Smith Who should the emails be sent to? jessica@example.com Message-ID to be used as In-Reply-To for the first email? y -Then, Git spits out a bunch of log information looking something like this for each patch you’re sending: +Git poté vytvoří log s určitými informacemi, který bude pro každou záplatu, kterou posíláte, vypadat asi takto: - (mbox) Adding cc: Jessica Smith from + (mbox) Adding cc: Jessica Smith from \line 'From: Jessica Smith ' OK. Log says: Sendmail: /usr/sbin/sendmail -i jessica@example.com @@ -559,54 +578,52 @@ Then, Git spits out a bunch of log information looking something like this for e Result: OK -At this point, you should be able to go to your Drafts folder, change the To field to the mailing list you’re sending the patch to, possibly CC the maintainer or person responsible for that section, and send it off. - -### Summary ### +### Shrnutí ### -This section has covered a number of common workflows for dealing with several very different types of Git projects you’re likely to encounter and introduced a couple of new tools to help you manage this process. Next, you’ll see how to work the other side of the coin: maintaining a Git project. You’ll learn how to be a benevolent dictator or integration manager. +V této části jsme popsali několik obvyklých pracovních postupů při přispívání do velmi odlišných typů projektů Git, s nimiž se můžete setkat. Představili jsme k nim také nové nástroje, které vám mohou v těchto procesech pomoci. V další části se na projekty podíváme z té druhé strany – ukážeme, jak může vypadat jejich správa. Dozvíte se, jak být benevolentním diktátorem nebo integračním manažerem. -## Maintaining a Project ## +## Správa projektu ## -In addition to knowing how to effectively contribute to a project, you’ll likely need to know how to maintain one. This can consist of accepting and applying patches generated via `format-patch` and e-mailed to you, or integrating changes in remote branches for repositories you’ve added as remotes to your project. Whether you maintain a canonical repository or want to help by verifying or approving patches, you need to know how to accept work in a way that is clearest for other contributors and sustainable by you over the long run. +Při práci na projektech Git možná nevystačíte jen s vědomostmi, jak do projektu efektivně přispívat. Pravděpodobně budete jednou potřebovat vědět něco i o správě projektů. Do této oblasti spadá přijímání a aplikace záplat vygenerovaných příkazem `format-patch`, které vám vývojáři poslali, nebo třeba integrace změn ve vzdálených větvích pro repozitáře, které jste do svého projektu přidali jako vzdálené repozitáře. Ať spravujete standardní repozitář, nebo pomáháte při ověřování či schvalování záplat, budete muset vědět, jak přijímat práci ostatních přispěvatelů, a to způsobem, který je pro ostatní co nejčistší a pro vás dlouhodobě udržitelný. -### Working in Topic Branches ### +### Práce v tematických větvích ### -When you’re thinking of integrating new work, it’s generally a good idea to try it out in a topic branch — a temporary branch specifically made to try out that new work. This way, it’s easy to tweak a patch individually and leave it if it’s not working until you have time to come back to it. If you create a simple branch name based on the theme of the work you’re going to try, such as `ruby_client` or something similarly descriptive, you can easily remember it if you have to abandon it for a while and come back later. The maintainer of the Git project tends to namespace these branches as well — such as `sc/ruby_client`, where `sc` is short for the person who contributed the work. -As you’ll remember, you can create the branch based off your master branch like this: +Pokud uvažujete o integraci nové práce do projektu, je většinou dobré zkusit si to v tematické větvi, tj. dočasné větvi, kterou vytvoříte konkrétně pro tento účel. Snadno tak můžete záplatu individuálně opravit, a pokud není funkční, opustit ji, dokud nebudete mít čas k její opravě. Pokud pro větev vytvoříte jednoduchý název spojený s tématem testované práce (např. `ruby_client` nebo něco obdobně popisného), snadno se na větev rozpomenete, jestliže se k ní musíte později vrátit. Správce projektů Git přiřazuje těmto větvím také jmenný prostor, např. `sc/ruby_client`, kde `sc` je zkratka pro osobu, která práci vytvořila. +Jak si vzpomínáte, můžete vytvořit větev založenou na své hlavní větvi: $ git branch sc/ruby_client master -Or, if you want to also switch to it immediately, you can use the `checkout -b` option: +Nebo pokud na ni chcete rovnou přepnout, můžete použít parametr `checkout -b`: $ git checkout -b sc/ruby_client master -Now you’re ready to add your contributed work into this topic branch and determine if you want to merge it into your longer-term branches. +Nyní tedy můžete vložit svůj příspěvek do této tematické větve a rozhodnout se, zda ho chcete začlenit do svých trvalejších větví. -### Applying Patches from E-mail ### +### Aplikace záplat z e-mailu ### -If you receive a patch over e-mail 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 e-mailed patch: with `git apply` or with `git am`. +Jestliže obdržíte e-mailem záplatu, kterou potřebujete integrovat do svého projektu, aplikujete ho nejprve do tematické větve, v níž ho vyhodnotíte. Existují dva způsoby aplikace záplaty z e-mailu: příkazem `git apply` nebo příkazem `git am`. -#### Applying a Patch with apply #### +#### Aplikace záplaty příkazem „apply“ #### -If you received the patch from someone who generated it with the `git diff` or a Unix `diff` command, you can apply it with the `git apply` command. Assuming you saved the patch at `/tmp/patch-ruby-client.patch`, you can apply the patch like this: +Pokud dostanete záplatu od někoho, kdo ji vygeneroval příkazem `git diff` nebo unixovým příkazem `diff`, můžete ho aplikovat příkazem `git apply`. Předpokládejme, že jste záplatu uložili jako `/tmp/patch-ruby-client.patch`. Aplikaci pak provedete takto: $ git apply /tmp/patch-ruby-client.patch -This modifies the files in your working directory. It’s almost identical to running a `patch -p1` command to apply the patch, although it’s more paranoid and accepts fewer fuzzy matches then patch. It also handles file adds, deletes, and renames if they’re described in the `git diff` format, which `patch` won’t do. Finally, `git apply` is an "apply all or abort all" model where either everything is applied or nothing is, whereas `patch` can partially apply patchfiles, leaving your working directory in a weird state. `git apply` is overall much more paranoid than `patch`. It won’t create a commit for you — after running it, you must stage and commit the changes introduced manually. +Tím změníte soubory ve svém pracovním adresáři. Je to téměř stejné, jako byste k aplikaci záplaty použili příkaz `patch -p1`. Tento postup je však přísnější a nepřijímá tolik přibližných shod jako příkaz patch. Poradí si také s přidanými, odstraněnými a přejmenovanými soubory, jsou-li popsány ve formátu `git diff`, což příkaz `patch` nedělá. A konečně příkaz `git apply` pracuje na principu „aplikuj vše, nebo zruš vše“. Buď jsou tedy aplikovány všechny soubory, nebo žádný. Naproti tomu příkaz `patch` může aplikovat soubory záplaty jen částečně a zanechat váš pracovní adresář v neurčitém stavu. Příkaz `git apply` je tedy celkově víc paranoidní než příkaz `patch`. Tímto příkazem ostatně ani nezapíšete revizi, po jeho spuštění budete muset připravit a zapsat provedené změny ručně. -You can also use git apply to see if a patch applies cleanly before you try actually applying it — you can run `git apply --check` with the patch: +Příkaz `git apply` můžete použít také ke kontrole, zda bude záplata aplikována čistě. V takovém případě použijte na patch příkaz `git apply --check`: - $ git apply --check 0001-seeing-if-this-helps-the-gem.patch + $ git apply --check 0001-seeing-if-this-helps-the-gem.patch error: patch failed: ticgit.gemspec:1 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. +Pokud se nezobrazí žádný výstup, záplata bude aplikována čistě. Jestliže kontrola selže, příkaz vrací nenulový návratový kód, a proto ho lze snadno používat ve skriptech. -#### Applying a Patch with am #### +#### Aplikace záplaty příkazem „am“ #### -If the contributor is a Git user and was good enough to use the `format-patch` command to generate their patch, then your job is easier because the patch contains author information and a commit message for you. If you can, encourage your contributors to use `format-patch` instead of `diff` to generate patches for you. You should only have to use `git apply` for legacy patches and things like that. +Pokud je přispěvatel uživatelem systému Git a byl natolik dobrý, že k vygenerování záplaty použil příkaz `format-patch`, budete mít usnadněnou práci, protože záplata obsahuje informace o autorovi a zprávu k revizi. Můžete-li, doporučte svým přispěvatelům, aby místo příkazu `diff` používali příkaz `format-patch`. Příkaz `git apply` je dobré používat jen pro starší záplaty a podobně. -To apply a patch generated by `format-patch`, you use `git am`. Technically, `git am` is built to read an mbox file, which is a simple, plain-text format for storing one or more e-mail messages in one text file. It looks something like this: +K aplikaci patche vygenerovaného příkazem `format-patch` použijte příkaz `git am`. Příkaz `git am` je technicky koncipován tak, aby přečetl soubor mbox, tj. formát prostého textu pro ukládání jedné či více e-mailových zpráv do jednoho textového souboru. Vypadá například takto: From 330090432754092d704da8e76ca5c05c198e71a8 Mon Sep 17 00:00:00 2001 From: Jessica Smith @@ -615,14 +632,14 @@ To apply a patch generated by `format-patch`, you use `git am`. Technically, `gi Limit log functionality to the first 20 -This is the beginning of the output of the format-patch command that you saw in the previous section. This is also a valid mbox e-mail format. If someone has e-mailed you the patch properly using git send-email, and you download that into an mbox format, then you can point git am to that mbox file, and it will start applying all the patches it sees. If you run a mail client that can save several e-mails out in mbox format, you can save entire patch series into a file and then use git am to apply them one at a time. +Toto je začátek výstupu příkazu format-patch, s nímž jsme se setkali v předchozí části. Zároveň je to také platný e-mailový formát mbox. Jestliže vám přispěvatel řádně poslal záplatu e-mailem pomocí příkazu `git send-email` a vy záplatu stáhnete do formátu mbox, můžete na soubor mbox použít příkaz `git am`, který začne aplikovat všechny záplaty, které najde. Jestliže spustíte poštovního klienta, který dokáže uložit několik e-mailů ve formátu mbox, můžete do jednoho souboru uložit celou sérii záplat a příkazem `git am` je pak aplikovat všechny najednou. -However, if someone uploaded a patch file generated via `format-patch` to a ticketing system or something similar, you can save the file locally and then pass that file saved on your disk to `git am` to apply it: +Pokud však někdo nahrál soubor záplaty vygenerovaný příkazem `format-patch` do tiketového nebo podobného systému, můžete soubor uložit lokálně a poté na tento uložený soubor použít příkaz `git am`. Tímto způsobem záplatu aplikujete: - $ git am 0001-limit-log-function.patch + $ git am 0001-limit-log-function.patch Applying: add limit to log function -You can see that it applied cleanly and automatically created the new commit for you. The author information is taken from the e-mail’s `From` and `Date` headers, and the message of the commit is taken from the `Subject` and body (before the patch) of the e-mail. For example, if this patch was applied from the mbox example I just showed, the commit generated would look something like this: +Jak vidíte, záplata byla aplikována čistě a automaticky byla vytvořena nová revize. Informace o autorovi jsou převzaty z polí `From` a `Date` v e-mailu a zpráva k revizi je převzata z `Subject` a těla e-mailu (před samotnou záplatou). Pokud byl patch aplikován například ze souboru mbox v předchozím příkladu, vygenerovaná revize bude vypadat zhruba takto: $ git log --pretty=fuller -1 commit 6c5e70b984a60b3cecd395edd5b48a7575bf58e0 @@ -635,11 +652,11 @@ You can see that it applied cleanly and automatically created the new commit for Limit log functionality to the first 20 -The `Commit` information indicates the person who applied the patch and the time it was applied. The `Author` information is the individual who originally created the patch and when it was originally created. +Informace `Commit` uvádí osobu, která patch aplikovala, a čas, kdy se tak stalo. Informace `Author` naproti tomu označuje jedince, který patch původně vytvořil, a kdy tak učinil. -But it’s possible that the patch won’t apply cleanly. Perhaps your main branch has diverged too far from the branch the patch was built from, or the patch depends on another patch you haven’t applied yet. In that case, the `git am` process will fail and ask you what you want to do: +Může se ale stát, že záplata nebude aplikována čistě. Vaše hlavní větev se mohla příliš odchýlit od větve, z níž byla záplata vytvořena, nebo je záplata závislá na jiné záplatě, kterou jste ještě neaplikovali. V takovém případě proces `git am` neproběhne a Git se vás zeptá, co chcete udělat dál: - $ git am 0001-seeing-if-this-helps-the-gem.patch + $ git am 0001-seeing-if-this-helps-the-gem.patch Applying: seeing if this helps the gem error: patch failed: ticgit.gemspec:1 error: ticgit.gemspec: patch does not apply @@ -648,16 +665,16 @@ But it’s possible that the patch won’t apply cleanly. Perhaps your main bran If you would prefer to skip this patch, instead run "git am --skip". To restore the original branch and stop patching run "git am --abort". -This command puts conflict markers in any files it has issues with, much like a conflicted merge or rebase operation. You solve this issue much the same way — edit the file to resolve the conflict, stage the new file, and then run `git am --resolved` to continue to the next patch: +Tento příkaz vloží poznámku o konfliktu (conflict marker) do všech souborů, u nichž došlo k problémům, stejně jako u operací sloučení nebo přeskládání, při nichž došlo ke konfliktu. Problém se také řeší stejným způsobem. Úpravou souboru odstraňte konflikt, připravte nový soubor k zapsání a spusťte příkaz `git am --resolved`, jímž se přesunete k následující záplatě: $ (fix the file) - $ git add ticgit.gemspec + $ git add ticgit.gemspec $ git am --resolved Applying: seeing if this helps the gem -If you want Git to try a bit more intelligently to resolve the conflict, you can pass a `-3` option to it, which makes Git attempt a three-way merge. This option isn’t on by default because it doesn’t work if the commit the patch says it was based on isn’t in your repository. If you do have that commit — if the patch was based on a public commit — then the `-3` option is generally much smarter about applying a conflicting patch: +Pokud chcete, aby se Git pokusil vyřešit konflikt inteligentněji, můžete zadat parametr `-3`. Git se pokusí o třícestné sloučení. Tato možnost není nastavena jako výchozí, protože ji nelze použít v situaci, kdy revize, o níž záplata říká, že je na ní založen, není obsažena ve vašem repozitáři. Pokud tuto revizi vlastníte – byla-li záplata založena na veřejné revizi – počíná si parametr `-3` při aplikaci kolidující záplaty většinou mnohem inteligentněji. - $ git am -3 0001-seeing-if-this-helps-the-gem.patch + $ git am -3 0001-seeing-if-this-helps-the-gem.patch Applying: seeing if this helps the gem error: patch failed: ticgit.gemspec:1 error: ticgit.gemspec: patch does not apply @@ -665,49 +682,49 @@ If you want Git to try a bit more intelligently to resolve the conflict, you can Falling back to patching base and 3-way merge... No changes -- Patch already applied. -In this case, I was trying to apply a patch I had already applied. Without the `-3` option, it looks like a conflict. +V tomto případě jsem se pokoušel aplikovat záplatu, kterou už jsem jednou aplikoval. Bez parametru `-3` se celá situace tváří jako konflikt. -If you’re applying a number of patches from an mbox, you can also run the `am` command in interactive mode, which stops at each patch it finds and asks if you want to apply it: +Pokud aplikujete několik záplat z jednoho souboru mbox, můžete příkaz `am` spustit také v interaktivním režimu, který zastaví před každou záplatou, kterou najde, a zeptá se vás, zda ji chcete aplikovat: $ git am -3 -i mbox Commit Body is: -------------------------- seeing if this helps the gem -------------------------- - Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all + Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all -This is nice if you have a number of patches saved, because you can view the patch first if you don’t remember what it is, or not apply the patch if you’ve already done so. +To oceníte v situaci, kdy máte uložených několik záplat. Pokud si nepamatujete, o co v dané záplatě šlo, můžete si ho před aplikací prohlédnout. Stejně tak vyloučíte záplaty, které jste už jednou aplikovali. -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. +Až budete mít všechny záplaty aplikovány a zapsány do tematické větve, můžete se rozhodnout, zda a jak je chcete integrovat do některé z trvalejších větví. -### Checking Out Remote Branches ### +### Checkout vzdálených větví ### -If your contribution came from a Git user who set up their own repository, pushed a number of changes into it, and then sent you the URL to the repository and the name of the remote branch the changes are in, you can add them as a remote and do merges locally. +Pokud váš příspěvek pochází od uživatele systému Git, který založil vlastní repozitář, odeslal do něj sérii změn a následně vám poslal adresu URL k repozitáři a název vzdálené větve, v níž změny najdete, můžete je přidat jako vzdálené a lokálně je začlenit. -For instance, if Jessica sends you an e-mail saying that she has a great new feature in the `ruby-client` branch of her repository, you can test it by adding the remote and checking out that branch locally: +Pokud vám tedy například Jessica pošle e-mail, že vytvořila skvělou novou funkci ve větvi `ruby-client` ve svém repozitáři, můžete funkci otestovat tak, že přidáte větev jako vzdálenou a provedete její lokální checkout: $ git remote add jessica git://github.com/jessica/myproject.git $ git fetch jessica $ git checkout -b rubyclient jessica/ruby-client -If she e-mails you again later with another branch containing another great feature, you can fetch and check out because you already have the remote setup. +Pokud vám později opět pošle e-mail, že jiná větev obsahuje další skvělou funkci, můžete tuto větev vyzvednout a provést její checkout, protože už máte nastaven tento repozitář jako vzdálený. -This is most useful if you’re working with a person consistently. If someone only has a single patch to contribute once in a while, then accepting it over e-mail may be less time consuming than requiring everyone to run their own server and having to continually add and remove remotes to get a few patches. You’re also unlikely to want to have hundreds of remotes, each for someone who contributes only a patch or two. However, scripts and hosted services may make this easier — it depends largely on how you develop and how your contributors develop. +Tuto možnost využijete zejména tehdy, když s někým spolupracujete dlouhodobě. Má-li někdo jen jednu záplatu, jíž chce právě teď přispět, bude rychlejší, pokud vám záplatu doručí e-mailem, než abyste všechny vývojáře nutili provozovat kvůli pár záplatám vlastní servery a pravidelně přidávat a odstraňovat vzdálené repozitáře. Pravděpodobně také nebudete chtít mít nastaveny stovky vzdálených serverů, z nichž byste dostávali po jednom nebo dvou záplatách. Situaci vám mohou usnadnit skripty a hostované služby. Do velké míry tu záleží na tom, jak vy a vaši vývojáři k vývoji přistupujete. -The other advantage of this approach is that you get the history of the commits as well. Although you may have legitimate merge issues, you know where in your history their work is based; a proper three-way merge is the default rather than having to supply a `-3` and hope the patch was generated off a public commit to which you have access. +Další výhodou tohoto postupu je, že získáte rovněž historii revizí. Přestože můžete mít oprávněné problémy se slučováním, víte, kde ve své historii můžete hledat příčiny. Řádné třícestné sloučení je vždy lepším řešením, než zadat parametr `-3` a doufat, že byl patch vygenerován z veřejné revize, k níž máte přístup. -If you aren’t working with a person consistently but still want to pull from them in this way, you can provide the URL of the remote repository to the `git pull` command. This does a one-time pull and doesn’t save the URL as a remote reference: +Pokud s někým nespolupracujete dlouhodobě, ale přesto od něj chcete stáhnout data touto cestou, můžete zadat adresu URL vzdáleného repozitáře k příkazu `git pull`. Příkaz provede jednorázové stažení a nebude ukládat URL jako referenci na vzdálený repozitář: $ git pull git://github.com/onetimeguy/project.git From git://github.com/onetimeguy/project * branch HEAD -> FETCH_HEAD Merge made by recursive. -### Determining What Is Introduced ### +### Jak zjistit provedené změny ### -Now you have a topic branch that contains contributed work. At this point, you can determine what you’d like to do with it. This section revisits a couple of commands so you can see how you can use them to review exactly what you’ll be introducing if you merge this into your main branch. +Nyní máte tematickou větev s prací, kterou jste obdrželi od jiného vývojáře. V tomto okamžiku můžete určit, jak s ní chcete naložit. V této části zopakujeme některé příkazy a podíváme se, jak je můžete použít, chcete-li zjistit, co přesně se stane, pokud novou práci začleníte do své hlavní větve. -It’s often helpful to get a review of all the commits that are in this branch but that aren’t in your master branch. You can exclude commits in the master branch by adding the `--not` option before the branch name. For example, if your contributor sends you two patches and you create a branch called `contrib` and applied those patches there, you can run this: +Často může být užitečné získat přehled o všech revizích, které jsou obsaženy v určité větvi, ale dosud nejsou ve vaší hlavní větvi. Revize v hlavní větvi lze vyloučit vložením parametru `--not` před název větve. Pokud vám například přispěvatel pošle dvě záplaty a vy vytvoříte větev s názvem `contrib`, do níž tyto záplaty aplikujete, můžete použít tento příkaz: $ git log contrib --not master commit 5b6235bd297351589efc4d73316f0a68d484f118 @@ -722,107 +739,107 @@ It’s often helpful to get a review of all the commits that are in this branch updated the gemspec to hopefully work better -To see what changes each commit introduces, remember that you can pass the `-p` option to `git log` and it will append the diff introduced to each commit. +Chcete-li zjistit, jaké změny byly v jednotlivých revizích provedeny, můžete k příkazu `git log` přidat parametr `-p`, který ke každé revizi připojí rozdíly ve formátu diff. -To see a full diff of what would happen if you were to merge this topic branch with another branch, you may have to use a weird trick to get the correct results. You may think to run this: +Chcete-li vidět plný výpis diff, jak by vypadaly rozdíly, kdybyste tuto tematickou větev začlenili do jiné větve, můžete použít speciální trik, který vám zobrazí požadované informace. Můžete zadat následující příkaz: $ git diff master -This command gives you a diff, but it may be misleading. If your `master` branch has moved forward since you created the topic branch from it, then you’ll get seemingly strange results. This happens because Git directly compares the snapshots of the last commit of the topic branch you’re on and the snapshot of the last commit on the `master` branch. For example, if you’ve added a line in a file on the `master` branch, a direct comparison of the snapshots will look like the topic branch is going to remove that line. +Výstupem tohoto příkazu bude výpis diff, který však může být lehce matoucí. Jestliže se vaše větev `master` posunula vpřed od chvíle, kdy jste z ní vytvořili tematickou větev, budou výstupem příkazu zdánlivě nesmyslné výsledky. Je to z toho důvodu, že Git přímo srovnává snímky poslední revize v tematické větvi, na níž se nacházíte, se snímky poslední revize ve větvi `master`. Pokud jste například do souboru ve větvi `master` přidali jeden řádek, přímé srovnání snímků bude vypadat, jako by měla tematická větev tento řádek odstranit. -If `master` is a direct ancestor of your topic branch, this isn’t a problem; but if the two histories have diverged, the diff will look like you’re adding all the new stuff in your topic branch and removing everything unique to the `master` branch. +Pokud je větev `master` přímým předkem vaší tematické větve, nebude s příkazem žádný problém. Pokud se však obě historie v nějakém bodě rozdělily, bude výpis diff vypadat, jako byste chtěli přidat všechna nová data v tematické větvi a odstranit vše, co je pouze ve větvi `master`. -What you really want to see are the changes added to the topic branch — the work you’ll introduce if you merge this branch with master. You do that by having Git compare the last commit on your topic branch with the first common ancestor it has with the master branch. +To, co chcete vidět ve skutečnosti, jsou změny přidané do tematické větve, práci, kterou provedete začleněním této větve do větve hlavní. Tohoto srovnání dosáhnete tak, že necháte Git porovnat poslední revizi ve vaší tematické větvi s prvním předkem, kterého má společného s hlavní větví. -Technically, you can do that by explicitly figuring out the common ancestor and then running your diff on it: +Můžete tedy explicitně najít společného předka obou větví a spustit na něm příkaz diff: $ git merge-base contrib master 36c7dba2c95e6bbb78dfa822519ecfec6e1ca649 - $ git diff 36c7db + $ git diff 36c7db -However, that isn’t convenient, so Git provides another shorthand for doing the same thing: the triple-dot syntax. In the context of the `diff` command, you can put three periods after another branch to do a `diff` between the last commit of the branch you’re on and its common ancestor with another branch: +To však není příliš pohodlný způsob, a proto Git nabízí jinou možnost, jak lze provést stejnou věc: trojtečkovou syntaxi. V kontextu příkazu `diff` můžete vložit tři tečky za druhou větev – získáte výpis `diff` mezi poslední revizí větve, na níž se nacházíte, a společným předkem s druhou větví: $ git diff master...contrib -This command shows you only the work your current topic branch has introduced since its common ancestor with master. That is a very useful syntax to remember. +Tento příkaz zobrazí pouze práci, která byla ve vaší aktuální tematické větvi provedena od chvíle, kdy se oddělila od hlavní větve. Určitě uděláte dobře, pokud si tuto syntaxi zapamatujete. -### Integrating Contributed Work ### +### Integrace příspěvků ### -When all the work in your topic branch is ready to be integrated into a more mainline branch, the question is how to do it. Furthermore, what overall workflow do you want to use to maintain your project? You have a number of choices, so I’ll cover a few of them. +Když už je práce v tematické větvi připravena a může být integrována do některé z významnějších větví, vyvstává otázka, jak to provést. A vůbec, jaký celkový pracovní postup zvolíte ke správě projektu? Existuje hned několik možností. Na některé z nich se můžeme podívat. -#### Merging Workflows #### +#### Pracovní postupy založené na slučování #### -One simple workflow merges your work into your `master` branch. In this scenario, you have a `master` branch that contains basically stable code. When you have work in a topic branch that you’ve done or that someone has contributed and you’ve verified, you merge it into your master branch, delete the topic branch, and then continue the process. If we have a repository with work in two branches named `ruby_client` and `php_client` that looks like Figure 5-19 and merge `ruby_client` first and then `php_client` next, then your history will end up looking like Figure 5-20. +Jeden jednoduchý pracovní postup začlení vaší práci do větve `master`. V tomto scénáři obsahuje vaše větev `master` převážně jen stabilní kód. Máte-li v tematické větvi práci, kterou jste vytvořili nebo kterou vám někdo doručil a vy jste ji schválili, začleníte ji do své hlavní větve, smažete tematickou větev a proces může pokračovat. Máme-li repozitář s prací ve dvou větvích pojmenovaných `ruby_client` a `php_client`, který vypadá jako na obrázku 5-19, a začleníme nejprve větev `ruby_client` a poté `php_client`, bude naše historie vypadat jako na obrázku 5-20. -Insert 18333fig0519.png -Figure 5-19. History with several topic branches +Insert 18333fig0519.png +Obrázek 5-19. Historie s několika tematickými větvemi Insert 18333fig0520.png -Figure 5-20. After a topic branch merge +Obrázek 5-20. Po začlenění tematické větve -That is probably the simplest workflow, but it’s problematic if you’re dealing with larger repositories or projects. +Jedná se patrně o nejjednodušší pracovní postup. Je však problematický, pokud ho používáme u velkých repozitářů nebo projektů. -If you have more developers or a larger project, you’ll probably want to use at least a two-phase merge cycle. In this scenario, you have two long-running branches, `master` and `develop`, in which you determine that `master` is updated only when a very stable release is cut and all new code is integrated into the `develop` branch. You regularly push both of these branches to the public repository. Each time you have a new topic branch to merge in (Figure 5-21), you merge it into `develop` (Figure 5-22); then, when you tag a release, you fast-forward `master` to wherever the now-stable `develop` branch is (Figure 5-23). +Máte-li více vývojářů nebo větší projekt, pravděpodobně budete chtít použít přinejmenším dvoufázový cyklus začlenění. V tomto scénáři máte dvě dlouhodobé větve, hlavní větev `master` a větev `develop`. Určíte, že větev `master` bude aktualizována, pouze když je k dispozici velmi stabilní verze a do větve `develop` je integrován veškerý nový kód. Obě tyto větve pravidelně odesíláte do veřejného repozitáře. Pokaždé, když máte novou tematickou větev k začlenění (obrázek 5-21), začleníte ji do větve `develop` (obrázek 5-22). Když poté označujete vydání, posunete větev `master` rychle vpřed do místa, kde je nyní větev `develop` stabilní (obrázek 5-23). -Insert 18333fig0521.png -Figure 5-21. Before a topic branch merge +Insert 18333fig0521.png +Obrázek 5-21. Před začleněním tematické větve -Insert 18333fig0522.png -Figure 5-22. After a topic branch merge +Insert 18333fig0522.png +Obrázek 5-22. Po začlenění tematické větve -Insert 18333fig0523.png -Figure 5-23. After a topic branch release +Insert 18333fig0523.png +Obrázek 5-23. Po vydání tematické větve -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 stuff. -You can also continue this concept, having an integrate branch where all the work is merged together. Then, when the codebase on that branch is stable and passes tests, you merge it into a develop branch; and when that has proven itself stable for a while, you fast-forward your master branch. +Pokud někdo při tomto postupu klonuje repozitář vašeho projektu, může provést buď checkout hlavní větve, aby získal nejnovější stabilní verzi a udržoval ji aktuální, nebo checkout větve develop, která může být ještě o něco napřed. +Tento koncept můžete dále rozšířit o integrační větev, v níž budete veškerou práci slučovat. Teprve pokud je kód v této větvi stabilní a projde testováním, začleníte ho do větve develop. A až se větev develop ukáže v některém okamžiku jako stabilní, posunete rychle vpřed i svou hlavní větev. -#### Large-Merging Workflows #### +#### Pracovní postupy se začleňováním velkého objemu dat #### -The Git project has four long-running branches: `master`, `next`, and `pu` (proposed updates) for new work, and `maint` for maintenance backports. When new work is introduced by contributors, it’s collected into topic branches in the maintainer’s repository in a manner similar to what I’ve described (see Figure 5-24). At this point, the topics are evaluated to determine whether they’re safe and ready for consumption or whether they need more work. If they’re safe, they’re merged into `next`, and that branch is pushed up so everyone can try the topics integrated together. +Váš projekt Git má čtyři trvalé větve: `master`, `next` a `pu` (proposed updates, tj. návrh aktualizací) pro novou práci a `maint` pro backporty správy. Pokud přispěvatelé vytvoří novou práci, je shromažďována v tematických větvích v repozitáři správce podobným způsobem, jaký už jsem popisoval (viz obrázek 5-24). Nyní budou tematické větve vyhodnoceny, zda jsou bezpečné a mohou být aplikovány, nebo zda potřebují další úpravy. Jsou-li vyhodnoceny jako bezpečné, budou začleněny do větve `next` a ta bude následně odeslána do repozitáře, aby mohli všichni vyzkoušet, jak fungují tematické větve po sloučení. -Insert 18333fig0524.png -Figure 5-24. Managing a complex series of parallel contributed topic branches +Insert 18333fig0524.png +Obrázek 5-24. Správa komplexní série současně zpracovávaných příspěvků v tematických větvích -If the topics still need work, they’re merged into `pu` instead. When it’s determined that they’re totally stable, the topics are re-merged into `master` and are then rebuilt from the topics that were in `next` but didn’t yet graduate to `master`. This means `master` almost always moves forward, `next` is rebased occasionally, and `pu` is rebased even more often (see Figure 5-25). +Pokud ale tematické větve vyžadují další úpravy, budou začleněny do větve `pu`. Pokud se ukáže, že jsou tyto tematické větve naprosto stabilní, budou začleněny do větve `master` a poté budou znovu sestaveny z tematických větví, které byly ve větvi `next`, ale ještě se nedostaly do větve `master`. To znamená, že se větev `master` téměř neustále posouvá vpřed, větev `next` je čas od času přeskládána a větev `pu` je přeskládávána ještě o něco častěji (viz obrázek 5-25). -Insert 18333fig0525.png -Figure 5-25. Merging contributed topic branches into long-term integration branches +Insert 18333fig0525.png +Obrázek 5-25. Začlenění tematických větví s příspěvky do dlouhodobých integračních větví -When a topic branch has finally been merged into `master`, it’s removed from the repository. 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. +Byla-li tematická větev konečně začleněna do větve `master`, může být odstraněna z repozitáře. Projekt Git má kromě toho větev `maint`, která byla odštěpena z posledního vydání a představuje záplaty backportované pro případ, že by bylo třeba vydat opravnou verzi. Pokud tedy klonujete repozitář Git, můžete stáhnout až čtyři větve, a hodnotit tak projekt na čtyřech různých úrovních vývoje. Záleží na vás, do jaké hloubky chcete proniknout nebo jak chcete přispívat. A správce projektu má k dispozici strukturovaný pracovní postup k evaluaci nových příspěvků. -#### Rebasing and Cherry Picking Workflows #### +#### Pracovní postupy s přeskládáním a částečným převzetím #### -Other maintainers prefer to rebase or cherry-pick contributed work on top of their master branch, rather than merging it in, to keep a mostly linear history. When you have work in a topic branch and have determined that you want to integrate it, you move to that branch and run the rebase command to rebuild the changes on top of your current master (or `develop`, and so on) branch. If that works well, you can fast-forward your `master` branch, and you’ll end up with a linear project history. +Jiní správci dávají před začleněním práce z příspěvků přednost jejímu přeskládání nebo částečnému převzetí na vrchol hlavní větve, čímž udržují historii co nejlineárnější. Máte-li určitou práci v tematické větvi a rozhodli jste se, že ji integrujete, přejdete na tuto větev a spustíte příkaz rebase, jímž znovu sestavíte příslušné změny na vrcholu svojí aktuální hlavní větve (příp. větve `develop` apod.). Pokud vše funguje, můžete větev `master` posunout rychle vpřed a výsledkem procesu bude lineární historie projektu. -The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like Figure 5-26. +Druhým způsobem, jak přesunout práci z jedné větve do druhé, je tzv. částečné převzetí (angl. cherry picking, tedy něco jako „vyzobání třešniček“). Částečné převzetí lze v systému Git přirovnat k přeskládání jedné revize. Při této operaci vezme systém záplatu, která byla provedena v dané revizi, a pokusí se ji znovu aplikovat na větev, na níž se právě nacházíte. To využijete například v situaci, kdy máte několik revizí v tematické větvi, ale chcete integrovat pouze jednu z nich. Částečné převzetí však můžete použít i místo přeskládání, pokud máte v tematické větvi pouze jednu revizi. Uvažujme tedy projekt, který vypadá jako na obrázku 5-26. -Insert 18333fig0526.png -Figure 5-26. Example history before a cherry pick +Insert 18333fig0526.png +Obrázek 5-26. Uvažovaná historie před částečným převzetím -If you want to pull commit `e43a6` into your master branch, you can run +Chcete-li do hlavní větve natáhnout revizi `e43a6`, můžete zadat následující příkaz: $ git cherry-pick e43a6fd3e94888d76779ad79fb568ed180e5fcdf Finished one cherry-pick. [master]: created a0a41a9: "More friendly message when locking the index fails." 3 files changed, 17 insertions(+), 3 deletions(-) -This pulls the same change introduced in `e43a6`, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like Figure 5-27. +Tímto natáhnete stejnou změnu, která byla provedena revizí `e43a6`, avšak hodnota SHA-1 obou revizí se bude lišit, neboť bude rozdílné datum aplikace. Vaše historie revizí bude nyní vypadat jako na obrázku 5-27. -Insert 18333fig0527.png -Figure 5-27. History after cherry-picking a commit on a topic branch +Insert 18333fig0527.png +Obrázek 5-27. Historie po částečném převzetí revize z tematické větve -Now you can remove your topic branch and drop the commits you didn’t want to pull in. +Nyní můžete tematickou větev odstranit a zahodit revize, které nehodláte natáhnout do jiné větve. -### Tagging Your Releases ### +### Označení vydání značkou ### -When you’ve decided to cut a release, you’ll probably want to drop a tag so you can re-create that release at any point going forward. You can create a new tag as I discussed in Chapter 2. If you decide to sign the tag as the maintainer, the tagging may look something like this: +Až se rozhodnete vydat určitou verzi, pravděpodobně ji budete chtít označit značkou, abyste mohli toto vydání v kterémkoli okamžiku v budoucnosti obnovit. Novou značku vytvoříte podle návodu v kapitole 2. Pokud se rozhodnete podepsat značku jako správce, bude označení probíhat takto: $ git tag -s v1.5 -m 'my signed 1.5 tag' You need a passphrase to unlock the secret key for user: "Scott Chacon " 1024-bit DSA key, ID F721C45A, created 2009-02-09 -If you do sign your tags, you may have the problem of distributing the public PGP key used to sign your tags. The maintainer of the Git project has solved this issue by including their public key as a blob in the repository and then adding a tag that points directly to that content. To do this, you can figure out which key you want by running `gpg --list-keys`: +Pokud své značky podepisujete, můžete mít problémy s distribucí veřejného klíče PGP použitého k podepsání značky. Správce projektu Git vyřešil tento problém tak, že přidal svůj veřejný klíč jako blob do repozitáře a poté vložil značku, která ukazuje přímo na tento obsah. Pomocí příkazu `gpg --list-keys` můžete určit, jaký klíč chcete: $ gpg --list-keys /Users/schacon/.gnupg/pubring.gpg @@ -831,49 +848,49 @@ If you do sign your tags, you may have the problem of distributing the public PG uid Scott Chacon sub 2048g/45D02282 2009-02-09 [expires: 2010-02-09] -Then, you can directly import the key into the Git database by exporting it and piping that through `git hash-object`, which writes a new blob with those contents into Git and gives you back the SHA-1 of the blob: +Poté můžete klíč přímo importovat do databáze Git: vyexportujte ho a použijte příkaz `git hash-object`, který zapíše nový blob s tímto obsahem do systému Git a vrátí vám otisk SHA-1 tohoto blobu: $ gpg -a --export F721C45A | git hash-object -w --stdin 659ef797d181633c87ec71ac3f9ba29fe5775b92 -Now that you have the contents of your key in Git, you can create a tag that points directly to it by specifying the new SHA-1 value that the `hash-object` command gave you: +Nyní máte obsah svého klíče v systému Git a můžete vytvořit značku, která bude ukazovat přímo na něj. Zadejte proto novou hodnotu SHA-1, kterou jste získali příkazem `hash-object`: $ git tag -a maintainer-pgp-pub 659ef797d181633c87ec71ac3f9ba29fe5775b92 -If you run `git push --tags`, the `maintainer-pgp-pub` tag will be shared with everyone. If anyone wants to verify a tag, they can directly import your PGP key by pulling the blob directly out of the database and importing it into GPG: +Zadáte-li příkaz `git push --tags`, začnete značku `maintainer-pgp-pub` sdílet s ostatními. Bude-li chtít značku kdokoli ověřit, může přímo importovat váš klíč PGP tak, že stáhne blob z databáze a naimportuje ho do programu GPG: $ 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. +Klíč pak může použít k ověření všech vašich podepsaných značek. Pokud navíc zadáte do zprávy značky další instrukce k jejímu ověření, může si je koncový uživatel zobrazit příkazem `git show `. -### Generating a Build Number ### +### Vygenerování čísla sestavení ### -Because Git doesn’t have monotonically increasing numbers like 'v123' or the equivalent to go with each commit, if you want to have a human-readable name to go with a commit, you can run `git describe` on that commit. Git gives you the name of the nearest tag with the number of commits on top of that tag and a partial SHA-1 value of the commit you’re describing: +Git nepoužívá pro jednotlivé revize monotónně rostoucí čísla („v123“ apod.), a proto možná rádi využijete příkaz `git describe`, jímž lze každé revizi přiřadit běžně zpracovatelný název. Git vám poskytne název nejbližší značky s počtem revizí na vrcholu této značky a část hodnoty SHA-1 revize, k níž se popis vztahuje: $ git describe master v1.6.2-rc1-20-g8c5b85c -This way, you can export a snapshot or build and name it something understandable to people. In fact, if you build Git from source code cloned from the Git repository, `git --version` gives you something that looks like this. If you’re describing a commit that you have directly tagged, it gives you the tag name. +Díky tomu lze snímek nebo sestavení (build) vyexportovat a přiřadit mu pro člověka srozumitelný název. Pokud sestavujete Git ze zdrojového kódu naklonovaného z repozitáře Git, získáte po spuštění příkazu `git --version` něco, co vypadá zhruba podobně. Zadáváte-li popis revize, kterou jste právě opatřili značkou, dostanete název této značky. -The `git describe` command favors annotated tags (tags created with the `-a` or `-s` flag), so release tags should be created this way if you’re using `git describe`, to ensure the commit is named properly when described. You can also use this string as the target of a checkout or 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. +Příkaz `git describe` upřednostňuje anotované značky (značky vytvořené s příznakem `-a` nebo `-s`). Pokud tedy používáte příkaz `git describe`, abyste se při vytváření popisu ujistili, že je revize pojmenována správně, měli byste značky jednotlivých vydání vytvářet tímto způsobem. Tento řetězec můžete také použít jako cíl příkazu checkout nebo show, ačkoli ty pracují se zkrácenou hodnotou SHA-1, a tak nebudou platné navždy. Například jádro Linuxu nyní přešlo z 8 na 10 znaků, aby byla zajištěna jedinečnost objektů SHA-1. Starší výstupy příkazu `git describe` proto už nebudou platné. -### Preparing a Release ### +### Příprava vydání ### -Now you want to release a build. One of the things you’ll want to do is create an archive of the latest snapshot of your code for those poor souls who don’t use Git. The command to do this is `git archive`: +Nyní budete chtít sestavení vydat. Jednou z věcí, kterou budete chtít udělat, je vytvoření archivu nejnovějšího snímku vašeho kódu pro všechny nebohé duše, které nepoužívají systém Git. Příkaz pro vytvoření archivu zní `git archive`: $ git archive master --prefix='project/' | gzip > `git describe master`.tar.gz $ ls *.tar.gz v1.6.2-rc1-20-g8c5b85c.tar.gz -If someone opens that tarball, they get the latest snapshot of your project under a project directory. You can also create a zip archive in much the same way, but by passing the `--format=zip` option to `git archive`: +Až někdo tento tarball otevře, získá nejnovější snímek vašeho projektu v projektovém adresáři. Stejným způsobem můžete vytvořit také archiv zip. K příkazu `git archive` stačí přidat parametr `--format=zip`: $ git archive master --prefix='project/' --format=zip > `git describe master`.zip -You now have a nice tarball and a zip archive of your project release that you can upload to your website or e-mail to people. +Nyní máte vytvořen tarball a archiv zip k vydání svého projektu, které můžete nahrát na svou webovou stránku nebo rozeslat e-mailem. -### The Shortlog ### +### Příkaz „shortlog“ ### -It’s time to e-mail 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 e-mail 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: +Nyní je na čase obeslat e-mailem poštovní konferenci lidí, kteří chtějí vědět, co je ve vašem projektu nového. Elegantním způsobem, jak rychle získat určitý druh záznamu o změnách (changelog), které byly do projektu přidány od posledního vydání nebo e-mailu, je použít příkaz `git shortlog`. Příkaz shrne všechny revize v zadaném rozmezí. Například následující příkaz zobrazí shrnutí všech revizí od posledního vydání (pokud bylo vaše poslední vydání pojmenováno v1.0.1): $ git shortlog --no-merges master --not v1.0.1 Chris Wanstrath (8): @@ -890,8 +907,8 @@ It’s time to e-mail your mailing list of people who want to know what’s happ Version bump to 1.0.2 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 e-mail to your list. +Výstupem příkazu je čisté shrnutí všech revizí od v1.0.1, seskupené podle autora, kterého můžete přidat do e-mailu své konference. -## Summary ## +## Shrnutí ## -You should feel fairly comfortable contributing to a project in Git as well as maintaining your own project or integrating other users’ contributions. Congratulations on being an effective Git developer! In the next chapter, you’ll learn more powerful tools and tips for dealing with complex situations, which will truly make you a Git master. +V tomto okamžiku byste tedy už měli hravě zvládat přispívání do projektů v systému Git, správu vlastního projektu i integraci příspěvků jiných uživatelů. Gratulujeme, nyní je z vás efektivní vývojář v systému Git! V další kapitole poznáte další výkonné nástroje a tipy k řešení složitých situací, které z vás udělají opravdového mistra mezi uživateli systému Git. diff --git a/cs/06-git-tools/01-chapter6.markdown b/cs/06-git-tools/01-chapter6.markdown index c27ac9fd3..24e5a12d3 100644 --- a/cs/06-git-tools/01-chapter6.markdown +++ b/cs/06-git-tools/01-chapter6.markdown @@ -1,22 +1,22 @@ -# Git Tools # +# Nástroje systému Git # -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. +Do této chvíle jste stačili poznat většinu každodenních příkazů a pracovních postupů, které budete při práci se zdrojovým kódem potřebovat k ovládání a správě repozitáře Git. Zvládli jste základní úkony sledování a zapisování souborů a pochopili jste přednosti přípravy souborů k zapsání i snadného vytváření a začleňování větví. -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. +Nyní poznáte několik velmi účinných nástrojů, které vám Git nabízí. Pravděpodobně je nebudete používat každý den, ale přesto se vám mohou čas od času hodit. -## Revision Selection ## +## Výběr revize ## -Git allows you to specify specific commits or a range of commits in several ways. They aren’t necessarily obvious but are helpful to know. +Systém Git umožňuje určit jednotlivé revize nebo interval revizí několika způsoby. Není nezbytně nutné, abyste je všechny znali, ale mohou být užitečné. -### Single Revisions ### +### Jednotlivé revize ### -You can obviously refer to a commit by the SHA-1 hash that it’s given, but there are more human-friendly ways to refer to commits as well. This section outlines the various ways you can refer to a single commit. +Revizi můžete samozřejmě specifikovat na základě otisku SHA-1, jenž jí byl přidělen. Existují však i uživatelsky příjemnější způsoby, jak označit konkrétní revizi. Tato část uvede několik různých způsobů, jak lze určit jednu konkrétní revizi. -### Short SHA ### +### Zkrácená hodnota SHA ### -Git is smart enough to figure out what commit you meant to type if you provide the first few characters, as long as your partial SHA-1 is at least four characters long and unambiguous — that is, only one object in the current repository begins with that partial SHA-1. +Git je dostatečně chytrý na to, aby pochopil, jakou revizi jste měli na mysli, zadáte-li pouze prvních několik znaků. Tento neúplný otisk SHA-1 musí mít alespoň čtyři znaky a musí být jednoznačný, tj. žádný další objekt v aktuálním repozitáři nesmí začínat stejnou zkrácenou hodnotou SHA-1. -For example, to see a specific commit, suppose you run a `git log` command and identify the commit where you added certain functionality: +Pokud si chcete například prohlédnout konkrétní revizi, řekněme, že spustíte příkaz `git log` a určíte revizi, do níž jste vložili určitou funkci: $ git log commit 734713bc047d87bf7eac9674765ae793478c50d3 @@ -38,74 +38,74 @@ For example, to see a specific commit, suppose you run a `git log` command and i added some blame and merge stuff -In this case, choose `1c002dd....` If you `git show` that commit, the following commands are equivalent (assuming the shorter versions are unambiguous): +V tomto případě vyberte `1c002dd....`. Pokud chcete na revizi použít příkaz `git show`, budou všechny následující příkazy ekvivalentní (za předpokladu, že jsou zkrácené verze jednoznačné): $ git show 1c002dd4b536e7479fe34593e72e6c6c1819e53b $ git show 1c002dd4b536e7479f $ git show 1c002d -Git can figure out a short, unique abbreviation for your SHA-1 values. If you pass `--abbrev-commit` to the `git log` command, the output will use shorter values but keep them unique; it defaults to using seven characters but makes them longer if necessary to keep the SHA-1 unambiguous: +Git dokáže identifikovat krátkou, jednoznačnou zkratku hodnoty SHA-1. Zadáte-li k příkazu `git log` parametr `--abbrev-commit`, výstup bude používat kratší hodnoty, ale pouze v jednoznačném tvaru. Standardně se používá sedm znaků, avšak je-li to kvůli jednoznačnosti hodnoty SHA-1 nezbytné, bude použito znaků více: $ git log --abbrev-commit --pretty=oneline ca82a6d changed the version number 085bb3b removed unnecessary test code a11bef0 first commit -Generally, eight to ten characters are more than enough to be unique within a project. One of the largest Git projects, the Linux kernel, is beginning to need 12 characters out of the possible 40 to stay unique. +Osm až deset znaků většinou bohatě stačí, aby byla hodnota v rámci projektu jednoznačná. V jednom z největších projektů Git, v jádru Linuxu, začíná být nutné zadávat pro jednoznačné určení už 12 znaků z celkových 40 možných. -### A SHORT NOTE ABOUT SHA-1 ### +### Krátká poznámka k hodnotě SHA-1 ### -A lot of people become concerned at some point that they will, by random happenstance, have two objects in their repository that hash to the same SHA-1 value. What then? +Někteří uživatelé bývají zmateni, že mohou mít v repozitáři – shodou okolností – dva objekty, které mají stejnou hodnotu SHA-1 otisku. Co teď? -If you do happen to commit an object that hashes to the same SHA-1 value as a previous object in your repository, GIt will see the previous object already in your Git database and assume it was already written. If you try to check out that object again at some point, you’ll always get the data of the first object. +Pokud náhodou zapíšete objekt, který má stejnou hodnotu SHA-1 otisku jako předchozí objekt ve vašem repozitáři, Git už uvidí předchozí objekt v databázi Git a bude předpokládat, že už byl zapsán. Pokud se někdy v budoucnosti pokusíte znovu provést checkout tohoto objektu, vždy dostanete data prvního objektu. -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. That’s 1,200 times the number of grains of sand on the earth. +Měli bychom však také říci, jak moc je nepravděpodobné, že taková situace nastane. Otisk SHA-1 má 20 bytů, neboli 160 bitů. Počet objektů s náhodným otiskem, které bychom potřebovali k 50% pravděpodobnosti, že nastane jediná kolize, je asi 2^80 (vzorec k určení pravděpodobnosti kolize je `p = (n(n-1)/2) * (1/2^160)`). 2^80 je 1,2 * 10^24, neboli 1 milion miliard miliard. To je 1200násobek počtu všech zrnek písku na celé Zemi. -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 (1 million Git objects) and pushing it into one enormous Git repository, it would take 5 years until that repository contained enough objects to have a 50% probability of a single SHA-1 object collision. 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. +Abyste si udělali představu, jak je nepravděpodobné, že dojde ke kolizi hodnot SHA-1, připojujeme jeden malý příklad. Kdyby 6,5 miliardy lidí na zemi programovalo a každý by každou sekundu vytvořil kód odpovídající celé historii linuxového jádra (1 milion objektů Git) a odesílal ho do jednoho obřího repozitáře Git, trvalo by 5 let, než by repozitář obsahoval dost objektů na to, aby existovala 50% pravděpodobnost, že dojde ke kolizi jediného objektu SHA-1. To už je pravděpodobnější, že všichni členové vašeho programovacího týmu budou během jedné noci v navzájem nesouvisejících incidentech napadeni a zabiti smečkou vlků. -### Branch References ### +### Reference větví ### -The most straightforward way to specify a commit requires that it have a branch reference pointed at it. Then, you can use a branch name in any Git command that expects a commit object or SHA-1 value. For instance, if you want to show the last commit object on a branch, the following commands are equivalent, assuming that the `topic1` branch points to `ca82a6d`: +Nejčistší způsob, jak určit konkrétní revizi, vyžaduje, aby měla revize referenci větve, která na ni ukazuje. V takovém případě můžete použít název větve v libovolném příkazu Git, který vyžaduje objekt revize nebo hodnotu SHA-1. Pokud chcete například zobrazit objekt poslední revize větve, můžete využít některý z následujících příkazů (za předpokladu, že větev `topic1` ukazuje na `ca82a6d`): $ git show ca82a6dff817ec66f44342007202690a93763949 $ git show topic1 -If you want to see which specific SHA a branch points to, or if you want to see what any of these examples boils down to in terms of SHAs, you can use a Git plumbing tool called `rev-parse`. You can see Chapter 9 for more information about plumbing tools; basically, `rev-parse` exists for lower-level operations and isn’t designed to be used in day-to-day operations. However, it can be helpful sometimes when you need to see what’s really going on. Here you can run `rev-parse` on your branch. +Jestliže vás zajímá, na kterou konkrétní hodnotu SHA větev ukazuje, nebo chcete-li zjistit, jak bude některý z těchto příkladů vypadat v podobě SHA, můžete použít jeden z nízkoúrovňových nástrojů systému Git: `rev-parse`. Více o nízkoúrovňových nástrojích najdete v kapitole 9. Nástroj `rev-parse` se používá v podstatě pouze pro operace na nižších úrovních a není koncipován pro každodenní používání. Může se však hodit, až budete jednou potřebovat zjistit, co se doopravdy odehrává. Tehdy můžete na svou větev spustit příkaz `rev-parse`: $ git rev-parse topic1 ca82a6dff817ec66f44342007202690a93763949 -### RefLog Shortnames ### +### Zkrácené názvy v záznamu RefLog ### -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. +Jednou z věcí, které probíhají na pozadí systému Git, zatímco vy pracujete, je uchovávání záznamu reflog, v němž se ukládají pozice referencí HEAD a všech vašich větví za několik posledních měsíců. -You can see your reflog by using `git reflog`: +Svůj reflog si můžete nechat zobrazit příkazem `git reflog`: $ git reflog - 734713b... HEAD@{0}: commit: fixed refs handling, added gc auto, updated - d921970... HEAD@{1}: merge phedders/rdocs: Merge made by recursive. - 1c002dd... HEAD@{2}: commit: added some blame and merge stuff - 1c36188... HEAD@{3}: rebase -i (squash): updating HEAD - 95df984... HEAD@{4}: commit: # This is a combination of two commits. - 1c36188... HEAD@{5}: rebase -i (squash): updating HEAD - 7e05da5... HEAD@{6}: rebase -i (pick): updating HEAD + 734713b HEAD@{0}: commit: fixed refs handling, added gc auto, updated + d921970 HEAD@{1}: merge phedders/rdocs: Merge made by recursive. + 1c002dd HEAD@{2}: commit: added some blame and merge stuff + 1c36188 HEAD@{3}: rebase -i (squash): updating HEAD + 95df984 HEAD@{4}: commit: # This is a combination of two commits. + 1c36188 HEAD@{5}: rebase -i (squash): updating HEAD + 7e05da5 HEAD@{6}: rebase -i (pick): updating HEAD -Every time your branch tip is updated for any reason, Git stores that information for you in this temporary history. And you can specify older commits with this data, as well. If you want to see the fifth prior value of the HEAD of your repository, you can use the `@{n}` reference that you see in the reflog output: +Pokaždé, když je z nějakého důvodu aktualizován vrchol větve, Git tuto informaci uloží v dočasné historii reflog. Pomocí těchto dat lze rovněž specifikovat starší revize. Chcete-li zobrazit pátou poslední hodnotu ukazatele HEAD svého repozitáře, použijte referenci `@{n}` z výstupu reflog: $ git show HEAD@{5} -You can also use this syntax to see where a branch was some specific amount of time ago. For instance, to see where your `master` branch was yesterday, you can type +Tuto syntaxi můžete použít také k zobrazení pozice, na níž se větev nacházela před určitou dobou. Chcete-li například zjistit, kde byla vaše větev `master` včera (yesterday), můžete zadat příkaz: $ git show master@{yesterday} -That shows you where the branch tip 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. +Git vám ukáže, kde se vrchol větve nacházel včera. Tato možnost funguje pouze pro data, jež jsou dosud v záznamu reflog. Nemůžete ji proto použít pro revize starší než několik měsíců. -To see reflog information formatted like the `git log` output, you can run `git log -g`: +Chcete-li zobrazit informace záznamu reflog ve formátu výstupu `git log`, zadejte příkaz `git log -g`: $ git log -g master commit 734713bc047d87bf7eac9674765ae793478c50d3 Reflog: master@{0} (Scott Chacon ) - Reflog message: commit: fixed refs handling, added gc auto, updated + Reflog message: commit: fixed refs handling, added gc auto, updated Author: Scott Chacon Date: Fri Jan 2 18:32:33 2009 -0800 @@ -119,24 +119,24 @@ To see reflog information formatted like the `git log` output, you can run `git Merge commit 'phedders/rdocs' -It’s important to note that the reflog information is strictly local — it’s a log of what you’ve done in your repository. The references won’t be the same on someone else’s copy of the repository; and right after you initially clone a repository, you'll have an empty reflog, as no activity has occurred yet in your repository. Running `git show HEAD@{2.months.ago}` will work only if you cloned the project at least two months ago — if you cloned it five minutes ago, you’ll get no results. +Měli bychom také doplnit, že informace záznamu reflog jsou čistě lokální, vztahují se pouze na to, co jste provedli ve svém repozitáři. V kopii repozitáře na počítači kohokoli jiného se budou tyto reference lišit. Bezprostředně poté, co poprvé naklonujete repozitář, bude váš reflog prázdný, protože ve vašem repozitáři ještě nebyla provedena žádná operace. Příkaz `git show HEAD@{2.months.ago}` bude fungovat, pouze pokud jste projekt naklonovali minimálně před dvěma měsíci (tedy „2 months ago“). Pokud jste jej naklonovali před pěti minutami, neobdržíte žádný výsledek. -### Ancestry References ### +### Reference podle původu ### -The other main way to specify a commit is via its ancestry. If you place a `^` at the end of a reference, Git resolves it to mean the parent of that commit. -Suppose you look at the history of your project: +Další základní způsob, jak specifikovat konkrétní revizi, je na základě jejího původu. Umístíte-li na konec reference znak `^`, Git bude referenci chápat tak, že označuje rodiče dané revize. +Můžete mít například takovouto historii projektu: $ git log --pretty=format:'%h %s' --graph * 734713b fixed refs handling, added gc auto, updated tests * d921970 Merge commit 'phedders/rdocs' - |\ + |\ | * 35cfb2b Some rdoc changes * | 1c002dd added some blame and merge stuff - |/ + |/ * 1c36188 ignore *.gem * 9b29157 add open3_detach to gemspec file list -Then, you can see the previous commit by specifying `HEAD^`, which means "the parent of HEAD": +Zobrazit předchozí revizi pak můžete pomocí `HEAD^`, což doslova znamená „rodič revize HEAD“: $ git show HEAD^ commit d921970aadf03b3cf0e71becdaab3147ba71cdef @@ -146,7 +146,7 @@ Then, you can see the previous commit by specifying `HEAD^`, which means "the pa Merge commit 'phedders/rdocs' -You can also specify a number after the `^` — for example, `d921970^2` means "the second parent of d921970." This syntax is only useful for merge commits, which have more than one parent. The first parent is the branch you were on when you merged, and the second is the commit on the branch that you merged in: +Za znakem `^` můžete zadat také číslo, např. `d921970^2` označuje „druhého rodiče revize d921970“. Tato syntaxe má význam pouze u revizí vzniklých sloučením, které mají více než jednoho rodiče. První rodič je větev, na níž jste se během začlenění nacházeli, druhým rodičem je větev, kterou jste začleňovali: $ git show d921970^ commit 1c002dd4b536e7479fe34593e72e6c6c1819e53b @@ -162,7 +162,7 @@ You can also specify a number after the `^` — for example, `d921970^2` means " Some rdoc changes -The other main ancestry specification is the `~`. This also refers to the first parent, so `HEAD~` and `HEAD^` are equivalent. The difference becomes apparent when you specify a number. `HEAD~2` means "the first parent of the first parent," or "the grandparent" — it traverses the first parents the number of times you specify. For example, in the history listed earlier, `HEAD~3` would be +Další základní možností označení původu je znak `~`. Také tento znak označuje prvního rodiče, výrazy `HEAD~` a `HEAD^` jsou proto ekvivalentní. Rozdíl mezi nimi je patrný při zadání čísla. `HEAD~2` označuje „prvního rodiče prvního rodiče“, tedy „prarodiče“. Příkaz překročí prvního rodiče tolikrát, kolikrát udává číselná hodnota. Například v historii naznačené výše by `HEAD~3` znamenalo: $ git show HEAD~3 commit 1c3618887afb5fbcbea25b7c013f4e2114448b8d @@ -171,7 +171,7 @@ The other main ancestry specification is the `~`. This also refers to the first ignore *.gem -This can also be written `HEAD^^^`, which again is the first parent of the first parent of the first parent: +Totéž by bylo možné označit výrazem `HEAD^^^`, který opět udává prvního rodiče prvního rodiče prvního rodiče: $ git show HEAD^^^ commit 1c3618887afb5fbcbea25b7c013f4e2114448b8d @@ -180,57 +180,57 @@ This can also be written `HEAD^^^`, which again is the first parent of the first ignore *.gem -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. +Tyto syntaxe můžete také kombinovat. Druhého rodiče předchozí reference (jestliže se jednalo o revizi sloučením) lze získat výrazem `HEAD~3^2` atd. -### Commit Ranges ### +### Intervaly revizí ### -Now that you can specify individual commits, let’s see how to specify ranges of commits. This is particularly useful for managing your branches — if you have a lot of branches, you can use range specifications to answer questions such as, "What work is on this branch that I haven’t yet merged into my main branch?" +Nyní, když umíte určit jednotlivé revize, podíváme se, jak lze určovat celé intervaly revizí. To využijete zejména při správě větví. Máte-li větší množství větví, pomůže vám označení intervalu revizí dohledat odpovědi na otázky typu: „Jaká práce je obsažena v této větvi, kterou jsem ještě nezačlenil do hlavní větve?“ -#### Double Dot #### +#### Dvě tečky #### -The most common range specification is the double-dot syntax. This basically asks Git to resolve a range of commits that are reachable from one commit but aren’t reachable from another. For example, say you have a commit history that looks like Figure 6-1. +Nejčastěji se při označení intervalu používá dvojtečková syntaxe. Pomocí ní systému Git v podstatě říkáte, aby uvažoval celý interval revizí, které jsou dostupné z jedné revize, ale nejsou dostupné z jiné. Předpokládejme tedy, že máte historii revizí jako na obrázku 6-1. -Insert 18333fig0601.png -Figure 6-1. Example history for range selection +Insert 18333fig0601.png +Obrázek 6-1. Příklad historie revizí pro výběr intervalu -You want to see what is in your experiment branch that hasn’t yet been merged into your master branch. You can ask Git to show you a log of just those commits with `master..experiment` — that means "all commits reachable by experiment that aren’t reachable by master." For the sake of brevity and clarity in these examples, I’ll use the letters of the commit objects from the diagram in place of the actual log output in the order that they would display: +Vy chcete vidět, co všechno obsahuje vaše experimentální větev, kterou jste ještě nezačlenili do hlavní větve. Pomocí výrazu `master..experiment` můžete systému Git zadat příkaz, aby vám zobrazil log právě s těmito revizemi, doslova „všemi revizemi dostupnými z větve experiment a nedostupnými z hlavní větve“. V zájmu stručnosti a názornosti použiji v těchto příkladech místo skutečného výstupu logu písmena objektů revizí z diagramu v pořadí, jak by se zobrazily: $ git log master..experiment D C -If, on the other hand, you want to see the opposite — all commits in `master` that aren’t in `experiment` — you can reverse the branch names. `experiment..master` shows you everything in `master` not reachable from `experiment`: +A samozřejmě si můžete nechat zobrazit i pravý opak, všechny revize ve větvi `master`, které nejsou ve větvi `experiment`. K tomu stačí obrátit pořadí názvů větví v příkazu. Výraz `experiment..master` zobrazí vše ve větvi `master`, co není dostupné ve větvi `experiment`: $ git log experiment..master F E -This is useful if you want to keep the `experiment` branch up to date and preview what you’re about to merge in. Another very frequent use of this syntax is to see what you’re about to push to a remote: +Tento log využijete, pokud chcete udržovat větev `experiment` stále aktuální a zjistit, co hodláte začlenit. Tato syntaxe se velmi často používá také ke zjištění, co hodláte odeslat do vzdálené větve: $ git log origin/master..HEAD -This command shows you any commits in your current branch that aren’t in the `master` branch on your `origin` remote. If you run a `git push` and your current branch is tracking `origin/master`, the commits listed by `git log origin/master..HEAD` are the commits that will be transferred to the server. -You can also leave off one side of the syntax to have Git assume HEAD. For example, you can get the same results as in the previous example by typing `git log origin/master..` — Git substitutes HEAD if one side is missing. +Tento příkaz zobrazí všechny revize ve vaší aktuální větvi, které nejsou obsaženy ve větvi `master` vzdáleného repozitáře `origin`. Spustíte-li příkaz `git push` a vaše aktuální větev sleduje větev `origin/master`, budou na server přesunuty revize, které lze zobrazit příkazem `git log origin/master..HEAD`. +Jednu stranu intervalu můžete zcela vynechat, Git na její místo automaticky dosadí HEAD. Stejné výsledky jako v předchozím příkladu dostanete zadáním příkazu `git log origin/master..` – Git dosadí na prázdnou stranu výraz HEAD. -#### Multiple Points #### +#### Několik bodů #### -The double-dot syntax is useful as a shorthand; but perhaps you want to specify more than two branches to indicate your revision, such as seeing what commits are in any of several branches that aren’t in the branch you’re currently on. Git allows you to do this by using either the `^` character or `--not` before any reference from which you don’t want to see reachable commits. Thus these three commands are equivalent: +Dvojtečková syntaxe je užitečná jako zkrácený výraz. Možná ale budete chtít k označení revize určit více než dvě větve, např. až budete chtít zjistit, které revize jsou obsaženy ve všech ostatních větvích a zároveň nejsou obsaženy ve větvi, na níž se právě nacházíte. V systému Git to můžete provést buď zadáním znaku `^` nebo parametru `--not` před referencí, jejíž dostupné revize si nepřejete zobrazit. Tyto tři příkazy jsou tedy ekvivalentní: $ git log refA..refB $ git log ^refA refB $ git log refB --not refA -This is nice because with this syntax you can specify more than two references in your query, which you cannot do with the double-dot syntax. For instance, if you want to see all commits that are reachable from `refA` or `refB` but not from `refC`, you can type one of these: +Tato syntaxe je užitečná zejména proto, že pomocí ní můžete zadat více než dvě reference, což není pomocí dvojtečkové syntaxe možné. Pokud chcete zobrazit například všechny revize, které jsou dostupné ve větvi `refA` nebo `refB`, ale nikoli ve větvi `refC`, zadejte jeden z následujících příkazů: $ git log refA refB ^refC $ 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. +Tím máte v rukou velmi efektivní systém vyhledávání revizí, který vám pomůže zjistit, co vaše větve obsahují. -#### Triple Dot #### +#### Tři tečky #### -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. Look back at the example commit history in Figure 6-1. -If you want to see what is in `master` or `experiment` but not any common references, you can run +Poslední významnou syntaxí k určení intervalu je trojtečková syntaxe, která vybere všechny revize dostupné ve dvou referencích, ale ne v obou zároveň. Podívejme se ještě jednou na příklad historie revizí na obrázku 6-1. +Chcete-li zjistit, co je ve větvi `master` nebo `experiment`, ale nechcete vidět jejich společné reference, zadejte příkaz: $ git log master...experiment F @@ -238,9 +238,9 @@ If you want to see what is in `master` or `experiment` but not any common refere D C -Again, this gives you normal `log` output but shows you only the commit information for those four commits, appearing in the traditional commit date ordering. +Výstupem příkazu bude běžný výpis příkazu `log`, ale zobrazí se pouze informace o těchto čtyřech revizích, uspořádané v tradičním pořadí podle data zapsání. -A common switch to use with the `log` command in this case is `--left-right`, which shows you which side of the range each commit is in. This helps make the data more useful: +Přepínačem, který se v tomto případě běžně používá v kombinaci s příkazem `log`, je parametr `--left-right`. Příkaz pak zobrazí, na jaké straně intervalu se ta která revize nachází. Díky tomu získáte k datům další užitečné informace: $ git log --left-right master...experiment < F @@ -248,12 +248,12 @@ A common switch to use with the `log` command in this case is `--left-right`, wh > D > C -With these tools, you can much more easily let Git know what commit or commits you want to inspect. +Pomocí těchto nástrojů můžete v systému Git daleko snáze specifikovat, kterou revizi nebo které revize chcete zobrazit. -## Interactive Staging ## +## Interaktivní příprava k zapsání ## -Git comes with a couple of scripts that make some command-line tasks easier. Here, you’ll look at a few interactive commands that can help you easily craft your commits to include only certain combinations and parts of files. These tools are very helpful if you modify a bunch of files and then decide that you want those changes to be in several focused commits rather than one big messy commit. This way, you can make sure your commits are logically separate changesets and can be easily reviewed by the developers working with you. -If you run `git add` with the `-i` or `--interactive` option, Git goes into an interactive shell mode, displaying something like this: +Git nabízí také celou řadu skriptů, které vám mohou usnadnit provádění příkazů zadávaných v příkazovém řádku. V této části se podíváme na několik interaktivních příkazů, které vám mohou pomoci snadno určit, na jaké kombinace a části souborů má být omezena konkrétní revize. Tyto nástroje se vám mohou velmi hodit, jestliže upravujete několik souborů a rozhodnete se, že tyto změny zapíšete raději do několika specializovaných revizí než do jedné velké nepřehledné. Tímto způsobem zajistíte, že budou vaše revize logicky oddělenými sadami změn, jež mohou vaši spolupracovníci snadno zkontrolovat. +Spustíte-li příkaz `git add` s parametrem `-i` nebo `--interactive`, přejde Git do interaktivního režimu shellu a zobrazí zhruba následující: $ git add -i staged unstaged path @@ -264,15 +264,15 @@ If you run `git add` with the `-i` or `--interactive` option, Git goes into an i *** Commands *** 1: status 2: update 3: revert 4: add untracked 5: patch 6: diff 7: quit 8: help - What now> + What now> -You can see that this command shows you a much different view of your staging area — basically the same information you get with `git status` but a bit more succinct and informative. It lists the changes you’ve staged on the left and unstaged changes on the right. +Vidíte, že tento příkaz vám poskytne podstatně odlišný pohled na vaši oblast připravených změn. Stejné informace, i když o něco stručnější a hutnější, získáte také příkazem `git status`. Tento příkaz vypíše všechny změny, které jste připravili k zapsání, na levé straně, nepřipravené změny na pravé. -After this comes a Commands section. Here you can do a number of things, including staging files, unstaging files, staging parts of files, adding untracked files, and seeing diffs of what has been staged. +Za seznamem změn následuje část Commands (Příkazy). Tady můžete provádět celou řadu věcí, včetně přípravy souborů k zapsání, vracení připravených souborů, přípravy částí souborů, přidávání nesledovaných souborů a prohlížení změn v připravených souborech. -### Staging and Unstaging Files ### +### Příprava souborů k zapsání a jejich vracení ### -If you type `2` or `u` at the `What now>` prompt, the script prompts you for which files you want to stage: +Zadáte-li na výzvu `What now>` (Co teď) odpověď `2` nebo `u`, skript se vás zeptá, které soubory chcete připravit k zapsání: What now> 2 staged unstaged path @@ -281,7 +281,7 @@ If you type `2` or `u` at the `What now>` prompt, the script prompts you for whi 3: unchanged +5/-1 lib/simplegit.rb Update>> -To stage the TODO and index.html files, you can type the numbers: +Jestliže chcete připravit k zapsání soubory TODO a index.html, zadejte příslušná čísla: Update>> 1,2 staged unstaged path @@ -290,9 +290,9 @@ To stage the TODO and index.html files, you can type the numbers: 3: unchanged +5/-1 lib/simplegit.rb Update>> -The `*` next to each file means the file is selected to be staged. If you press Enter after typing nothing at the `Update>>` prompt, Git takes anything selected and stages it for you: +Znak `*` vedle souborů znamená, že je soubor vybrán jako připravený k zapsání. Jestliže na výzvu `Update>>` nic nezadáte a stisknete klávesu Enter, Git vezme všechny vybrané soubory a připraví je k zapsání: - Update>> + Update>> updated 2 paths *** Commands *** @@ -304,7 +304,7 @@ The `*` next to each file means the file is selected to be staged. If you press 2: +1/-1 nothing index.html 3: unchanged +5/-1 lib/simplegit.rb -Now you can see that the TODO and index.html files are staged and the simplegit.rb file is still unstaged. If you want to unstage the TODO file at this point, you use the `3` or `r` (for revert) option: +Jak vidíte, soubory TODO a index.html jsou připraveny k zapsání, soubor simplegit.rb nikoli. Chcete-li v tuto chvíli vrátit soubor TODO z oblasti připravených změn, použijte parametr `3` nebo `r` (jako „revert“ neboli „vrátit“): *** Commands *** 1: status 2: update 3: revert 4: add untracked @@ -322,7 +322,7 @@ Now you can see that the TODO and index.html files are staged and the simplegit. Revert>> [enter] reverted one path -Looking at your Git status again, you can see that you’ve unstaged the TODO file: +Pokud se nyní znovu podíváte na stav Git souboru TODO, uvidíte, že už není připraven k zapsání: *** Commands *** 1: status 2: update 3: revert 4: add untracked @@ -333,7 +333,7 @@ Looking at your Git status again, you can see that you’ve unstaged the TODO fi 2: +1/-1 nothing index.html 3: unchanged +5/-1 lib/simplegit.rb -To see the diff of what you’ve staged, you can use the `6` or `d` (for diff) command. It shows you a list of your staged files, and you can select the ones for which you would like to see the staged diff. This is much like specifying `git diff --cached` on the command line: +Chcete-li zobrazit výpis diff připravených souborů, použijte příkaz `6` nebo `d` (jako „diff“). Příkaz zobrazí seznam připravených souborů. Můžete vybrat ty soubory, pro něž chcete zobrazit rozdíly připravených změn. Je to prakticky totéž, jako byste na příkazovém řádku zadali příkaz `git diff --cached`: *** Commands *** 1: status 2: update 3: revert 4: add untracked @@ -355,11 +355,11 @@ To see the diff of what you’ve staged, you can use the `6` or `d` (for diff) c