Как стать MediaWiki хакером

From mediawiki.org
This page is a translated version of the page How to become a MediaWiki hacker and the translation is 71% complete.
Outdated translations are marked like this.

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

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

Если вы уже опытный разработчик и хорошо знакомы с особенностями MediaWiki, посетите Портал разработчиков .

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

Обзор

MediaWiki — это программное обеспечение, на основе которого создана Википедия, её родственные проекты, а также тысячи вики по всему миру.

Хотя MediaWiki написана на языке программирования PHP, некоторые вспомогательные утилиты написаны на других языках, включая пакетные файлы, сценарии командной строки, makefiles и Python. JavaScript is used for providing interactive interface elements along with jQuery and Vue.js as client JavaScript libraries.

Some supporting tools are written in other languages, including batch files, shell scripts, makefiles and Python.

MediaWiki изначально написана для платформы LAMP [1] и работает в большинстве операционных систем. MediaWiki изначально использует сервера баз данных MySQL или MariaDB.[2]

Разработка ведется в стиле открытого исходного кода[3], в основном координируется онлайн и поддерживается Wikimedia Foundation. Тем не менее волонтеры, сообщество, разработчики также играют огромную роль.

  • Исходный код хранится в Gerrit и управляется с помощью системы контроля ревизий Git и может быть просмотрен здесь[4]
  • Проверка кода происходит на Gerrit и может быть просмотрена [gerrit:q/project:mediawiki/core|здесь]. Следуйте этому руководству, которое поможет настроить Git и Gerrit для отправки патчей.
  • Bug reports (сообщения об ошибках) и запросы функций подаются, а проекты согласовываются в Фабрикатор и могут быть просмотрены здесь

Find or create a task

Before you ever develop a feature or fix a bug in a MediaWiki project, it is important that you do your research about it. This includes:

  1. Search Phabricator if an open or closed Task (Document Types field) already exists. If it doesn't, create one. If this is a very small change, don't create one.
  2. Find and investigate the code that needs to be changed to implement the feature. Comment your findings on the Phabricator Task if they might be helpful to others who implement it or review your changes.
  3. Determine if you can likely add the feature or fix the bug based the code you investigated and the changes needed. If the task is large or complex, you should find something easier and work your way up to eventually be able to handle tasks of that size. If you believe you can complete it, assign yourself to the Task and begin working on it.

Настройка среды разработки

Once you have found something you can work on, the next step to developing MediaWiki or an extension is creating an environment to run MediaWiki, its database, and any other external features so that you can develop and test them.

You can install and develop MediaWiki on Linux, Windows, or macOS using any of the three solutions below.

Docker

Docker is a good option if you want to setup a MediaWiki installation quickly and are not planning on installing many extensions.

Вы также можете попробовать экспериментальный инструмент mwcli, который настраивает Docker с помощью нескольких простых команд и предоставляет базовые функции оркестрации для контейнеров MediaWiki Docker.

Vagrant

  • Установка Vagrant — Установка сервера MediaWiki со всем необходимым внутри виртуальной машины Linux (возможно использование Linux, Windows или Mac хостов)

Vagrant позволяет вам запускать экземпляр MediaWiki, который вы можете разрабатывать, а также позволяет вам добавлять и разрабатывать любое из 250+ расширений — и все это с помощью одной команды.

Это экономит время на установку и настройку по сравнению с установкой вручную.

Самостоятельная установка

Local installation is a good option if you want to set up a simple development environment quickly without using Docker.

Open a code editor

The two recommended code editors for editing MediaWiki are VSCode and PhpStorm. VSCode is free and PhpStorm is paid, however, you can acquire a PhpStorm license for free if you are a student by linking your GitHub Education account to your JetBrains account, or by requesting a license granted to Wikimedia.

To determine which editor you should install and use, know that all-around, PhpStorm has more and more-powerful features than VSCode. However, PhpStorm takes significantly longer to load on start than VSCode as it builds an index of the entire repository whereas VSCode progressively loads. Therefore, VSCode is typically useful for file-viewing sessions or small changes and PhpStorm for larger changes. It makes sense to have both installed for these reasons.

To develop the MediaWiki codebase that is inside a Docker container you can establish a remote connection to it and open the MediaWiki folder inside it using VSCode or PhpStorm.

Change and test the code

Change the code and view your changes by reloading your MediaWiki browser tab. Make sure to follow Руководство:Соглашение по кодированию . Write and run tests on your code to make sure it works and is formatted properly.

Note, you can save time by ensuring your changes will be accepted before taking the time to write tests. Create a patch without needed tests and ask for someone to review it stating that you will add tests after they review it.

Create a patch

Finally, to submit your code to be reviewed and added to the repository you are contributing to, follow Gerrit/Руководство .

Советы и рекомендации по коммуникации

Посмотрите за тем как разработчик исправляет баг в расширении MediaWiki, включая исследование, git коммит, проверка изменения и миграция в ветку, закрытие Bugzilla ticket (в настоящее время заменено на Фабрикатор ).

Follow these tips to communicate effectively and get help from community members.

Use Phabricator tasks effectively

When you plan to work on a Фабрикатор task:

  • No need to ask for permission: You can work on unassigned tasks without asking someone to assign them to you. There is no authority who assigns tasks or who needs to be asked first.
    • If a task already has a recent patch in Gerrit, choose a different task to work on instead.
    • If an existing patch in Gerrit has not been merged and has not seen any changes for a long time, you could improve that existing patch, based on the feedback in Gerrit and in the task.
  • Do your research: When you consider working on a task, do research before you start coding. Look at the code, try to understand what it is supposed to do, read related documentation, and try to find the places where you need to make code changes.
    • In a Фабрикатор task, use the project tags in the side bar to find the code repository for the task.
    • If you have no idea at all how to fix the bug, consider finding an easier one first.
  • You do not need to announce your plans before you start working on a task, but you should communicate that you are working on the task.
    • When you start work, set yourself as task assignee by clicking Edit Task… in Phabricator, and set your Phabricator username in the Assigned To field. This communicates to others that you are working on it, so they don't duplicate work.
    • When your plans or interests change: If you are no longer working on a task, remove yourself as the assignee of the task. This tells others that they can work on the task, and they won't expect you to still work on it.
  • Follow Phabricator etiquette.
    • In Phabricator tasks, discuss only specific questions about the topic of that task. Don't use Phabricator to ask general questions, like how to set up a development environment or how to fix problems with Gerrit.

Compose good questions

  • Be specific and provide context: Instead of simply asking "Can you give me more info?", "Please guide me", or "Please tell me how to start", include the following information in your question:
    • What are you trying to achieve?
    • What have you already tried? Copy and paste your commands and their output (if not too long) instead of paraphrasing in your own words.
    • What have you found out already during your research? Include links to code, documentation, or other resources you already consulted.
  • Use specific titles and subject lines in your communication. "Proposal draft" or "Need help" is not specific.
  • Keep conversations readable: When you reply in Zulip, in Phabricator tasks, or on mailing lists, only quote sections of previous comments that are relevant to your response. If you quote a complete previous comment, it makes threads hard to read.

Follow communication policies and best practices

Before you send or post your question:

Ask in the right place

  • Ask in public: Do not send private messages if your conversation topic is not secret.

Private messages don't help others.

  • Ask and discuss in the best place:
    • In Phabricator tasks, discuss only specific questions about the topic of that task.
    • Ask general technical questions, like how to set up a development environment or how to fix problems with Gerrit, in the places listed on Общение .
    • If you take part in an outreach program, then Zulip is for discussing questions about the outreach programs themselves.

Be patient

After you post your question:

  • Do not ask people for code review in a separate message. People receive Gerrit and Phabricator notifications and will respond when they can.
  • When seeking input and comments, especially during weekends and holidays, you may need to wait until business hours resume. On chat channels like IRC: if nobody answers, try again at a different time; don't just give up!
  • If you don't get an answer even after waiting and being patient, consider if other Communication channels might be a better place to ask your question.

Приложение

Вкладчики в MediaWiki за работой в Бангалоре, Индия.

PHP

MediaWiki написан на PHP, соответственно он необходим для работы над ядром MediaWiki.

Учите PHP
  • Учебник PHP — Доступен на многих языках. Если вы не знаете PHP, но умеете программировать на других объектно-ориентированных языках программирования, то изучение PHP для вас будет несложным.
  • Программирование на PHP в Викиучебнике.
  • PHP в Викиверситете.
Источники по PHP
Что нужно знать
  • Скрипт maintenance/eval.php содержит базовый интерпретатор с объектами и классами MediaWiki.
  • Кроме того, скрипт maintenance/shell.php в MediaWiki является заменой кода основанной на PsySH maintenance/eval.php, см. Руководство:Shell.php

Базы данных

Зачастую необходимы знания базы данных MySQL/MariaDB.

Учите MySQL/MariaDB
Материалы по MySQL/MariaDB
Что нужно знать
  • Тестируйте код с MySQL/MariaDB.
    • MediaWiki использует MySQL and MariaDB в качестве основных баз данных. Также поддерживаются и другие СУБД, такие как PostgreSQL и SQLite. Однако почти все разработчики используют MySQL/MariaDB и проводят тесты только используя их, вследствие этого другие базы данных при тестах часто выходят из строя. Поэтому, если вы целенаправленно не занимаетесь улучшением поддержки для других баз данных, то используйте MySQL/MariaDB. Если да, то убедитесь в правильности работы с MySQL/MariaDB (и в эффективности запросов), так как их используют почти все остальные разработчики.

JavaScript и CSS

JavaScript и CSS стали стандартом в разработке фронтенда. Вы не должны быть знакомы с JavaScript, jQuery и CSS для разработки MediaWiki, но соответствующие знания могут понадобиться.

Учите JavaScript и CSS
Материалы по JavaScript и CSS

MediaWiki

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

Материалы MediaWiki, необходимые к прочтению
Ресуры MediaWiki

Расширения MediaWiki

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

Основа MediaWiki расширений
Прочие ресурсы

MediaWiki skins

См. также

Footnotes

  1. MediaWiki работает на большинстве платформ, которые поддерживают PHP, однако отсутствие определенных утилит или функций операционной системы может ограничить функциональность или производительность MediaWiki на платформах, отличных от LAMP.
  2. В MediaWiki кроме поддержки MySQL и MariaDB есть поддержка DBMS, включая PostgreSQL и SQLite.
  3. В число девелоперов входят волонтеры и оплачиваемый персонал (или контрактные рабочие) из различных организаций. Полный список работающих на кодом MediaWiki смотрите в статье Разработчики .
  4. Посмотрите исходный код и ревизии в репозиториях кода https://phabricator.wikimedia.org/diffusion/ или загрузите исходный код на вашу систему используя Gerrit.