Manual:Coding conventions/fr

Cette page décrit les conventions de codage utilisées dans le code de base de MediaWiki et les extensions utilisées pour les sites web Wikimedia, y compris les conventions de nommage correspondantes. Les modifications qui ne suivent pas ces conventions peuvent être sommairement -1'ed par les relecteurs de code; ceci doit être considéré comme une invitation à corriger les problèmes de style et mettre à jour le patch.

Cette page liste les conventions générales qui s'appliquent à l'ensemble du code MediaWiki, quelquesoit le langage dans lequel il est écrit. Pour les instructions concernant des composants spécifiques ou des types de fichiers particuliers de MediaWiki, voir:


 * SVG
 * SVG

Sur Wikitech (s'applique au moins aux opérations/puppet):


 * Puppet

Largeur des tabulations
Les lignes doivent être indentées avec un seul caractère Tab par niveau d'indentation. Ne faites pas de supposition sur le nombre d'espaces par Tab. La plupart des développeurs MediaWiki estiment que 4 espaces par Tab conviennent bien pour la lisibilité, mais beaucoup de systèmes sont configurés pour utiliser 8 espaces par Tab et certains développeurs peuvent utiliser aussi 2 espaces par Tab.

Pour les utilisateurs vim, une manière de faire ces initialisations est d'ajouter ce qui suit à $HOME/.vimrc:

autocmd Filetype php setlocal ts=4 sw=4

avec des lignes semblables pour CSS, HTML et JavaScript.

Néanmoins, pour Python, suivez à la place le guide concernant les espaces de PEP 8, qui recommande les espaces pour les nouveaux projets.

Nouvelles lignes
Tous les fichiers doivent utiliser le passage à la ligne du style Unix (caractère LF uniquement, et non une combinaison CR+LF).


 * git sous Windows va (par défaut) convertir les passages à la ligne CR+LF en LF lors de la validation (commit).

Tous les fichiers doivent se terminer par un retour à la ligne.


 * Cela a un sens parce que toutes les autres lignes ont un caractère de nouvelle ligne à la fin.
 * Cela aide à faire circuler plus facilement les données en formats non binaires (comme les diffs).
 * Les outils en ligne de commande comme cat et wc ne manipulent pas les fichiers si aucun n'est bon (ou au moins, pas de la manière que l'on voudrait ou que l'on souhaiterait).

Encodage
Tous les fichiers texte doivent être encodés avec UTF-8 sans Byte Order Mark (BOM).

N'utilisez pas Microsoft Notepad pour modifier vos fichiers, parce qu'il insère toujours un BOM. Le BOM arrête l'exécution des fichiers PHP parce que c'est un caractère spécial tout au début du fichier et qu'il est produit par le navigateur web au client.

Bref, assurez-vous que votre éditeur prend en charge UTF-8 sans BOM.

Caractères espaces de fin de ligne
When using an IDE, pressing the Home and End keys (among other keyboard shortcuts) usually ignores trailing whitespace and instead jumps to the end of the code, which is intended. In non-IDE text editors, though, pressing End will jump to the very end of the line, which means the developer must backspace through the trailing whitespace to get to the spot where they actually want to type.

Enlever les espaces de fin est une opération triviale pour la plupart des éditeurs de texte. Les développeurs doivent éviter d'ajouter des espaces après la fin, principalement sur les lignes qui contiennent d'autre code visible.

Certains outils rendent cela plus facile:


 * nano: GNU nano 3.2;
 * : in the Save Options from menu "Edit > Preferences", enable "Clean trailing whitespace and EOL markers" and "Only clean changed lines";
 * Kate: you can see trailing spaces by enabling the option "Highlight trailing spaces". This option can be found in "Settings > Configure Kate > Appearance". You can also tell Kate to cleanup trailing spaces on save in "Settings > Configure Kate > Open/Save".
 * vim: divers plugin de nettoyage automatique;
 * Sublimer le texte: plugin TrailingSpaces.

Mots-clé
N'utilisez pas de parenthèses avec des mots-clé (comme,  ) là où ce n'est pas nécessaire.

Style général
MediaWiki's indenting style is similar to the so-called "One True Brace Style". Braces are placed on the same line as the start of the function, conditional, loop, etc. The else/elseif is placed on the same line as the previous closing brace.

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:

Alignement vertical
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.)

Continuation de ligne
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.

Structures de contrôle sans parenthèses
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:

Modifié ultérieurement en:

Ceci a la capacité de créer des bogues subtiles.

Style emacs
Dans emacs, en utilisant  de nXHTML mode, vous pouvez définir un mode mineur MediaWiki dans votre fichier .emacs:

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.

Construction des 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.

Nommage des fichiers
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.

Fichiers des points d'accès
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.

N'utilisez jamais les espaces dans les noms de fichiers ou de répertoires, et n'utilisez jamais les caractères non-ASCII. Pour les titres en minuscules, les tirets sont préférables aux caractères soulignés.

Fichiers JS, CSS, et de média
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.

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

Fichiers texte
Les développeurs peuvent garder les fichiers de documentation dans Git à côté du 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".

Formats des fichiers texte

 * 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). Par exemple, le   de l'extension Wikibase dans 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). Par exemple, le   de l'extension Wikibase dans 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.

Entêtes des fichiers source
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.

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

Notes des versions
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.

Messages système
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.

Orthographe préférée
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.

Abbréviations des clés de messages

 * ph
 * emplacement à substituer (texte des champs d'entrée)


 * tip
 * texte de la bulle d'aide


 * tog-xx
 * gérer les options dans les préférences utilisateur

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

Chargeur de ressources
Module names should match the main definition of the scripts they load. For example a module defining the  object is named "mediawiki.util" and the module for the   object constructor is named "mediawiki.Title".

Modules du coeur
If you need some additional functionality of a core module (or you need a function that does something similar but a different), actually improve the core module. Don't just copy+paste and modify the code in another place.

Remise en forme du code
Restructurez le code aussitôt que les modifications sont faites: n'attendez pas que le code s'enlaidisse au fur et à mesure des modifications.

However, use separate commits if the refactoring is large. See also Architecture guidelines (draft).

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. Exemple: Ne gèrer que l'accroche 'wikipage.diff' pour les diffs officiels.

Liens externes

 * outils de style pour le code