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

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

Перейти к: навигация, поиск
Внимание: Вы не представились системе. Ваш IP-адрес будет записан в историю изменений этой страницы.
Правка может быть отменена. Пожалуйста, просмотрите сравнение версий, чтобы убедиться, что это именно те изменения, которые вас интересуют, и нажмите «Записать страницу», чтобы изменения вступили в силу.
Текущая версия Ваш текст
Строка 9: Строка 9:
__TOC__
__TOC__
-
=== Получение исходного кода Qt ===
+
=== Getting the Qt source code ===
Этот раздел показывает, как загрузить исходный код, и объясняет концепцию Git-хранилища.
Этот раздел показывает, как загрузить исходный код, и объясняет концепцию Git-хранилища.
Строка 84: Строка 84:
* 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: Строка 92:
   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: Строка 156:
     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: Строка 168:
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: Строка 180:
# 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). Область подготовки — это мощная концепция, делающая лёгкой работу с множеством файлов одновременно 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.
Строка 231: Строка 230:
   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
Строка 245: Строка 244:
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.  
Строка 255: Строка 254:
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:

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


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