Важно

Перевод - это работа сообщества : ссылка:Вы можете присоединиться. Эта страница в настоящее время переводится |прогресс перевода|.

1. Пошаговое руководство

Примечание

Хотя для демонстрации процесса используется QGIS-Documentation, все команды и шаги, показанные ниже, применимы и к QGIS-Website.

Если вы читаете эти строки, то наверняка хотите внести свой вклад в написание документации по QGIS и ищете руководство к действию. Вы пришли в нужное место! В этом документе мы расскажем вам о различных способах достижения этой цели, покажем основные шаги, которые необходимо выполнить, приемы, которые можно использовать, и ловушки, о которых следует знать.

Если вам нужна помощь, не стесняйтесь спрашивать в комментариях к отчету о проблеме, которую вы пытаетесь исправить, или пишите в список QGIS-community-team. Ознакомьтесь с общей информацией о поддержке сообщества QGIS <https://qgis.org/resources/support/>`_.

Теперь давайте погрузимся в процесс.

Исходные тексты документации хранятся с помощью системы контроля версий git и доступны на GitHub по адресу https://github.com/qgis/QGIS-Documentation. Список проблем, которые нужно исправить, и функций, которые нужно объяснить, можно найти на https://github.com/qgis/QGIS-Documentation/issues.

Совет

Если вы впервые участвуете в проекте и не знаете, с чего начать, возможно, вам будет интересно разобраться с нашими «приветственными» отчетами о проблемах <https://github.com/qgis/QGIS-Documentation/contribute>`_.

Существует два основных способа изменения файлов, не исключающих друг друга:

  1. Использование веб-интерфейса GitHub

  2. Использование инструментов командной строки Git.

1.1. Использование веб-интерфейса GitHub

Веб-интерфейс GitHub позволяет выполнять следующие действия:

  • редактировать файлы

  • просмотрите и зафиксируйте изменения

  • оформите запрос на притяжение, чтобы ваши изменения были добавлены в основной репозиторий

  • создавать, обновлять или удалять ветви

Если вы еще не знакомы с git и лексикой GitHub, вам стоит прочитать проект GitHub Hello-world, чтобы узнать базовую лексику и действия, которые будут использоваться ниже.

Примечание

Если вы устраняете проблему, о которой было сообщено

Если вы вносите изменения для исправления проблемы, добавьте комментарий к отчету о проблеме, чтобы назначить ее своей. Это не позволит нескольким людям работать над одной проблемой.

1.1.1. Форк QGIS-Документация

Предполагая, что у вас уже есть аккаунт на GitHub <https://github.com/signup>`_, сначала вам нужно форкнуть исходные файлы документации.

Перейдите на страницу QGIS-документация репозитория и нажмите на кнопку githubFork в правом верхнем углу.

В вашем аккаунте на GitHub вы найдете репозиторий QGIS-документация (https://github.com/<YourName>/QGIS-Documentation). Этот репозиторий является копией официального репозитория QGIS-Documentation, где у вас есть полный доступ на запись, и вы можете вносить изменения, не затрагивая официальную документацию.

1.1.2. Внести изменения

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

Альтернатива 1: Используйте ярлык Редактировать на GitHub

Pages on the QGIS documentation website can be edited quickly and easily by clicking on the Edit on GitHub link at the top right of each page, or in the drop-down menu at the bottom of the left sidebar.

  1. Это откроет файл в ветке qgis:master с сообщением в верхней части страницы о том, что у вас нет доступа на запись в это хранилище и ваши изменения будут применены к новой ветке вашего репозитория.

  2. Внесите свои изменения. Поскольку документация написана с использованием синтаксиса reStructureText, в зависимости от ваших изменений, вам может понадобиться руководствоваться Руководством по написанию.

  3. Once you have finished modifying the file, press Commit changes… and add a short title explaining your changes. You can also provide a more detailed explanation, if necessary.

  4. Press Propose changes, saving the modifications to your repository. This will generate a dedicated branch (patch-xxx) in your repository and the web browser will open the Comparing changes page.

    • If the issue you are addressing does not need any further changes, jump to the Share your changes via Pull Request section below.

    • Если вы хотите внести дополнительные изменения перед отправкой в QGIS, выполните следующие действия:

      1. Перейдите к вашему форку QGIS-документации (https://github.com/<YourName>/QGIS-Documentation)

      2. Click on githubBranch and search for the new patch-xxx branch.

      3. Select it. The githubBranch button will now display Branch: patch-xxx.

      4. Jump down to the Modify files section below.

Альтернатива 2: Создайте специальную ветку в репозитории документации

Вы можете редактировать файлы прямо из форка Документации QGIS.

First, make sure that your master branch is up to date with upstream, i.e. qgis/QGIS-Documentation:master branch. To do so:

  1. Перейдите на главную страницу вашего репозитория, то есть https:/<YourName>/github.com//QGIS-Documentation. Ветка master должна быть активной с упоминанием того, обновлена ли она до qgis/QGIS-Documentation:master или нет.

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

    Если за ним стоят только коммиты:

    1. Expand the Sync fork drop-down menu on the right. You can:

      • Compare the branches and see new changes in the upstream branch you do not yet have in yours

      • Fetch and merge: brings changes from the upstream branch into yours.

    2. Click Fetch and merge: after the process, your branch is mentioned as up to date with qgis/QGIS-Documentation:master.

  2. Click on githubBranch in the upper left corner of your forked QGIS-Documentation repository and enter a unique name in the text field to create a new branch. It is advised that the name of the new branch relates to the problem you intend to fix. Convenient for identifying the branch later.

  3. Press Create branch <branch_name> from master. The githubBranch button should now display branch_name.

  4. You are ready to start new changes on top of your new branch.

Внимание

Вносите изменения в специальную ветку, никогда в мастер ветку

По правилам, не вносите изменения в свою ветку master, за исключением тех случаев, когда вы сливаете изменения из ветки master в свою копию репозитория QGIS-Documentation. Отдельные ветки позволяют вам работать над несколькими проблемами одновременно, не вмешиваясь в работу других веток. Если вы допустите ошибку, вы всегда можете удалить ветку и начать заново, создав новую из основной ветки.

1.1.3. Изменение файлов

  1. Make sure the branch you want to modify is active: its name is displayed in the top left menu or in the page URL.

  2. Browse the source files to the file that needs modifications.

  3. Press the githubEditPencil Edit this file button.

  4. Update the text following the writing guidelines

  5. Once you have finished modifying the file, press Commit changes… and add a short title explaining your changes. You can also provide a more detailed explanation, if necessary.

  6. Make sure Commit directly to the <branch_name> branch is selected.

  7. Press Commit changes to save your modifications in the branch.

  8. To update or add a new image file:

    1. Browse your branch to the folder of the file to update or add.

    2. Top right, use the Add files ► Upload files menu to select and load files from your drive. You can find hints for formatting an image for the docs at Managing Screenshots.

    3. If a file of the same name already exists, it gets overwritten.

    4. Commit once again your changes to the target branch.

  9. Repeat the previous steps for any other files that need to be updated to fix the issue.

1.1.4. Поделитесь своими изменениями через Pull Request

You need to make a pull request to integrate your changes into the official documentation.

Начните новый запрос на привлечение ресурсов

  1. If you used the Edit on GitHub link, after you commit your changes, GitHub automatically opens a new page comparing the changes you made in your patch-xxx branch to the qgis/QGIS-Documentation:master branch.

  2. In all the cases, the comparing changes page can be reached by going to the «Pull requests» page of your repository and click on New pull request.

Сравнить изменения

Если вы видите два диалоговых окна, в одном из которых написано база:мастер, а в другом сравнить:имя_ветви (см. рисунок), это означает, что изменения из одной из ваших веток будут слиты только в вашу мастер-ветку. Чтобы исправить это, нажмите на ссылку Сравнить все ветки.

../../_images/githubCompareAcrossForks.png

Рис. 1.8 Если ваша страница Сравнение изменений выглядит так, нажмите на ссылку Сравнить по форкам.

Вы увидите четыре выпадающих меню. Они позволят вам сравнить изменения, внесенные в вашу ветку, с мастер-веткой, в которую вы хотите слиться. К ним относятся:

  • базовый форк: форк, в который вы хотите слить свои изменения

  • база: ветвь базового форка, в которую вы хотите слить свои изменения

  • головная вилка: вилка, в которой есть изменения, которые вы хотите включить в базовую вилку

  • ** сравнить**: ветвь с этими изменениями

Выберите qgis/QGIS-документация в качестве базового форка с мастер в качестве базового, установите головной форк на ваш репозиторий <YourName>/QGIS-документация, и установите compare на вашу модифицированную ветку.

../../_images/githubCreatePullRequestComparison.png

Рис. 1.9 Сравнение изменений между qgis/QGIS- Документация и вашим репозиторием

Зеленая галочка с надписью Возможность слияния показывает, что ваши изменения могут быть слиты в официальную документацию без конфликтов.

Нажмите на кнопку Создать запрос на притяжение.

Предупреждение

Если вы видите githubCantMerge

Это означает, что существуют конфликты. Файлы, которые вы изменяете, не обновлены в ветке, на которую вы нацелились, потому что кто-то другой сделал коммит, который конфликтует с вашими изменениями. Вы всё ещё можете создать запрос, но вам нужно будет исправить все конфликты, чтобы завершить слияние.

Совет

Несмотря на то, что документация QGIS переводится, поддерживается самая последняя версия <https://docs.qgis.org/latest>`_ и исправляются существующие проблемы. Если вы исправляете проблемы для другого выпуска, измените базу с мастер на соответствующую ветку релиза_... в шагах выше.

Опишите ваш запрос на притяжение

A text box will open: fill in a title and any relevant description of the changes you are proposing.

Если это относится к определенному выпуску <https://github.com/qgis/QGIS-Documentation/issues>`_, добавьте номер выпуска к своим комментариям. Для этого введите # и номер проблемы (например #1234). Если перед комментарием стоит выражение исправить или закрыть, то соответствующий вопрос будет закрыт, как только запрос будет объединен.

Добавьте ссылки на все изменяемые страницы документации.

Нажмите на Создать запрос на притяжение.

Просмотр и комментирование запроса на выгрузку

Как видно из вышеизложенного, каждый может вносить изменения в документацию с помощью запросов на выгрузку. Точно так же каждый может просматривать запросы на изменения с вопросами и комментариями. Возможно, стиль написания не соответствует рекомендациям проекта, в изменении не хватает каких-то важных деталей или скриншотов, а может быть, все выглядит отлично и в полном порядке. Рецензирование помогает улучшить качество вклада, как по форме, так и по содержанию.

Чтобы просмотреть запрос на притяжение:

  1. Перейдите на страницу pull requests и нажмите на pull request, который вы хотите прокомментировать.

  2. В нижней части страницы вы найдете текстовое поле, в котором можно оставить общие комментарии о запросе.

  3. Чтобы добавить комментарии к определенным строкам,

    1. Click on githubFilesChanged and find the file you want to comment on. You may have to click on < > Display the source diff to see the changes.

    2. Прокрутите страницу до строки, которую вы хотите прокомментировать, и нажмите на githubBluePlus. Откроется текстовое поле, в котором вы сможете оставить комментарий.

Конкретные комментарии к строкам могут быть опубликованы либо:

  • как отдельные комментарии, используя кнопку Добавить отдельный комментарий. Они публикуются по мере добавления. Используйте эту кнопку только в том случае, если у вас мало комментариев или если вы отвечаете на другой комментарий.

  • или как часть обзора, нажав на кнопку Начать обзор. Ваши комментарии не отправляются автоматически после проверки, что позволяет вам отредактировать или отменить их впоследствии, добавить краткое изложение основных моментов обзора или глобальные инструкции относительно запроса на вынос и того, одобряете вы его или нет. Этот способ удобен, поскольку он более гибкий и позволяет структурировать обзор, редактировать комментарии, публиковать их, когда вы будете готовы, и отправлять одно уведомление последователям репозитория, а не по одному уведомлению на каждый комментарий. Получите более подробную информацию <https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/reviewing-proposed-changes-in-a-pull-request>`_.

../../_images/githubAddLineComment.png

Рис. 1.10 Комментирование строки с предложением об изменении

В комментариях к строкам могут содержаться предложения, которые автор заявки может применить к заявке. Чтобы добавить предложение, нажмите кнопку githubSuggestions Вставить предложение в верхней части текстового поля комментария и измените текст в блоке предложения.

Совет

Предпочитаем фиксировать предложения в запросе на вытягивание как пакет

Как автор pull request, при непосредственном включении отзывов рецензентов в свой pull request, избегайте использования кнопки Коммитировать предложение в нижней части комментария, если у вас много предложений, которые нужно рассмотреть, и вы предпочитаете добавлять их в виде пакетного коммита, то есть:

  1. Перейти на вкладку githubFilesChanged

  2. Нажмите Добавить предложение в пакет для каждой переформулировки, которую вы хотите включить. Вы увидите, что счетчик увеличивается по мере выполнения.

  3. Нажмите любую из кнопок Коммитировать предложения, когда будете готовы применить предложения к вашему pull request, и введите сообщение с описанием изменений.

Это добавит все изменения в вашу ветку как один коммит, что приведет к более разборчивой истории изменений и уменьшит количество уведомлений для последователей репозитория. Кстати, выполнение этой процедуры также сэкономит вам много кликов.

Внести исправления

Новый pull request будет автоматически добавлен в список Pull requests. Другие редакторы и администраторы будут просматривать ваш запрос на доработку и могут вносить предложения или просить внести исправления.

Запрос на внесение изменений также запускает автоматические проверки сборки (например, форматирование rst, синтаксис кода python), а отчеты отображаются внизу страницы. Если найдена ошибка, рядом с вашим коммитом появится красный крестик. Нажмите на красный крестик или на Детали в разделе резюме в нижней части страницы pull request, чтобы увидеть подробности ошибки. Вы должны будете исправить все сообщения об ошибках или предупреждениях до того, как ваши изменения будут зафиксированы в репозитории qgis/QGIS-Documentation.

You can make modifications to your pull request until it is merged with the main repository, either to improve your request, to address requested modifications, or to fix a build error:

  1. Click on the githubFilesChanged tab in your pull request page

  2. Press menu on the right of the filename that you want to modify, and select Edit file.

  3. The file opens in edit mode; add your modifications and commit.

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

Если вы хотите исправить другую проблему, создайте новую ветку для этих изменений и повторите описанные выше шаги.

Администратор объединит ваш вклад после исправления всех ошибок сборки, а также после того, как вы и администраторы будут удовлетворены вашими изменениями.

1.1.5. Удалите вашу объединенную ветвь

Вы можете удалить ветку после того, как ваши изменения будут объединены. Удаление старых веток избавит вас от неиспользуемых и устаревших веток в вашем репозитории.

  1. Перейдите к вашему форку репозитория QGIS-документация (https://github.com/<YourName>/QGIS-Documentation).

  2. Click on the Branches tab. Below Your branches you’ll see a list of your branches.

  3. Click on the deleteSelected Delete this branch icon to delete any unwanted branches.

1.2. Using Git command line tools

The GitHub web interface is an easy way to update the QGIS-documentation repo with your contributions, but it doesn’t offer tools to:

  • group your commits and clean your change history

  • fix possible conflicts with the main repo

  • build the documentation to test your changes

You need to install git on your hard drive in order to get access to more advanced and powerful tools and have a local copy of the repository. Some basics you may often need are exposed below. You’ll also find rules to care about even if you opt for the web interface.

In the code samples below, lines beginning with $ show commands you should type while # are comments.

1.2.1. Local repository

Now you are ready to get a local clone of your QGIS-Documentation repository.

You can clone your QGIS repository using the web URL as follows:

# move to the folder in which you intend to store the local repository
$ cd ~/Documents/Development/QGIS/
$ git clone https://github.com/<YourName>/QGIS-Documentation.git

The former command line is simply an example. You should adapt both the path and the repository URL, replacing <YourName> with your github user name.

Check the following:

# Enter the local repository
$ cd ./QGIS-Documentation
$ git remote -v
origin  https://github.com/<YourName>/QGIS-Documentation.git (fetch)
origin  https://github.com/<YourName>/QGIS-Documentation.git (push)
$ git branch
* master
  • origin is the name of the remote repository of your QGIS-Documentation repository.

  • master is the default main branch. You should never use it to contribute! Never!

Alternatively you can clone your QGIS repository using the SSH protocol:

# move to the folder in which you intend to store the local repository
$ cd ~/Documents/Development/QGIS/
$ git clone [email protected]:<YourName>/QGIS-Documentation.git

Совет

Permission denied (publickey) error?

If you get a Permission denied (publickey) error with the former command, there may be a problem with your SSH key. See GitHub help for details.

Check the following if you used the SSH protocol:

# Enter the local repository
$ cd ./QGIS-Documentation
$ git remote -v
origin  [email protected]:<YourName>/QGIS-Documentation.git (fetch)
origin  [email protected]:<YourName>/QGIS-Documentation.git (push)
$ git branch
* master

You can start to work here but in the long term process you will get a lot of issues when you will push your contribution (called Pull Request in github process) as the master branch of the qgis/QGIS-Documentation repository will diverge from your local/remote repository. You then need to keep track of the main remote repository and work with branches.

1.2.2. Add another remote repository

To be able to follow the work in the main project, add a new remote repository in your local repository. This new remote repository is the QGIS-Documentation repository from QGIS project:

$ git remote add upstream https://github.com/qgis/QGIS-Documentation.git
$ git remote -v
origin  https://github.com/<YourName>/QGIS-Documentation.git (fetch)
origin  https://github.com/<YourName>/QGIS-Documentation.git (push)
upstream        https://github.com/qgis/QGIS-Documentation.git (fetch)
upstream        https://github.com/qgis/QGIS-Documentation.git (push)

Similarly, you can use the SSH protocol to add a remote repository in your local repository:

$ git remote add upstream [email protected]:qgis/QGIS-Documentation.git
$ git remote -v
origin  [email protected]:<YourName>/QGIS-Documentation.git (fetch)
origin  [email protected]:<YourName>/QGIS-Documentation.git (push)
upstream        [email protected]:qgis/QGIS-Documentation.git (fetch)
upstream        [email protected]:qgis/QGIS-Documentation.git (push)

So now you have the choice between two remote repository:

  • origin to push your local branch in your remote repository

  • upstream to merge (if you have right to do so) your contribution to the official one OR to update your master branch of local repository from the master branch of the official repository.

Примечание

upstream is just a label, a kind of standard name but you can call it as you want.

1.2.3. Update your base branch

Before working on a new contribution, you should always update your master branch in your local repository. Assuming you are willing to push changes to the testing documentation, run the following command lines:

# switch to master branch (it is easy to forget this step!)
$ git checkout master
# get "information" from the master branch in the upstream repository
# (aka qgis/QGIS-Documentation's repository)
$ git fetch upstream master
# merge update from upstream/master to the current local branch
# (which should be master, see step 1)
$ git merge upstream/master
# update **your** remote repository (aka <YourName>/QGIS-Documentation)
$ git push origin master

Now you have your local and remote repositories which both have their master branch up to date with the official master branch of QGIS-Documentation. You can start to work on your contribution.

Примечание

Switch the branch if you wish to contribute to released doc

Along with the testing documentation, we continue to fix issues in the latest release, meaning that you can also contribute to it. Follow the previous section sample code, replacing master with the corresponding branch of the latest documentation.

1.2.4. Contribute to your production branch

Now that your base branch is updated, you need to create a dedicated branch in which you add your contribution. Always work on a branch other than the base branch! Always!

# Create a new branch
$ git checkout -b myNewBranch
# checkout means go to the branch
# and -b flag creates a new branch if needed, based on current branch
# Let's check the list of existing branches (* indicates the current branch)
$ git branch
master
release_2.18
...
* myNewBranch
# You can now add your contribution, by editing the concerned file(s)
# with any application (in this case, vim is used)
$ vim myFile
# once done
$ git add myFile
$ git commit

Few words about commit/push commands:

  • try to commit only one contribution (atomic change) i.e. address only one issue

  • try to explain carefully what you change in the title of your commit and in the description. The first line is a title and should start by an upper case letter and have 80 characters length, don’t end with a .. Be concise. Your description can be longer, end with a . and you can give much more details.

  • use a # with a number to refer to an issue. Prefix with Fix if you fix the ticket: your commit will close the ticket.

Now that your changes are saved and committed in your local branch, you need to send them to your remote repository in order to create pull request:

$ git push origin myNewBranch

1.2.5. Share your Changes

Now you can go to your github repository and create a Pull Request as exposed in a previous section. Ensure you create a PR from your branch to the remote branch you are targetting in the official QGIS-Documentation repository.

1.2.6. Clean-up your local and remote repository

After your PR has been merged into the official QGIS-Documentation, you can delete your branch. If you work a lot this way, in few weeks you will get a lot of unuseful branches. So keep your repository clean this way:

# delete local branch
$ git branch -d myNewBranch
# Remove your remote myNewBranch by pushing nothing to it
$ git push origin :myNewBranch

And do not forget to update the master branch in your local repository!

1.3. Дополнительная литература

  • Other than the Github web interface and the git command line tools exposed above, there are also GUI applications you can use to create and manage your contributions to the documentation.

  • When the changes in the pull request are conflicting with recent changes pushed to the target branch, the conflicts need to be resolved before a merge is possible:

    • if the conflict relates to few competing lines, a Resolve conflicts button is available in the GitHub pull request page. Press the button and resolve the issue as explained at Resolving a merge conflict on GitHub

    • if the conflict involves files renaming or removal, then you’d need to resolve the conflict using git command lines. Typically, you have to first rebase your branch over the target branch using git rebase targetBranch call and fix the conflicts that are reported. Read more at Resolving a merge conflict using the command line

  • Sometimes, at the end of the proofreading process, you may end up with changes split into multiple commits that are not necessarily worth it. Git command lines help you squash these commits to a smaller number and more meaningful commit messages. Some details at Using git rebase on the command line