Участник:Lit-uriy/GitIntroductionWithQt

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

(Различия между версиями)
Перейти к: навигация, поиск
(Настройки для изменений: немного перевёл)
(Реальное внесение изменений: немного перевёл)
Строка 113: Строка 113:
==== Реальное внесение изменений ====
==== Реальное внесение изменений ====
-
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}}
-
The diff command shows us what we have changed:
+
Команда ''diff'' показывает нам, что мы имеем изменения:
{{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: Строка 157:
     int lastIndexOf(const QRegExp &, int from = -1) const;}}
     int lastIndexOf(const QRegExp &, int from = -1) const;}}
-
The status command gives an overview of what “git commit” would do:
+
Команда ''status'' даёт обзор того, что будет делать команда “''git commit''”:
{{code|bash|code=$ git status
{{code|bash|code=$ git status
# On branch master
# On branch master
Строка 169: Строка 169:
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")}}
-
Following the recommendation in the output we mark qstring.cpp and .h as files to be included in the next commit:
+
Следуя рекомендациям в выводе предыдущей команды мы помечаем файлы qstring.cpp и .h для включения в следующую фиксацию изменений (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: Строка 181:
# Untracked files not listed (use -u option to show untracked files)}}
# Untracked files not listed (use -u option to show untracked files)}}
-
And finally we create a new commit:
+
И, в конце, мы фиксируем изменения, т.е. создаём правку в хранилище (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''.
+
Обычно git откроет новый текстовый редактор, если вы пропускаете ключ ''-m''.
-
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.
+
Помечая файлы для включения в правку, мы добавляем их в область подготовки git’а (staging area). Область подготовки — это мощная концепция, делающая лёгкой работу с множеством файлов одновременно while still creating small incremental commits.
=== Common operations and fixing mistakes ===
=== Common operations and fixing mistakes ===

Версия 19:10, 22 сентября 2009

40px Эта статья является переводом руководства: GitIntroductionWithQt

Введение

Этот документ является простым руководством показывающим процедуры необходимые для разработки и сопровождения заплаток on top of Qt. Оно не заменяет руководство по Git deliberately skipping over other established but different git-based workflows.

Содержание


Получение исходного кода Qt

Этот раздел показывает, как загрузить исходный код, и объясняет концепцию Git-хранилища.

Во-первых, мы извлекаем исходный код Qt, используя команду git clone:

$ git clone git://gitorious.org/qt/qt.git
cd qt

Она создаст новый каталог называемый “qt” и загружает исходный код в него. Она также загружает полную историю всех файлов во всех версиях, следовательно создаётся идентичная копия – называемая хранилище – того, что хранится на сервере. Именно поэтому процесс называется клонированием. Исходник клона запоминается как “origin”.

Вы можете создать новый клон, просто скопировав каталог, например, на USB-накопитель. Новый каталог будет тоже самодостаточным.

Сейчас мы имеем все изменения внутри хранилища, вы можете работать полностью автономно. Соединение с сервером gitorious.org необходимо только, когда вам необходимо получить новые изменения исходного кода или отправить свои.

Просмотр исходного кода

Эта секция знакомит с журналом Git, командами show (показать) и blame (авторство) для поиска в истории проекта.

Выполните команду log, чтобы увидеть последние изменения:

$ git log

Эта программа запускает страничную программу позволяющую вам прокручивать список зафиксированных изменений с помощью курсора и клавиш "Page Up/Down". Чтобы врнуться в оболочку нажмите клавишу ‘q’.

Команда log принимает аргументы, такие как -n, чтобы ограничить количество изменений. Например, чтобы напечатать последние три изменения выполните:

$ git log -n3

Чтобы ограничить вывод команды log, например, чтобы показать только те изменения, которые затрагивают один или множество файлов/каталогов, вы можете использовать следующие аргументы:

$ git log src/corelib/kernel
$ git log src/gui/kernel/qwidget.cpp
$ git log examples/examples.pro examples/painting/basicdrawing/main.cpp

Существуют различные способы ограничения вывода команды log, сверх описанных здесь. За подробностями обращайтесь к документации по git log, в частности к разделу “Commit Limiting”.

Изменения в git идентифицируются с помощью уникальной контрольной суммы SHA1. Контрольная сумма находится в первой строке вывода команды git log. Например:
commit 211bea9838bcc2acd7f54b65468fe1be2d81b1e0
Author: Denis Dzyubenko 
Date:   Fri Apr 24 14:18:17 2009 +0200

    Re-send network request properly when the socket is in Closing state.

    This fixes the "QAbstractSocket::connectToHost() called when already
    connecting/connected to ". The issue was that we were trying
    to call connect on a socket that was in a Closing state. We have to
    wait for the disconnected signal before we try to connect again.

    Reviewed-by: Prasanth

Вы можете просматривать правки используя команду git show c конкретным id правки в качестве аргумента. Следующая команда показывает все изменения выше, в том числе разницу (diff):

$ git show 211bea9838bcc2acd7f54b65468fe1be2d81b1e0

To see the last command you made use show without any arguments:

$ git show

Команды git show и log позволяют просматривать историю проекта или отдельные файлы. Иногда, также удобно просматривать исходный код построчно, например, когда вы хотите узнать, кто написал определённый фрагмент кода. Git предоставляет такую возможность с помощью команды blame:

$ git blame src/gui/kernel/qwidget.cpp

Вывод этой команды – показываемый постранично – разделён на колонки. Первая колонка показывает id правки, сопровождаемый автором и датой для каждой строки.

Git специализируется на отслеживании содержимого файлов, имя файла менее важно, чем исходный код который он содержит. Следовательно git blame может автоматически обнаруживать, например, что функция была перемещена из одного файла в другой.

Внесение изменений

Настройки для изменений

Предыдущие разделы описывали, как клонировать хранилище, и как просматривать историю проекта. Этот раздел, наконец, описывает, как создавать историю, посредством записи изменений в новых праках и отслеживание правок в ветках.

Тем не мение, сначала вы должны зарегестрировать ваше имя и электропочту с помощью git, чтобы использовать для правок, которые вы создаёте. Вам необходимо выполнить эту команду только однажды:
$ git config user.name "Your Name"
$ git config user.email "me@example.com"

Сейчас, также, подходящий момент, чтобы установить шаблон правок, который мы используем в Qt Software:

$ git config commit.template .commit-template

Следующий шаг - определить, на какой ветке разработки мы находимся. В git ветки имеют очень лёгкую идею, которая позволяет идентифицировать правки по имени. Каждая правка имеет ссылку на её родительскую правку(и), корые формирует исотрию. Команда git branch, без аргументов, отображает список локальных веток также, как и веток в данный момент checked out:

$ git branch
* master

Вывод команды показывает, что у нас имеется только одна локальная ветка, называемая “master”, а символ “*” указывает, что она является текущей веткой. Имя “master”, в разработке с помощью git, обычно описывает главную (main) линию разработки.

Кроме ваших локальных веток, git также запоминает ветки в исходном (origin) хранилище. Ключ “-r” показывает их, предваряя строкой “origin”:

$ git branch -r
  origin/4.5
  origin/HEAD -> origin/master
  origin/master

В целях разработки новых возможностей, мы можем создать новую ветку такой командой:

$ git branch my-feature origin/master

Ветка “my-feature”, основаная на на ветке “master” исходного хранилища, теперь видна в списке веток:

$ git branch
* master
  my-feature

Команда git checkout также может изменить текущую ветку:

$ git checkout my-feature

Переключено на ветку "my-feature"

$ git branch
  master
* my-feature

Она также обновит и файлы в вашем рабочем каталоге, до последней правки в новой текущей ветке. Новые правки будут записаны в ветку “my-feature” вместо предыдущей - “master”.

Вы можете иметь столько локальных веток, сколько захотите, они очень дёшевы. Каждая ветка использует всего несколько байт дискового пространства. Инструкции о том, как удалять ветки, пожалуйста смотрите в документации по команде git branch.

Реальное внесение изменений

Тепрь мы можем пойти дальше и начать вносить изменения:

$ edit src/corelib/tools/qstring.cpp

Команда diff показывает нам, что мы имеем изменения:

$ git diff
diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp
index 375d672..d7345e6 100644
--- a/src/corelib/tools/qstring.cpp
+++ b/src/corelib/tools/qstring.cpp
@@ -2855,6 +2855,20 @@ int QString::count(const QRegExp& rx) const
     Same as size().
 */
 
+/*!
+    \since 4.6
+
+    Returns this string in reverse order.
+*/
+QString QString::reversed() const
+{
+    QString result;
+    result.reserve(d->size);
+    for (int i = 0; i < d->size; ++i)
+        result[i] = d->data[d->size - i];
+    return result;
+}
+
 
 /*!
     \enum QString::SectionFlag
diff --git a/src/corelib/tools/qstring.h b/src/corelib/tools/qstring.h
index 1493dce..077bda9 100644
--- a/src/corelib/tools/qstring.h
+++ b/src/corelib/tools/qstring.h
@@ -195,6 +195,8 @@ public:
     int count(QChar c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
     int count(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
 
+    QString reversed() const;
+
 #ifndef QT_NO_REGEXP
     int indexOf(const QRegExp &, int from = 0) const;
     int lastIndexOf(const QRegExp &, int from = -1) const;

Команда status даёт обзор того, что будет делать команда “git commit”:

$ git status
# 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)
#
#       modified:   src/corelib/tools/qstring.cpp
#       modified:   src/corelib/tools/qstring.h
#
no changes added to commit (use "git add" and/or "git commit -a")

Следуя рекомендациям в выводе предыдущей команды мы помечаем файлы qstring.cpp и .h для включения в следующую фиксацию изменений (commit):

$ git add src/corelib/tools/qstring.cpp src/corelib/tools/qstring.h
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#       modified:   src/corelib/tools/qstring.cpp
#       modified:   src/corelib/tools/qstring.h
#
# Untracked files not listed (use -u option to show untracked files)

И, в конце, мы фиксируем изменения, т.е. создаём правку в хранилище (commit):

$ git commit -m "Add a new reversed() function to QString"
[my-feature c8d9c54] Add a new reversed() function to QString

Обычно git откроет новый текстовый редактор, если вы пропускаете ключ -m.

Помечая файлы для включения в правку, мы добавляем их в область подготовки git’а (staging area). Область подготовки — это мощная концепция, делающая лёгкой работу с множеством файлов одновременно while still creating small incremental commits.

Common operations and fixing mistakes

This section gives recipes for fixing common mistakes and explains common operations such as reviewing your changes before committing using the diff command.

You can undo changes to a file before it is committed with the checkout command:

$ 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

This will exclude the file from the next commit and leave it in your working directory unchanged with your modifications intact.

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.

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

The diff command optionally takes directories and files as argument, to limit the output.

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:

[ rename oldfile.cpp to newfile.cpp using a graphical file manager ]
$ git rm oldfile.cpp
$ git add newfile.cpp

Alternatively you can use the convenience mv command:

$ git mv oldfile.cpp newfile.cpp

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.

Отправка и обновление ваших изменений

Получение обновлений

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.

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
remote: Counting objects: 3013, done.
remote: Compressing objects: 100% (395/395), done.
remote: Total 1730 (delta 1455), reused 1582 (delta 1332)
Receiving objects: 100% (1730/1730), 1.13 MiB

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.

You can inspect the new changes using the log or show commands:

$ git log -p origin/master

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

To combine the new changes with our own local commits we use a technique called rebasing:

$ git checkout my-feature
$ 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.

Отправка ваших изменений для рассмотрения

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:

$ 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.

Note: You only need to create one personal clone — there is no need for a separate repository for each fix, use branches for that.

В заключение

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