Differences between revisions 1 and 39 (spanning 38 versions)
Revision 1 as of 2007-07-20 06:00:04
Size: 981
Editor: mpm
Comment:
Revision 39 as of 2016-07-10 13:21:59
Size: 5156
Comment: update to the same line length rule that ContributingChanges uses
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
Don'ts: ## page was renamed from BasicCodingStyle
#pragma section-numbers 2
<<Include(A:dev)>>

= Coding Style =

How to make your code pretty the Mercurial way.

<<TableOfContents>>

== Introduction ==

This page is intended to save new developers a few round-trips when [[ContributingChanges|contributing changes]]. It doesn't cover everything, but it does cover some of the most common mistakes people make.

== Some code doesn't agree with the coding style! ==

Yes, because some code predates the coding style and has not yet been rewritten to conform. Please follow the coding style for all new code.

== Naming conventions ==

For consistency and ease of reference, Mercurial uses a single style for all identifiers: '''all lowercase, with no underbars between words'''.
This matches Python's core style (with the notable exception of has_key which is deprecated). For private methods and helper functions, the convention is to use a single leading underbar. Use a trailing underbar to avoid shadowing built-ins and imported modules.

Throughout the code, the following variables usually refer to the same thing:

|| '''name''' || '''description''' ||
|| p1, p2 || first and second parents ||
|| ctx || a context.changectx instance (or derivative) ||
|| fctx || a context.filectx instance ||
|| fn, fname || filename ||
|| fp || a python file(like) object ||
|| repo || a localrepo or review object ||
|| unfi || an unfiltered local repo instance ||

== Whitespace and syntax ==

We approximately follow [[http://www.python.org/dev/peps/pep-0008/|PEP 8]] guidelines for whitespace:
Line 4: Line 40:
 * don't use lines longer than 80 characters  * use four spaces to indent
 * add a linebreak after a colon
 * use whitespace around most operators
 * don't use lines that are 80 characters or longer (i.e. the maximum length is 79)
Line 6: Line 45:
 * don't name functions with CamelCase
 * don't name functions with lots_of_under_bars
 * don't make helper functions prefixed with do_
 * don't name your classes in Uppercase
 * in general, don't make ["mpm"] use his shift key any more than he has to
 * don't use default arguments without a good reason
 * don't use a class to encompass something that's not conceptually an object
 * don't use sorted(), rstrip(), or various other post-Py2.3 goodies
 * don't put OS-specific hacks outside of util.py and friends.
 * use a ''single'' blank line between top-level functions and class definitions (unlike the PEP8 convention).
Line 16: Line 47:
Do:
Line 18: Line 48:
 * use single quotes rather than double quotes
 * use a single underscore prefix for private methods and functions
 * use a single underscore prefix for a helper function
 * add a linebreak after a colon
== Language features and compatibility ==

 * Mercurial is designed for SupportedPythonVersions and onward so don't use new features:
   * no Py3k-isms
 * Don't add default arguments to new functions unless you're going to use them

== Classes ==

/!\ Avoid wasting effort by asking [[mpm]] for permission to use a class

 * Think twice about using classes, functions are almost always smaller and simpler
 * Think three times if you are a recovering Java programmer
 * Class names should still be lowercase (but exception classes are `CamelCased`)
 * Classes should derive from 'object'
 * Private methods and variables should be indicated with a leading underscore
 * Destructors in Python are not reliable and should be avoided

== Unicode and character encoding ==

Character encoding is a complex topic (see [[EncodingStrategy|Encoding Strategy]] for an overview) but Mercurial generally follows these rules:

 * Almost all string data is manipulated either as plain byte strings in the local encoding or in no encoding
 * Mercurial-specific metadata like usernames is converted to UTF-8 byte strings in a restricted number of places using fromlocal/tolocal
 * Unicode objects are '''avoided wherever possible''' and no core APIs are designed to handle them

== Status and error messages ==

 * use _() to mark things for i18n

Short messages should look like this:
{{{
adding foo.txt
}}}

Note the following:

 * it starts with a ''lower-case'' word.
 * it has no trailing full-stop (`.`).

Some existing strings don't follow this style and are kept like that for backwards compatibility reasons. But please write all new strings in this style.

The above message should look like this in your code:
{{{
ui.status(_('adding %s\n') % filename)
}}}

Please note:

 * The `_` function is used to mark the string as translatable. Import it from the `i18n` module.
 * The string interpolation is done ''after'' the call to the `_` function.

== Miscellaneous ==

 * Don't put OS-specific hacks outside of util.py and friends
Line 23: Line 103:
 * use _() to mark things for i18n
 * add testcases to the test suite
 * run the test suite
 * follow the [[HelpStyleGuide||style guide]] when adding help texts
Line 27: Line 105:
-- ["mpm"] == Automated checking ==

A lot of the rules in this document and a bunch of others can be automatically checked with our '`check-code`' script:

{{{
$ python contrib/check-code.py --blame `hg manifest`
mercurial/i18n.py:42 (working directory):
 > u = u'\n\n'.join([p and t.ugettext(unicode(p, 'ascii')) or '' for p in paragraphs])
 line too long
}}}

We recommend you '''run this script before every submission'''. In addition to catching style and portability issues in Python code, it will also inspect our C code and test suite.

== See also ==

 * [[ContributingChanges|Contributing changes]] - how to send us your changes
 * [[HelpStyleGuide|Help style guide]] - pointers on writing online help text
 * [[WritingTests|Writing tests]] - how to extend the test suite

----
CategoryDeveloper

Note:

This page is primarily intended for developers of Mercurial.

Coding Style

How to make your code pretty the Mercurial way.

1. Introduction

This page is intended to save new developers a few round-trips when contributing changes. It doesn't cover everything, but it does cover some of the most common mistakes people make.

2. Some code doesn't agree with the coding style!

Yes, because some code predates the coding style and has not yet been rewritten to conform. Please follow the coding style for all new code.

3. Naming conventions

For consistency and ease of reference, Mercurial uses a single style for all identifiers: all lowercase, with no underbars between words. This matches Python's core style (with the notable exception of has_key which is deprecated). For private methods and helper functions, the convention is to use a single leading underbar. Use a trailing underbar to avoid shadowing built-ins and imported modules.

Throughout the code, the following variables usually refer to the same thing:

name

description

p1, p2

first and second parents

ctx

a context.changectx instance (or derivative)

fctx

a context.filectx instance

fn, fname

filename

fp

a python file(like) object

repo

a localrepo or review object

unfi

an unfiltered local repo instance

4. Whitespace and syntax

We approximately follow PEP 8 guidelines for whitespace:

  • don't use tabs
  • use four spaces to indent
  • add a linebreak after a colon
  • use whitespace around most operators
  • don't use lines that are 80 characters or longer (i.e. the maximum length is 79)
  • don't leave trailing whitespace
  • use a single blank line between top-level functions and class definitions (unlike the PEP8 convention).

5. Language features and compatibility

  • Mercurial is designed for SupportedPythonVersions and onward so don't use new features:

    • no Py3k-isms
  • Don't add default arguments to new functions unless you're going to use them

6. Classes

/!\ Avoid wasting effort by asking mpm for permission to use a class

  • Think twice about using classes, functions are almost always smaller and simpler
  • Think three times if you are a recovering Java programmer
  • Class names should still be lowercase (but exception classes are CamelCased)

  • Classes should derive from 'object'
  • Private methods and variables should be indicated with a leading underscore
  • Destructors in Python are not reliable and should be avoided

7. Unicode and character encoding

Character encoding is a complex topic (see Encoding Strategy for an overview) but Mercurial generally follows these rules:

  • Almost all string data is manipulated either as plain byte strings in the local encoding or in no encoding
  • Mercurial-specific metadata like usernames is converted to UTF-8 byte strings in a restricted number of places using fromlocal/tolocal
  • Unicode objects are avoided wherever possible and no core APIs are designed to handle them

8. Status and error messages

  • use _() to mark things for i18n

Short messages should look like this:

adding foo.txt

Note the following:

  • it starts with a lower-case word.

  • it has no trailing full-stop (.).

Some existing strings don't follow this style and are kept like that for backwards compatibility reasons. But please write all new strings in this style.

The above message should look like this in your code:

ui.status(_('adding %s\n') % filename)

Please note:

  • The _ function is used to mark the string as translatable. Import it from the i18n module.

  • The string interpolation is done after the call to the _ function.

9. Miscellaneous

  • Don't put OS-specific hacks outside of util.py and friends
  • add docstrings
  • follow the HelpStyleGuide when adding help texts

10. Automated checking

A lot of the rules in this document and a bunch of others can be automatically checked with our 'check-code' script:

$ python contrib/check-code.py --blame `hg manifest`
mercurial/i18n.py:42 (working directory):
 >     u = u'\n\n'.join([p and t.ugettext(unicode(p, 'ascii')) or '' for p in paragraphs])
 line too long

We recommend you run this script before every submission. In addition to catching style and portability issues in Python code, it will also inspect our C code and test suite.

11. See also


CategoryDeveloper

CodingStyle (last edited 2022-02-21 17:44:01 by RaphaelGomes)