Coding Style

How to make your code pretty the Mercurial way.

/!\ This page is intended for developers.

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

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

name

description

p1, p2

first and second parents

fctx

a context.filectx instance

fn, fname

filename

fp

a python file(like) object

3. Whitespace and syntax

We approximately follow PEP 8 guidelines for whitespace:

4. Language features and compatibility

5. Classes

6. Unicode and character encoding

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

7. Status and error messages

Short messages should look like this:

adding foo.txt

Note the following:

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:

8. Miscellaneous

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

10. See also


CategoryDeveloper