Manual:Coding conventions/ja

このページでは、MediaWiki コードベース内や、ウィキメディアのウェブサイト群で使用されることを意図している拡張機能内で使用される、コーディング規約を説明します. コードレビューワーは、これら規約に従わない変更をまとめて-1処理することがあります. その場合は、スタイルの問題を修正してパッチを更新するように推奨されたと解釈するようにお願いします.

このページでは、コードがどの言語で書かれているかにかかわらずすべての MediaWiki コードに適用される全般的な規約を列挙します. MediaWiki の特定のコンポーネントやファイルの種類に適用されるガイドラインについては、以下を参照してください:


 * SVG
 * SVG

wiki技術部 (少なくとも運営/パペットに適用):


 * Puppet

タブの幅
各行は深さ1段ごとにタブ記号1個でインデントを施します. タブ1個が何文字相当か自分で決めることはできません. MediaWikiの開発者の多くは可読性の面からもタブ1個を半角アキ4個相当が妥当だとしていますが、多くのシステムでは半角アキ8個相当の設定で、なかには半角アキ2個のつもりで使用する開発者もいます.

テキストエディタのvim利用者には$HOME/.vimrcに以下の記述を追加して設定する方法があります.

autocmd Filetype php setlocal ts=4 sw=4

CSSやHTML、JavaScriptにも似た記述を使います.

しかしながらPythonでは、コードのスタイルガイドPEP 8の空白スペース (アキ) ガイドラインに従い、タブではなくアキを使用するように推奨しています.

改行
どのファイルも改行はUnix式にします (LF記号1個であって、CR+LFではない).


 * Windows版のgitでは (既定として) コミットの段階で自動的にCR+LF改行をLFに置換します.

すべてのファイルについて、末尾に改行文字を付けるべきです.


 * その他の行はすべて、行末に改行記号があるため整合性があります.
 * これにより非バイナリ形式 (差分など) でのデータ取り回しが楽になります.
 * catやwcなどコマンドラインツールで欠如するとファイル処理が円滑に進みません (あるいは少なくとも予期したりこうあるべきと思う挙動になりません).

エンコーディング
テキストファイルはすべてBOMのない、UTF-8で符号化.

ファイル編集には、必ずBOMを挿入するMicrosoft Notepadは使用できません. ファイル冒頭に特殊文字BOMが入ることによって、ウェブブラウザがそれをクライアントに出力するため、PHPファイルの作動が阻害されます.

まとめるなら、必ずUTF-8対応でBOMを挿入しないエディタをご利用ください.

末尾の空白類
IDEを使用すると「Home」と「End」のキー (その他のキーボードショートカットも含む) を押すと、想定どおり、通常は行末の空白スペースを無視してコード末尾にジャンプします. ところが非IDEテキストエディタの場合は「End」キーを押すと行末の空白スペースの末尾に飛んでしまい、開発者は入力しようとして想定した位置まで、バックスペースで戻る必要があります.

操作としては、行末の空白スペースの削除はほとんどのテキストエディタで簡単です. 開発者は、他の可視コードを含む行では特に、行の末尾に空白を入れないでください.

処理を簡略化するツールがあります.


 * nano: GNU nano 3.2 "Het kromme hout";
 * Komodo Edit: メニューの「Edit > Preferences」を開きSave Optionsで「Clean trailing whitespace and EOL markers」ならびに「Only clean changed lines」を有効にする;
 * Kate: オプション「Highlight trailing spaces」を有効にすると、行末の空白スペースを表示する. 「Settings > Configure Kate > Appearance」から設定. また「Settings > Configure Kate > Open/Save」の設定で、保存時に行末の空白スペース削除を自動処理できる.
 * vim: さまざまな自動クリーンナッププラグインを備える.
 * Sublime Text: TrailingSpace処理用プラグイン (行末の空白スペースを強調表示、削除)

キーワード
キーワード (例 や ) に不要な括弧を付けない.

全般的なスタイル
MediaWikiのインデントの形式は、いわゆる「The One True Brace Style」(1TBS あるいは OTBS) (1TBS あるいは OTBS)と同様です. 波括弧は関数、条件文やループなどの開始と同じ行に置きます. else/elseifは前の波括弧 ( } ) と同じ行に置きます.

Multi-line statements are written with the second and subsequent lines being indented by one extra level:

Use indenting and line breaks to clarify the logical structure of your code. Expressions which nest multiple levels of parentheses or similar structures may begin a new indenting level with each nesting level:

In switch statements indent within the braces and between cases:

垂直方向の配置
Avoid vertical alignment. It tends to create diffs which are hard to interpret, since the width allowed for the left column constantly has to be increased as more items are added.

When needed, create mid-line vertical alignment with spaces rather than tabs. For instance this:

Is achieved as follows with spaces rendered as dots:

 $namespaceNames·=·[ → NS_MEDIA············=>·'Media', → NS_SPECIAL··········=>·'Special', → NS_MAIN·············=>·'', ]; (If you use the tabular vim add-on, entering :Tabularize /= will align the '=' signs.)

行の継続
Lines should be broken at between 80 and 100 columns. There are some rare exceptions to this. Functions which take lots of parameters are not exceptions.

The operator separating the two lines should be placed at the end of the preceding line.

When continuing "if" statements, a switch to Allman-style braces makes the separation between the condition and the body clear:

Opinions differ on the amount of indentation that should be used for the conditional part. Using an amount of indentation different to that used by the body makes it more clear that the conditional part is not the body, but this is not universally observed.

Continuation of conditionals and very long expressions tend to be ugly whichever way you do them. So it's sometimes best to break them up by means of temporary variables.

波括弧で囲まない制御構造
Do not write "blocks" as a single-line. They reduce the readability of the code by moving important statements away from the left margin, where the reader is looking for them. Remember that making code shorter doesn't make it simpler. The goal of coding style is to communicate effectively with humans, not to fit computer-readable text into a small space.

This avoids a common logic error, which is especially prevalent when the developer is using a text editor which does not have a "smart indenting" feature. The error occurs when a single-line block is later extended to two lines:

Later changed to:

This has the potential to create subtle bugs.

emacsスタイル
In emacs, using  from nXHTML mode, you can set up a MediaWiki minor mode in your .emacs file:

The above  function will check your path when   is invoked to see if it contains “mw” or “mediawiki” and set the buffer to use the   minor mode for editing MediaWiki source. You will know that the buffer is using  because you'll see something like “PHP MW” or “PHP/lw MW” in the mode line.

URL の構築
Never build URLs manually with string concatenation or similar. Always use the full URL format for requests made by your code (especially POST and background requests).

You can use the appropriate or  method in PHP, the  magic word in wikitext, the mw.util.getURL method in JavaScript, and similar methods in other languages. You'll avoid issues with unexpected short URL configuration and more.

ファイルの命名
Files which contain server-side code should be named in UpperCamelCase. This is also our naming convention for extensions. Name the file after the most important class it contains; most files will contain only one class, or a base class and a number of descendants. For example,  contains only the   class;   contains the   class, and also its descendants   and.

Access point files
Name "access point" files, such as SQL, and PHP entry points such as  and , in lowercase. Maintenance scripts are generally in lowerCamelCase, although this varies somewhat. Files intended for the site administrator, such as readmes, licenses and changelogs, are usually in UPPERCASE.

Never include spaces in file names or directories, and never use non-ASCII characters. For lowercase titles, hyphens are preferred to underscores.

JS, CSS, and media files
For JavaScript, CSS and media files (usually loaded via ResourceLoader) file naming should match module naming. For example:
 * Module  might have files   and
 * module  has file

Modules names registered by extensions should follow name like, for instance:

This keeps it easy to find files, even if you divide up a module into smaller files for editing convenience and then bundle them together into a single module.

説明文書
The language-specific subpages have more information on the exact syntax for code comments in files, e.g. comments in PHP for doxygen. Using precise syntax allows us to generate documentation from source code at http://doc.wikimedia.org.

Some elements of MediaWiki are documented in core's. For instance, if you add a new hook, you should update with the name of the hook, a description of what the hook does, and the parameters used by the hook.

テキスト ファイル
Developers can keep documentation files in Git alongside code. This can be good for detailed documentation of extension architecture, database design, etc. that you should update with each code commit that changes behavior. Pages on mediawiki.org that relate to documentation in Git should link to it using.

(The possibility to transclude text from Git files into wiki pages is tracked in T91626.)

Note that many technical documentation pages on mediawiki.org pages document the evolution of MediaWiki code over many releases. Either describe changes in your document or state it only describes the latest codebase in "master".

テキスト ファイルの書式

 * If your text file is wikitext, give it a  extension. GitHub can parse a subset of wikitext, so   files mirrored on GitHub will display some formatting (a   extension also works, but is longer). For example, the Wikibase extension's   in GitHub.
 * If your text file is wikitext, give it a  extension. GitHub can parse a subset of wikitext, so   files mirrored on GitHub will display some formatting (a   extension also works, but is longer). For example, the Wikibase extension's   in GitHub.


 * Doxygen supports Markdown formatting, so you can put lightly-formatted documentation in  files. Diffusion and GitHub also support   files. Name the explanatory file for a directory or project  ; Diffusion and GitHub will display this file when you view that directory or project (e.g. RESTbase's , in  and on GitHub).
 * Doxygen supports Markdown formatting, so you can put lightly-formatted documentation in  files. Diffusion and GitHub also support   files. Name the explanatory file for a directory or project  ; Diffusion and GitHub will display this file when you view that directory or project (e.g. RESTbase's , in  and on GitHub).


 * no extension and
 * Doxygen by default parses these as C language files (!!, tracked in ). You can take advantage of this by making the file mimic a C comment, and then add doxygen directives to the file. For example, generates File backend design in doxygen, and begins with:




 * Special:Version/Credits assumes  and   (with no extension) are wikitext files.

ソースファイルのヘッダー
In order to be compliant with most licenses you should have something similar to the following (specific to GPLv2 PHP applications) at the top of every source file.

ライセンス
Licenses are generally referred to by their full name or acronym as per SPDX standard. See also Manual:$wgExtensionCredits#license.

リリースノート
You must document all significant changes (including all fixed bug reports) to the core software which might affect wiki users, server administrators, or extension authors in the  file. is in development; on every release we move the past release notes into the  file and start afresh. is generally divided into three sections:


 * Configuration changes is the place to put changes to accepted default behavior, backwards-incompatible changes, or other things which need a server administrator to look at and decide "is this change right for my wiki?". Try to include a brief explanation of how the previous functionality can be recovered if desired.
 * Bug fixes is the place to note changes which fix behavior which is accepted to be problematic or undesirable. These will often be issues reported in Phabricator, but needn't necessarily.
 * New features is, unsurprisingly, to note the addition of new functionality.

There may be additional sections for specific components (e.g. the Action API) or for miscellaneous changes that don't fall into one of the above categories.

In all cases, if your change is in response to one or more issues reported in Phabricator, include the task ID(s) at the start of the entry. Add new entries in chronological order at the end of the section.

システムメッセージ
When creating a new system message, use hyphens (-) where possible instead of CamelCase or snake_case. So for example,  is a good name, while   and   are not.

If the message is going to be used as a label which can have a colon after it, don't hardcode the colon; instead, put the colon inside the message text. Some languages (such as French which require a space before) need to handle colons in a different way, which is impossible if the colon is hardcoded. The same holds for several other types of interpunctuation.

Try to use message keys "whole" in code, rather than building them on the fly; as this makes it easier to search for them in the codebase. For instance, the following shows how a search for  will not find this use of the message key if they are not used as a whole.

If you feel that you have to build messages on the fly, put a comment with all possible whole messages nearby:

See Localisation for more conventions about creating, using, documenting and maintaining message keys.

好ましい綴り
It is just as important to have consistent spelling in the UI and codebase as it is to have consistent UI. By long standing history, 'American English' is the preferred spelling for English language messages, comments, and documentation.

メッセージキーの短縮形

 * ph
 * プレースホルダー (placeholder: 入力欄内のテキスト)


 * tip
 * ツールチップ テキスト (tooltip text)


 * tog-xx
 * 利用者の個人設定内のトグル (toggle) オプション (訳注: チェックボックス)

句点
Non-title error messages are considered as sentences and should have punctuation.

ResourceLoader
モジュール名は読みこむスクリプトのメインの定義と一致する必要があります. 例として オブジェクトを定義するモジュールの名前は"mediawiki.util"となり、 コンストラクタに対するモジュールなら"mediawiki.Title"と命名します.

コア モジュール
もしコアモジュールのその他の機能（または似ているが違う機能）が必要な場合、実際にコアモジュールを改善してください. 変更するために別の場所にあったコードをコピー&ペーストして使うことはできません.

リファクタリング
修正を加えるたびにコードのリファクタを実行：修正のだびにコードの悪化を蓄積しないでください.

ただし、リファクタリングが大量に及ぶ場合は、コミットを分割して行います. 構築ガイドArchitecture guidelines (草案) も参照してください.

HTML
MediaWiki HTTP responses output HTML that can be generated by one of two sources. The MediaWiki PHP code is a trusted source for the user interface, it can output any arbitrary HTML. The Parser converts user-generated wikitext into HTML, this is an untrusted source. Complex HTML created by users via wikitext is often found in the "Template" namespace. HTML produced by the Parser is subject to sanitization before output.

Most data attributes are allowed to be used by users in wikitext and templates. But, the following prefixes have been restricted and are not allowed in wikitext. This enables client JavaScript code to determine whether a DOM element came from a trusted source:


 * – This attribute is present in HTML generated by OOUI widgets.
 * – reserved attribute for internal use by Parsoid.
 * and  – reserved attribute for internal use by MediaWiki core, skins and extensions. The   is also used by Parsoid.

When selecting elements in JavaScript, one can specify an attribute key/value to ensure only DOM elements from the intended trusted source are considered. Example: Only trigger 'wikipage.diff' hook for official diffs.

外部リンク

 * コード スタイル ツール