Редактирование: Участник:Lit-uriy/GitIntroductionWithQt

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск
Внимание: Вы не представились системе. Ваш IP-адрес будет записан в историю изменений этой страницы.
Правка может быть отменена. Пожалуйста, просмотрите сравнение версий, чтобы убедиться, что это именно те изменения, которые вас интересуют, и нажмите «Записать страницу», чтобы изменения вступили в силу.
Текущая версия Ваш текст
Строка 4: Строка 4:
}}
}}
-
=== Введение ===
+
=== Introduction ===
-
Этот документ является простым руководством показывающим процедуры необходимые для разработки и сопровождения заплаток '''on top of Qt'''. Оно не заменяет руководство по [[Git]] deliberately skipping over other established but different git-based workflows.
+
This document is a simple guide showing the procedures necessary to develop and maintain patches on top of Qt. It is not a replacement for the Git manual deliberately skipping over other established but different git-based workflows.
__TOC__
__TOC__
 +
=== Getting the Qt source code ===
 +
This section shows how to download the source code and explains the concept of a git repository.
-
=== Получение исходного кода Qt ===
+
First, we have to retrieve Qt’s source code, using the git clone command:
-
Этот раздел показывает, как загрузить исходный код, и объясняет концепцию Git-хранилища.
+
{{code|bash|code=
-
 
+
-
Во-первых, мы извлекаем исходный код Qt, используя команду ''git clone'':
+
-
{{Команда|
+
$ git clone git://gitorious.org/qt/qt.git
$ git clone git://gitorious.org/qt/qt.git
cd qt}}
cd qt}}
-
Она создаст новый каталог называемый “qt” и загружает исходный код в него. Она также загружает полную историю всех файлов во всех версиях, следовательно создаётся идентичная копия называемая хранилище того, что хранится на сервере. Именно поэтому процесс называется клонированием. Исходник клона запоминается как “origin”.
+
This creates a new directory called “qt” and downloads the source code into it. It also downloads the entire history of all files in all versions, therefore creating an identical copy called repository of what is stored on the server. That is why the process is called cloning. The source of the clone is remembered as the “origin”.
-
Вы можете создать новый клон, просто скопировав каталог, например, на USB-накопитель. Новый каталог будет тоже самодостаточным.
+
You can create new clones simply by copying the directory, for example onto a USB stick. The new directory will be self-contained, too.
-
Сейчас мы имеем все изменения внутри хранилища, вы можете работать полностью автономно. Соединение с сервером gitorious.org необходимо только, когда вам необходимо получить новые изменения исходного кода или отправить свои.
+
Now that you have all the changes inside the repository, you can work 100% offline. A connection to the gitorious.org server is only necessary when you need to fetch new source code changes or push upstream.
-
=== Просмотр исходного кода ===
+
=== Inspecting the source code ===
-
Эта секция знакомит с журналом Git, командами ''show'' (показать) и ''blame'' (авторство) для поиска в истории проекта.
+
This section introduces the git log, show and blame commands to find out the history of the project.
-
Выполните команду ''log'', чтобы увидеть последние изменения:
+
Run the log command to view recent changes:
-
{{Команда|$ git log}}
+
{{code|bash|code=$ git log}}
-
Эта программа запускает страничную программу позволяющую вам прокручивать список зафиксированных изменений с помощью курсора и клавиш "Page Up/Down". Чтобы врнуться в оболочку нажмите клавишу ‘q’.
+
This command launches a pager program allowing you to scroll through the list of committed changes with the cursor and Page Up/Down keys. To return to the shell press the ‘q’ key.
-
Команда ''log'' принимает аргументы, такие как <code>-n</code>, чтобы ограничить количество изменений. Например, чтобы напечатать последние три изменения выполните:
+
The log command accepts options, such as -n to limit the number of changes. For example to list the last three changes run:
-
{{Команда|$ git log -n3}}
+
{{code|bash|code=$ git log -n3}}
-
Чтобы ограничить вывод команды ''log'', например, чтобы показать только те изменения, которые затрагивают один или множество файлов/каталогов, вы можете использовать следующие аргументы:
+
To limit the output of the log command, e.g., to show only changes that affect one or multiple files/directories, you can use the following options:
-
{{Команда|$ git log src/corelib/kernel
+
{{code|bash|code=$ git log src/corelib/kernel
$ git log src/gui/kernel/qwidget.cpp
$ git log src/gui/kernel/qwidget.cpp
$ git log examples/examples.pro examples/painting/basicdrawing/main.cpp}}
$ git log examples/examples.pro examples/painting/basicdrawing/main.cpp}}
-
Существуют различные способы ограничения вывода команды ''log'', сверх описанных здесь. За подробностями обращайтесь к документации по ''git log'', в частности к разделу “''Commit Limiting''”.
+
There are various ways of limiting the output of the log command, beyond the ones described here. Refer to git log’s documentation for more details, particularly the “Commit Limiting” section.
-
Изменения в git идентифицируются с помощью уникальной контрольной суммы SHA1. Контрольная сумма находится в первой строке вывода команды ''git log''. Например:<pre>
+
Changes in git are identified with a unique SHA1 checksum. The checksum is on the first line of the git log output. For example:<pre>
commit 211bea9838bcc2acd7f54b65468fe1be2d81b1e0
commit 211bea9838bcc2acd7f54b65468fe1be2d81b1e0
Author: Denis Dzyubenko  
Author: Denis Dzyubenko  
Строка 55: Строка 54:
     Reviewed-by: Prasanth</pre>
     Reviewed-by: Prasanth</pre>
-
Вы можете просматривать правки используя команду ''git show'' c конкретным ''id'' правки в качестве аргумента. Следующая команда показывает все изменения выше, в том числе разницу (diff):
+
You can inspect commits using the git show command with the commit id as argument. The following command shows the entire change above including a diff:
{{code|bash|code=$ git show 211bea9838bcc2acd7f54b65468fe1be2d81b1e0}}
{{code|bash|code=$ git show 211bea9838bcc2acd7f54b65468fe1be2d81b1e0}}
Строка 61: Строка 60:
{{code|bash|code=$ git show}}
{{code|bash|code=$ git show}}
-
Команды git ''show'' и ''log'' позволяют просматривать историю проекта или отдельные файлы. Иногда, также удобно просматривать исходный код построчно, например, когда вы хотите узнать, кто написал определённый фрагмент кода. Git предоставляет такую возможность с помощью команды ''blame'':
+
The git show and log commands allow to inspect the history of the project or individual files. Sometimes it is also useful to inspect source code on a line-by-line basis, for example when you would like to find out who introduced a certain snippet of code. Git provides this functionality with the blame command:
{{code|bash|code=$ git blame src/gui/kernel/qwidget.cpp}}
{{code|bash|code=$ git blame src/gui/kernel/qwidget.cpp}}
-
Вывод этой команды показываемый постранично разделён на колонки. Первая колонка показывает id правки, сопровождаемый автором и датой для каждой строки.
+
The output of this command shown in a pager is split into columns. The first column shows the commit id, followed by the author and date for each line.
-
Git специализируется на отслеживании содержимого файлов, имя файла менее важно, чем исходный код который он содержит. Следовательно git blame может автоматически обнаруживать, например, что функция была перемещена из одного файла в другой.
+
Git specializes in tracking the content of files, the name of a file is less important than the source code it contains. Therefore git blame can automatically detect, for example, that a function was moved from one file to another.
-
=== Внесение изменений ===
+
=== Making changes ===
-
==== Настройки для изменений ====
+
==== Setting up for changes ====
-
Предыдущие разделы описывали, как клонировать хранилище, и как просматривать историю проекта. Этот раздел, наконец, описывает, как создавать историю, посредством записи изменений в новых праках и отслеживание правок в ветках.
+
The previous sections explained how to clone the repository and how to find out the history of the project. This section finally shows how to create history, through the recording of changes in new commits and the tracking of commits in branches.
-
Тем не мение, сначала вы должны зарегестрировать ваше имя и электропочту с помощью git, чтобы использовать для правок, которые вы создаёте. Вам необходимо выполнить эту команду только однажды:{{code|bash|code=
+
However, first you have to register your name and e-mail address with git, to be used for commits we create. You need to run these commands only once:{{code|bash|code=
$ git config user.name "Your Name"
$ git config user.name "Your Name"
$ git config user.email "me@example.com"}}
$ git config user.email "me@example.com"}}
-
Сейчас, также, подходящий момент, чтобы установить шаблон правок, который мы используем в Qt Software:
+
This is also a good time to install the commit template we use in Qt Software:
{{code|bash|code=$ git config commit.template .commit-template}}
{{code|bash|code=$ git config commit.template .commit-template}}
-
Следующий шаг - определить, на какой ветке разработки мы находимся. В git ветки имеют очень лёгкую идею, которая позволяет идентифицировать правки по имени. Каждая правка имеет ссылку на её родительскую правку(и), корые формирует исотрию. Команда ''git branch'', без аргументов, отображает список локальных веток также, как и веток в данный момент checked out:
+
The next step is to identify on what branch of development we are on. In git branches are a very lightweight concept that allow identifying a commit by name. Each commit has a reference to its parent commit(s), which forms the history. The git branch command, without any arguments, displays the list of local branches as well as the branch currently checked out:
{{code|bash|code=$ git branch
{{code|bash|code=$ git branch
* master}}
* master}}
-
Вывод команды показывает, что у нас имеется только одна локальная ветка, называемая “master”, а символ “*” указывает, что она является текущей веткой. Имя “master”, в разработке с помощью git, обычно описывает главную (main) линию разработки.
+
The output shows that we have only one local branch called “master” and the “*” indicates that it is the current branch. The name “master” in git development usually describes the main line of development.
-
Кроме ваших локальных веток, git также запоминает ветки в исходном (origin) хранилище. Ключ “-r” показывает их, предваряя строкой “origin”:
+
Besides your local branches git also remembers the branches in the origin repository. The “-r” option shows them, prefixed with “origin”:
{{code|bash|code=$ git branch -r
{{code|bash|code=$ git branch -r
   origin/4.5
   origin/4.5
Строка 92: Строка 91:
   origin/master}}
   origin/master}}
-
В целях разработки новых возможностей, мы можем создать новую ветку такой командой:
+
For the purpose of developing a new feature we can create a new branch with the same command:
{{code|bash|code=$ git branch my-feature origin/master}}
{{code|bash|code=$ git branch my-feature origin/master}}
-
Ветка “my-feature”, основаная на на ветке “master” исходного хранилища, теперь видна в списке веток:
+
The “my-feature” branch is based on the origin’s “master” branch, now visible in the list of branches:
{{code|bash|code=$ git branch
{{code|bash|code=$ git branch
* master
* master
   my-feature}}
   my-feature}}
-
Команда ''git checkout'' также может изменить текущую ветку:
+
The git checkout command can also change the current branch:
{{code|bash|code=$ git checkout my-feature}}
{{code|bash|code=$ git checkout my-feature}}
-
Переключено на ветку "my-feature"
+
Switched to branch "my-feature"
-
 
+
{{code|bash|code=$ git branch
{{code|bash|code=$ git branch
   master
   master
* my-feature}}
* my-feature}}
-
Она также обновит и файлы в вашем рабочем каталоге, до последней правки в новой текущей ветке. Новые правки будут записаны в ветку “my-feature” вместо предыдущей - “master”.
+
This will also update the files in your working directory to match the latest commit in the new current branch. New commits will be recorded in “my-feature” instead of the previous “master” branch.
-
Вы можете иметь столько локальных веток, сколько захотите, они очень дёшевы. Каждая ветка использует всего несколько байт дискового пространства. Инструкции о том, как удалять ветки, пожалуйста смотрите в документации по команде ''git branch''.
+
You can have as many local branches as you like, they are very cheap. Each branch uses only few bytes of disk space. Please see the documentation of the git branch command for instructions on how to delete branches.
-
==== Реальное внесение изменений ====
+
==== Actually making the changes ====
-
Тепрь мы можем пойти дальше и начать вносить изменения:
+
Now we can go ahead and start making changes:
{{code|bash|code=$ edit src/corelib/tools/qstring.cpp}}
{{code|bash|code=$ edit src/corelib/tools/qstring.cpp}}
-
Команда ''diff'' показывает нам, что мы имеем изменения:
+
The diff command shows us what we have changed:
{{code|bash|code=$ git diff
{{code|bash|code=$ git diff
diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp
diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp
Строка 157: Строка 155:
     int lastIndexOf(const QRegExp &, int from = -1) const;}}
     int lastIndexOf(const QRegExp &, int from = -1) const;}}
-
Команда ''status'' даёт обзор того, что будет делать команда “''git commit''”:
+
The status command gives an overview of what “git commit” would do:
{{code|bash|code=$ git status
{{code|bash|code=$ git status
# On branch master
# On branch master
Строка 169: Строка 167:
no changes added to commit (use "git add" and/or "git commit -a")}}
no changes added to commit (use "git add" and/or "git commit -a")}}
-
Следуя рекомендациям в выводе предыдущей команды мы помечаем файлы qstring.cpp и .h для включения в следующую фиксацию изменений (commit):
+
Following the recommendation in the output we mark qstring.cpp and .h as files to be included in the next commit:
{{code|bash|code=$ git add src/corelib/tools/qstring.cpp src/corelib/tools/qstring.h
{{code|bash|code=$ git add src/corelib/tools/qstring.cpp src/corelib/tools/qstring.h
$ git status
$ git status
Строка 181: Строка 179:
# Untracked files not listed (use -u option to show untracked files)}}
# Untracked files not listed (use -u option to show untracked files)}}
-
И, в конце, мы фиксируем изменения, т.е. создаём правку в хранилище (commit):
+
And finally we create a new commit:
{{code|bash|code=$ git commit -m "Add a new reversed() function to QString"
{{code|bash|code=$ git commit -m "Add a new reversed() function to QString"
[my-feature c8d9c54] Add a new reversed() function to QString}}
[my-feature c8d9c54] Add a new reversed() function to QString}}
-
Обычно git откроет новый текстовый редактор, если вы пропускаете ключ ''-m''.
+
Normally git will open a new text editor if you omit the -m parameter.
-
Помечая файлы для включения в правку, мы добавляем их в область подготовки git’а (staging area). Область подготовки&nbsp;&mdash; это мощная концепция, делающая лёгкой работу с множеством файлов одновременно while still creating small incremental commits.
+
Marking files to be included in commits means adding them to git’s staging area. The staging area is a powerful concept, making it easy to work on multiple files simultaenously while still creating small incremental commits.
-
=== Общие операции и исправления ошибок ===
+
=== Common operations and fixing mistakes ===
-
Этот раздел предлагает рецепты для исправления частых ошибок и объясняет общие операции, такие как просмотр ваших изменений перед фиксацией используя команду ''diff''.
+
This section gives recipes for fixing common mistakes and explains common operations such as reviewing your changes before committing using the diff command.
-
Вы можете отменить изменения в файле до его фиксации в хранилище с помощью команды ''checkout'':
+
You can undo changes to a file before it is committed with the checkout command:
-
{{Команда|$ git checkout HEAD -- src/corelib/tools/qstring.cpp}}
+
$ git checkout HEAD -- src/corelib/tools/qstring.cpp
-
Если вы случайно пометили файл для последующей фиксации вы можете сбросить его, например, такой командой:
+
If you have accidentially marked a file for the next commit you can reset it like this:
-
{{Команда|$ git reset HEAD -- src/corelib/tools/qstring.cpp}}
+
$ git reset HEAD -- src/corelib/tools/qstring.cpp
-
Это исключит файл из последующей фиксации и оставит его в вашем рабочем каталоге без последних изменений.
+
This will exclude the file from the next commit and leave it in your working directory unchanged with your modifications intact.
-
После изменения файла команда ''git diff'' показывает строки, которые вы изменили. Отличия вычисляются на основе файла в вашем рабочем каталоге и фала, который был добавлен в область подготовки используя команду ''git add''.
+
After changing a file the git diff command shows the lines you have modified. The difference is calculated from the file in your working directory and the file when it was added to the staging area using git add.
-
Если вы хотите посмотреть отличия между файлом в области подготовки и последней правкой вы можете передать ключ в команду ''diff'':
+
If you want to show the difference between the file in the staging area and the last commit you have to pass an option to the diff command:
-
{{Команда|$ git diff --cached}}
+
$ git diff --cached
-
Команда ''diff'' может принимать в качестве аргументов и каталоги и файлы, чтобы ограничить вывод.
+
The diff command optionally takes directories and files as argument, to limit the output.
-
Переименование файлов в git осуществляется переименовыванием их в вашем рабочем каталоге используя команду/инструмент по вашему выбору. Как только вы переименовали файл вы должны сказать ''git'''у:
+
Files are renamed in git by renaming them in your working directory using a command/tool of your choice. Once you've renamed a file you have to tell git:
-
{{Команда|# oldfile.cpp переименован в newfile.cpp используя графический файловый менеджер
+
[ rename oldfile.cpp to newfile.cpp using a graphical file manager ]
$ git rm oldfile.cpp
$ git rm oldfile.cpp
-
$ git add newfile.cpp}}
+
$ git add newfile.cpp
-
В качестве альтернативы, вы можете использовать команду ''mv'':
+
Alternatively you can use the convenience mv command:
-
{{Команда|$ git mv oldfile.cpp newfile.cpp}}
+
$ git mv oldfile.cpp newfile.cpp
-
Одна из сильнх сторон git’а  - то, что он не обращает внимание на то, как как именно вы изменяете свои файлы. Он оптимизирован, чтобы выяснить, что изменилось. Например, когда копируете файл в ваш исходный код, то достаточно просто выполнить “git add” с именем нового файла. Git автоматически найдёт откуда файл был скопирован.
+
One of git’s strengths is that it does not care how exactly you change your files. It is optimized to find out what changed after the fact. For example when copying a file in your source code it is enough to simply run “git add” with the new file. Git automatically finds out where the file was copied from.
-
=== Отправка и обновление ваших изменений ===
+
=== Sending and updating your changes ===
-
==== Получение обновлений ====
+
==== Obtaining updates ====
-
После изучения предыдущих глав (разделов) вы должны уметь делать небольшие изменения, посредством создания правок в ваши локальные ветки. Этот раздел по шагам проведёт вас через объединение ваших изменений с последними изменениями from the upstream repository и объяснит, как создать отдельные файлы-заплатки для подачи в проект.
+
After studying the previous chapters you should be able to develop small changes by creating commits in your local branches. This chapter guides you through the steps of combining your changes with the latest changes from the upstream repository and explains how to create separate patch files for submission into the project.
-
Во время разработки кода в вашем локальном клоне проекта, оригинальное хранилище эволюционирует и принимает новые изменения. Сначала мы обновляем наше зеркало правок в оригинальном хранилище, используя команду ''fetch'':
+
While developing code in your local clone of the project, the original repository evolves and sees new changes. First we update our mirror of the commits in the original repository using the fetch command:
-
{{Команда|$ git fetch
+
$ git fetch
remote: Counting objects: 3013, done.
remote: Counting objects: 3013, done.
remote: Compressing objects: 100% (395/395), done.
remote: Compressing objects: 100% (395/395), done.
Строка 229: Строка 227:
Resolving deltas: 100% (1455/1455), completed with 892 local objects.
Resolving deltas: 100% (1455/1455), completed with 892 local objects.
From git://gitorious.org/qt/qt.git
From git://gitorious.org/qt/qt.git
-
   be7384d..822114e  master    -> origin/master}}
+
   be7384d..822114e  master    -> origin/master
-
Вывод команды указывает, что ветка “master” в оригинальном хранилище gitorious.org была обновлена с помощью новых правок и эти правки теперь доступны в ветке origin/master, являющейся локальным отображением.
+
The output indicates that the “master” branch in the original gitorious.org repository has been updated with new commits and these commits are now available in the locally mirrored origin/master branch.
-
Вы можете просмотреть новые изменения используя команды ''log'' или ''show'':
+
You can inspect the new changes using the log or show commands:
-
{{Команда|$ git log -p origin/master}}
+
$ git log -p origin/master
-
Команда ''log'' будет включать различия индивидуальных правок если вы укажите аргумент -p.
+
The log command will include the diffs of the individual commits if you specify the -p argument.
Updating your branch with the downloaded, new changes
Updating your branch with the downloaded, new changes
To combine the new changes with our own local commits we use a technique called rebasing:
To combine the new changes with our own local commits we use a technique called rebasing:
-
{{Команда|$ git checkout my-feature
+
$ git checkout my-feature
-
$ git rebase origin/master}}
+
$ git rebase origin/master
After making “my-feature” the current branch git rebase will first re-initialize the branch to be identical to origin/master, which includes the new commits. Then it will apply each of your commits, basing them on top of the newly initialized branch.
After making “my-feature” the current branch git rebase will first re-initialize the branch to be identical to origin/master, which includes the new commits. Then it will apply each of your commits, basing them on top of the newly initialized branch.
-
==== Отправка ваших изменений для рассмотрения ====
+
==== Sending your feature for review ====
When you decide that the work in your “my-feature” branch is complete then the next step is to make your changes available for upstream inclusion. This is done by creating a personal clone of Qt on Gitorious, and then pushing your branch to this repository.  
When you decide that the work in your “my-feature” branch is complete then the next step is to make your changes available for upstream inclusion. This is done by creating a personal clone of Qt on Gitorious, and then pushing your branch to this repository.  
Suppose your clone of Qt is at http://gitorious.org/~simon/qt/simons-clone you can use the git push command together with the push url to upload your branch there:
Suppose your clone of Qt is at http://gitorious.org/~simon/qt/simons-clone you can use the git push command together with the push url to upload your branch there:
-
{{Команда|$ git push git@gitorious.org:~simon/qt/simons-clone.git my-feature}}
+
$ git push git@gitorious.org:~simon/qt/simons-clone.git my-feature
Once uploaded to Gitorious you can then create merge requests for inclusion of your commits into other projects.
Once uploaded to Gitorious you can then create merge requests for inclusion of your commits into other projects.
Строка 255: Строка 253:
Note: You only need to create one personal clone — there is no need for a separate repository for each fix, use branches for that.
Note: You only need to create one personal clone — there is no need for a separate repository for each fix, use branches for that.
-
=== В заключение ===
+
=== Conclusion ===
We hope that this introductions helps you familiarize yourself with the use of git. The official Git documentation web page is a very good continuation point:
We hope that this introductions helps you familiarize yourself with the use of git. The official Git documentation web page is a very good continuation point:
http://git-scm.com/documentation
http://git-scm.com/documentation
-
 
-
[[Категория:Git]]
 
-
[[Категория:Qt]]
 

Пожалуйста, обратите внимание, что все ваши добавления могут быть отредактированы или удалены другими участниками. Если вы не хотите, чтобы кто-либо изменял ваши тексты, не помещайте их сюда.
Вы также подтверждаете, что являетесь автором вносимых дополнений, или скопировали их из источника, допускающего свободное распространение и изменение своего содержимого (см. Wiki.crossplatform.ru:Авторское право). НЕ РАЗМЕЩАЙТЕ БЕЗ РАЗРЕШЕНИЯ ОХРАНЯЕМЫЕ АВТОРСКИМ ПРАВОМ МАТЕРИАЛЫ!


Шаблоны, использованные на текущей версии страницы: