1
============================
2
Guidelines for modifying bzr
3
============================
7
(The current version of this document is available in the file ``HACKING``
8
in the source tree, or at http://doc.bazaar-vcs.org/current/hacking.html)
13
* New functionality should have test cases. Preferably write the
14
test before writing the code.
16
In general, you can test at either the command-line level or the
17
internal API level. See Writing tests below for more detail.
19
* Try to practice Test-Driven Development. before fixing a bug, write a
20
test case so that it does not regress. Similarly for adding a new
21
feature: write a test case for a small version of the new feature before
22
starting on the code itself. Check the test fails on the old code, then
23
add the feature or fix and check it passes.
25
* Exceptions should be defined inside bzrlib.errors, so that we can
26
see the whole tree at a glance.
28
* Imports should be done at the top-level of the file, unless there is
29
a strong reason to have them lazily loaded when a particular
30
function runs. Import statements have a cost, so try to make sure
31
they don't run inside hot functions.
33
* Module names should always be given fully-qualified,
34
i.e. ``bzrlib.hashcache`` not just ``hashcache``.
36
* Commands should return non-zero when they encounter circumstances that
37
the user should really pay attention to - which includes trivial shell
40
Recommended values are
42
1. Conflicts in merge-like operations, or changes are present in
44
2. Unrepresentable diff changes (i.e. binary files that we cannot show
46
3. An error or exception has occurred.
51
We have a commitment to 6 months API stability - any supported symbol in a
52
release of bzr MUST NOT be altered in any way that would result in
53
breaking existing code that uses it. That means that method names,
54
parameter ordering, parameter names, variable and attribute names etc must
55
not be changed without leaving a 'deprecated forwarder' behind. This even
56
applies to modules and classes.
58
If you wish to change the behaviour of a supported API in an incompatible
59
way, you need to change its name as well. For instance, if I add an optional keyword
60
parameter to branch.commit - that's fine. On the other hand, if I add a
61
keyword parameter to branch.commit which is a *required* transaction
62
object, I should rename the API - i.e. to 'branch.commit_transaction'.
64
When renaming such supported API's, be sure to leave a deprecated_method (or
65
_function or ...) behind which forwards to the new API. See the
66
bzrlib.symbol_versioning module for decorators that take care of the
67
details for you - such as updating the docstring, and issuing a warning
68
when the old api is used.
70
For unsupported API's, it does not hurt to follow this discipline, but it's
71
not required. Minimally though, please try to rename things so that
72
callers will at least get an AttributeError rather than weird results.
75
Standard parameter types
76
------------------------
78
There are some common requirements in the library: some parameters need to be
79
unicode safe, some need byte strings, and so on. At the moment we have
80
only codified one specific pattern: Parameters that need to be unicode
81
should be checked via ``bzrlib.osutils.safe_unicode``. This will coerce the
82
input into unicode in a consistent fashion, allowing trivial strings to be
83
used for programmer convenience, but not performing unpredictably in the
84
presence of different locales.
90
The copyright policy for bzr was recently made clear in this email (edited
91
for grammatical correctness)::
93
The attached patch cleans up the copyright and license statements in
94
the bzr source. It also adds tests to help us remember to add them
95
with the correct text.
97
We had the problem that lots of our files were "Copyright Canonical
98
Development Ltd" which is not a real company, and some other variations
99
on this theme. Also, some files were missing the GPL statements.
101
I want to be clear about the intent of this patch, since copyright can
102
be a little controversial.
104
1) The big motivation for this is not to shut out the community, but
105
just to clean up all of the invalid copyright statements.
107
2) It has been the general policy for bzr that we want a single
108
copyright holder for all of the core code. This is following the model
109
set by the FSF, which makes it easier to update the code to a new
110
license in case problems are encountered. (For example, if we want to
111
upgrade the project universally to GPL v3 it is much simpler if there is
112
a single copyright holder). It also makes it clearer if copyright is
113
ever debated, there is a single holder, which makes it easier to defend
114
in court, etc. (I think the FSF position is that if you assign them
115
copyright, they can defend it in court rather than you needing to, and
116
I'm sure Canonical would do the same).
117
As such, Canonical has requested copyright assignments from all of the
120
3) If someone wants to add code and not attribute it to Canonical, there
121
is a specific list of files that are excluded from this check. And the
122
test failure indicates where that is, and how to update it.
124
4) If anyone feels that I changed a copyright statement incorrectly, just
125
let me know, and I'll be happy to correct it. Whenever you have large
126
mechanical changes like this, it is possible to make some mistakes.
128
Just to reiterate, this is a community project, and it is meant to stay
129
that way. Core bzr code is copyright Canonical for legal reasons, and
130
the tests are just there to help us maintain that.
136
When you change bzrlib, please update the relevant documentation for the
137
change you made: Changes to commands should update their help, and
138
possibly end user tutorials; changes to the core library should be
139
reflected in API documentation.
144
The docstring of a command is used by ``bzr help`` to generate help output
145
for the command. The list 'takes_options' attribute on a command is used by
146
``bzr help`` to document the options for the command - the command
147
docstring does not need to document them. Finally, the '_see_also'
148
attribute on a command can be used to reference other related help topics.
153
If you make a user-visible change, please add a note to the NEWS file.
154
The description should be written to make sense to someone who's just
155
a user of bzr, not a developer: new functions or classes shouldn't be
156
mentioned, but new commands, changes in behaviour or fixed nontrivial
157
bugs should be listed. See the existing entries for an idea of what
160
Within each release, entries in the news file should have the most
161
user-visible changes first. So the order should be approximately:
163
* changes to existing behaviour - the highest priority because the
164
user's existing knowledge is incorrect
165
* new features - should be brought to their attention
166
* bug fixes - may be of interest if the bug was affecting them, and
167
should include the bug number if any
168
* major documentation changes
169
* changes to internal interfaces
171
People who made significant contributions to each change are listed in
172
parenthesis. This can include reporting bugs (particularly with good
173
details or reproduction recipes), submitting patches, etc.
178
Functions, methods, classes and modules should have docstrings
179
describing how they are used.
181
The first line of the docstring should be a self-contained sentence.
183
For the special case of Command classes, this acts as the user-visible
184
documentation shown by the help command.
186
The docstrings should be formatted as reStructuredText_ (like this
187
document), suitable for processing using the epydoc_ tool into HTML
190
.. _reStructuredText: http://docutils.sourceforge.net/rst.html
191
.. _epydoc: http://epydoc.sourceforge.net/
198
Please write PEP-8__ compliant code.
200
One often-missed requirement is that the first line of docstrings
201
should be a self-contained one-sentence summary.
203
__ http://www.python.org/peps/pep-0008.html
210
Functions, methods or members that are in some sense "private" are given
211
a leading underscore prefix. This is just a hint that code outside the
212
implementation should probably not use that interface.
214
We prefer class names to be concatenated capital words (``TestCase``)
215
and variables, methods and functions to be lowercase words joined by
216
underscores (``revision_id``, ``get_revision``).
218
For the purposes of naming some names are treated as single compound
219
words: "filename", "revno".
221
Consider naming classes as nouns and functions/methods as verbs.
223
Try to avoid using abbreviations in names, because there can be
224
inconsistency if other people use the full name.
230
``revision_id`` not ``rev_id`` or ``revid``
232
Functions that transform one thing to another should be named ``x_to_y``
233
(not ``x2y`` as occurs in some old code.)
239
Python destructors (``__del__``) work differently to those of other
240
languages. In particular, bear in mind that destructors may be called
241
immediately when the object apparently becomes unreferenced, or at some
242
later time, or possibly never at all. Therefore we have restrictions on
243
what can be done inside them.
245
0. Never use a __del__ method without asking Martin/Robert first.
247
1. Never rely on a ``__del__`` method running. If there is code that
248
must run, do it from a ``finally`` block instead.
250
2. Never ``import`` from inside a ``__del__`` method, or you may crash the
253
3. In some places we raise a warning from the destructor if the object
254
has not been cleaned up or closed. This is considered OK: the warning
255
may not catch every case but it's still useful sometimes.
261
In some places we have variables which point to callables that construct
262
new instances. That is to say, they can be used a lot like class objects,
263
but they shouldn't be *named* like classes:
265
> I think that things named FooBar should create instances of FooBar when
266
> called. Its plain confusing for them to do otherwise. When we have
267
> something that is going to be used as a class - that is, checked for via
268
> isinstance or other such idioms, them I would call it foo_class, so that
269
> it is clear that a callable is not sufficient. If it is only used as a
270
> factory, then yes, foo_factory is what I would use.
276
Several places in Bazaar use (or will use) a registry, which is a
277
mapping from names to objects or classes. The registry allows for
278
loading in registered code only when it's needed, and keeping
279
associated information such as a help string or description.
285
To make startup time faster, we use the ``bzrlib.lazy_import`` module to
286
delay importing modules until they are actually used. ``lazy_import`` uses
287
the same syntax as regular python imports. So to import a few modules in a
290
from bzrlib.lazy_import import lazy_import
291
lazy_import(globals(), """
300
revision as _mod_revision,
302
import bzrlib.transport
306
At this point, all of these exist as a ``ImportReplacer`` object, ready to
307
be imported once a member is accessed. Also, when importing a module into
308
the local namespace, which is likely to clash with variable names, it is
309
recommended to prefix it as ``_mod_<module>``. This makes it clearer that
310
the variable is a module, and these object should be hidden anyway, since
311
they shouldn't be imported into other namespaces.
314
Modules versus Members
315
~~~~~~~~~~~~~~~~~~~~~~
317
While it is possible for ``lazy_import()`` to import members of a module
318
when using the ``from module import member`` syntax, it is recommended to
319
only use that syntax to load sub modules ``from module import submodule``.
320
This is because variables and classes can frequently be used without
321
needing a sub-member for example::
323
lazy_import(globals(), """
324
from module import MyClass
328
return isinstance(x, MyClass)
330
This will incorrectly fail, because ``MyClass`` is a ``ImportReplacer``
331
object, rather than the real class.
334
Passing to other variables
335
~~~~~~~~~~~~~~~~~~~~~~~~~~
337
It also is incorrect to assign ``ImportReplacer`` objects to other variables.
338
Because the replacer only knows about the original name, it is unable to
339
replace other variables. The ``ImportReplacer`` class will raise an
340
``IllegalUseOfScopeReplacer`` exception if it can figure out that this
341
happened. But it requires accessing a member more than once from the new
342
variable, so some bugs are not detected right away.
348
(The strategy described here is what we want to get to, but it's not
349
consistently followed in the code at the moment.)
351
bzrlib is intended to be a generically reusable library. It shouldn't
352
write messages to stdout or stderr, because some programs that use it
353
might want to display that information through a GUI or some other
356
We can distinguish two types of output from the library:
358
1. Structured data representing the progress or result of an
359
operation. For example, for a commit command this will be a list
360
of the modified files and the finally committed revision number
363
These should be exposed either through the return code or by calls
364
to a callback parameter.
366
A special case of this is progress indicators for long-lived
367
operations, where the caller should pass a ProgressBar object.
369
2. Unstructured log/debug messages, mostly for the benefit of the
370
developers or users trying to debug problems. This should always
371
be sent through ``bzrlib.trace`` and Python ``logging``, so that
372
it can be redirected by the client.
374
The distinction between the two is a bit subjective, but in general if
375
there is any chance that a library would want to see something as
376
structured data, we should make it so.
378
The policy about how output is presented in the text-mode client
379
should be only in the command-line tool.
385
In general tests should be placed in a file named test_FOO.py where
386
FOO is the logical thing under test. That file should be placed in the
387
tests subdirectory under the package being tested.
389
For example, tests for merge3 in bzrlib belong in bzrlib/tests/test_merge3.py.
390
See bzrlib/tests/test_sampler.py for a template test script.
392
Tests can be written for the UI or for individual areas of the library.
393
Choose whichever is appropriate: if adding a new command, or a new command
394
option, then you should be writing a UI test. If you are both adding UI
395
functionality and library functionality, you will want to write tests for
396
both the UI and the core behaviours. We call UI tests 'blackbox' tests
397
and they are found in ``bzrlib/tests/blackbox/*.py``.
399
When writing blackbox tests please honour the following conventions:
401
1. Place the tests for the command 'name' in
402
bzrlib/tests/blackbox/test_name.py. This makes it easy for developers
403
to locate the test script for a faulty command.
405
2. Use the 'self.run_bzr("name")' utility function to invoke the command
406
rather than running bzr in a subprocess or invoking the
407
cmd_object.run() method directly. This is a lot faster than
408
subprocesses and generates the same logging output as running it in a
409
subprocess (which invoking the method directly does not).
411
3. Only test the one command in a single test script. Use the bzrlib
412
library when setting up tests and when evaluating the side-effects of
413
the command. We do this so that the library api has continual pressure
414
on it to be as functional as the command line in a simple manner, and
415
to isolate knock-on effects throughout the blackbox test suite when a
416
command changes its name or signature. Ideally only the tests for a
417
given command are affected when a given command is changed.
419
4. If you have a test which does actually require running bzr in a
420
subprocess you can use ``run_bzr_subprocess``. By default the spawned
421
process will not load plugins unless ``--allow-plugins`` is supplied.
427
We have a rich collection of tools to support writing tests. Please use
428
them in preference to ad-hoc solutions as they provide portability and
429
performance benefits.
434
The ``TreeBuilder`` interface allows the construction of arbitrary trees
435
with a declarative interface. A sample session might look like::
437
tree = self.make_branch_and_tree('path')
438
builder = TreeBuilder()
439
builder.start_tree(tree)
440
builder.build(['foo', "bar/", "bar/file"])
441
tree.commit('commit the tree')
442
builder.finish_tree()
444
Please see bzrlib.treebuilder for more details.
449
The ``BranchBuilder`` interface allows the creation of test branches in a
450
quick and easy manner. A sample session::
452
builder = BranchBuilder(self.get_transport().clone('relpath'))
453
builder.build_commit()
454
builder.build_commit()
455
builder.build_commit()
456
branch = builder.get_branch()
458
Please see bzrlib.branchbuilder for more details.
463
We make selective use of doctests__. In general they should provide
464
*examples* within the API documentation which can incidentally be tested. We
465
don't try to test every important case using doctests -- regular Python
466
tests are generally a better solution.
468
Most of these are in ``bzrlib/doc/api``. More additions are welcome.
470
__ http://docs.python.org/lib/module-doctest.html
475
Currently, bzr selftest is used to invoke tests.
476
You can provide a pattern argument to run a subset. For example,
477
to run just the blackbox tests, run::
479
./bzr selftest -v blackbox
481
To skip a particular test (or set of tests), use the --exclude option
482
(shorthand -x) like so::
484
./bzr selftest -v -x blackbox
486
To list tests without running them, use the --list-only option like so::
488
./bzr selftest --list-only
490
This option can be combined with other selftest options (like -x) and
491
filter patterns to understand their effect.
494
Errors and exceptions
495
=====================
497
Errors are handled through Python exceptions.
499
We broadly classify errors as either being either internal or not,
500
depending on whether ``user_error`` is set or not. If we think it's our
501
fault, we show a backtrace, an invitation to report the bug, and possibly
502
other details. This is the default for errors that aren't specifically
503
recognized as being caused by a user error. Otherwise we show a briefer
504
message, unless -Derror was given.
506
Many errors originate as "environmental errors" which are raised by Python
507
or builtin libraries -- for example IOError. These are treated as being
508
our fault, unless they're caught in a particular tight scope where we know
509
that they indicate a user errors. For example if the repository format
510
is not found, the user probably gave the wrong path or URL. But if one of
511
the files inside the repository is not found, then it's our fault --
512
either there's a bug in bzr, or something complicated has gone wrong in
513
the environment that means one internal file was deleted.
515
Many errors are defined in ``bzrlib/errors.py`` but it's OK for new errors
516
to be added near the place where they are used.
518
Exceptions are formatted for the user by conversion to a string
519
(eventually calling their ``__str__`` method.) As a convenience the
520
``._fmt`` member can be used as a template which will be mapped to the
521
error's instance dict.
523
New exception classes should be defined when callers might want to catch
524
that exception specifically, or when it needs a substantially different
527
Exception strings should start with a capital letter and should not have a
528
final fullstop. If long, they may contain newlines to break the text.
535
Bazaar has a few facilities to help debug problems by going into pdb_, the
538
.. _pdb: http://docs.python.org/lib/debugger-commands.html
540
If the ``BZR_PDB`` environment variable is set
541
then bzr will go into pdb post-mortem mode when an unhandled exception
544
If you send a SIGQUIT signal to bzr, which can be done by pressing C-\ on Unix,
545
bzr will go into the debugger immediately. You can continue execution by
546
typing ``c``. This can be disabled if necessary by setting the
547
environment variable ``BZR_SIGQUIT_PDB=0``.
555
Integer identifier for a revision on the main line of a branch.
556
Revision 0 is always the null revision; others are 1-based
557
indexes into the branch's revision history.
563
The ``Transport`` layer handles access to local or remote directories.
564
Each Transport object acts like a logical connection to a particular
565
directory, and it allows various operations on files within it. You can
566
*clone* a transport to get a new Transport connected to a subdirectory or
569
Transports are not used for access to the working tree. At present
570
working trees are always local and they are accessed through the regular
571
Python file io mechanisms.
576
Transports work in URLs. Take note that URLs are by definition only
577
ASCII - the decision of how to encode a Unicode string into a URL must be
578
taken at a higher level, typically in the Store. (Note that Stores also
579
escape filenames which cannot be safely stored on all filesystems, but
580
this is a different level.)
582
The main reason for this is that it's not possible to safely roundtrip a
583
URL into Unicode and then back into the same URL. The URL standard
584
gives a way to represent non-ASCII bytes in ASCII (as %-escapes), but
585
doesn't say how those bytes represent non-ASCII characters. (They're not
586
guaranteed to be UTF-8 -- that is common but doesn't happen everywhere.)
588
For example if the user enters the url ``http://example/%e0`` there's no
589
way to tell whether that character represents "latin small letter a with
590
grave" in iso-8859-1, or "latin small letter r with acute" in iso-8859-2
591
or malformed UTF-8. So we can't convert their URL to Unicode reliably.
593
Equally problematic if we're given a url-like string containing non-ascii
594
characters (such as the accented a) we can't be sure how to convert that
595
to the correct URL, because we don't know what encoding the server expects
596
for those characters. (Although this is not totally reliable we might still
597
accept these and assume they should be put into UTF-8.)
599
A similar edge case is that the url ``http://foo/sweet%2Fsour`` contains
600
one directory component whose name is "sweet/sour". The escaped slash is
601
not a directory separator. If we try to convert URLs to regular Unicode
602
paths this information will be lost.
604
This implies that Transports must natively deal with URLs; for simplicity
605
they *only* deal with URLs and conversion of other strings to URLs is done
606
elsewhere. Information they return, such as from ``list_dir``, is also in
607
the form of URL components.
610
Unicode and Encoding Support
611
============================
613
This section discusses various techniques that Bazaar uses to handle
614
characters that are outside the ASCII set.
619
When a ``Command`` object is created, it is given a member variable
620
accessible by ``self.outf``. This is a file-like object, which is bound to
621
``sys.stdout``, and should be used to write information to the screen,
622
rather than directly writing to ``sys.stdout`` or calling ``print``.
623
This file has the ability to translate Unicode objects into the correct
624
representation, based on the console encoding. Also, the class attribute
625
``encoding_type`` will effect how unprintable characters will be
626
handled. This parameter can take one of 3 values:
629
Unprintable characters will be represented with a suitable replacement
630
marker (typically '?'), and no exception will be raised. This is for
631
any command which generates text for the user to review, rather than
632
for automated processing.
633
For example: ``bzr log`` should not fail if one of the entries has text
634
that cannot be displayed.
637
Attempting to print an unprintable character will cause a UnicodeError.
638
This is for commands that are intended more as scripting support, rather
639
than plain user review.
640
For exampl: ``bzr ls`` is designed to be used with shell scripting. One
641
use would be ``bzr ls --null --unknows | xargs -0 rm``. If ``bzr``
642
printed a filename with a '?', the wrong file could be deleted. (At the
643
very least, the correct file would not be deleted). An error is used to
644
indicate that the requested action could not be performed.
647
Do not attempt to automatically convert Unicode strings. This is used
648
for commands that must handle conversion themselves.
649
For example: ``bzr diff`` needs to translate Unicode paths, but should
650
not change the exact text of the contents of the files.
653
``bzrlib.urlutils.unescape_for_display``
654
----------------------------------------
656
Because Transports work in URLs (as defined earlier), printing the raw URL
657
to the user is usually less than optimal. Characters outside the standard
658
set are printed as escapes, rather than the real character, and local
659
paths would be printed as ``file://`` urls. The function
660
``unescape_for_display`` attempts to unescape a URL, such that anything
661
that cannot be printed in the current encoding stays an escaped URL, but
662
valid characters are generated where possible.
668
The ``bzrlib.osutils`` module has many useful helper functions, including
669
some more portable variants of functions in the standard library.
671
In particular, don't use ``shutil.rmtree`` unless it's acceptable for it
672
to fail on Windows if some files are readonly or still open elsewhere.
673
Use ``bzrlib.osutils.rmtree`` instead.
679
If you'd like to propose a change, please post to the
680
bazaar@lists.canonical.com list with a patch, bzr changeset, or link to a
681
branch. Please put '[patch]' in the subject so we can pick them out, and
682
include some text explaining the change. Remember to put an update to the NEWS
683
file in your diff, if it makes any changes visible to users or plugin
684
developers. Please include a diff against mainline if you're giving a link to
687
Please indicate if you think the code is ready to merge, or if it's just a
688
draft or for discussion. If you want comments from many developers rather than
689
to be merged, you can put '[rfc]' in the subject lines.
691
Anyone is welcome to review code. There are broadly three gates for
694
* Doesn't reduce test coverage: if it adds new methods or commands,
695
there should be tests for them. There is a good test framework
696
and plenty of examples to crib from, but if you are having trouble
697
working out how to test something feel free to post a draft patch
700
* Doesn't reduce design clarity, such as by entangling objects
701
we're trying to separate. This is mostly something the more
702
experienced reviewers need to help check.
704
* Improves bugs, features, speed, or code simplicity.
706
Code that goes in should pass all three.
708
If you read a patch please reply and say so. We can use a numeric scale
709
of -1, -0, +0, +1, meaning respectively "really don't want it in current
710
form", "somewhat uncomfortable", "ok with me", and "please put it in".
711
Anyone can "vote". (It's not really voting, just a terse expression.)
713
If something gets say two +1 votes from core reviewers, and no
714
vetos, then it's OK to come in. Any of the core developers can bring it
715
into their integration branch, which I'll merge regularly. (If you do
716
so, please reply and say so.)
722
We write some extensions in C using pyrex. We design these to work in
725
* User with no C compiler
726
* User with C compiler
729
The recommended way to install bzr is to have a C compiler so that the
730
extensions can be built, but if no C compiler is present, the pure python
731
versions we supply will work, though more slowly.
733
For developers we recommend that pyrex be installed, so that the C
734
extensions can be changed if needed.
736
For the C extensions, the extension module should always match the
737
original python one in all respects (modulo speed). This should be
738
maintained over time.
740
To create an extension, add rules to setup.py for building it with pyrex,
741
and with distutils. Now start with an empty .pyx file. At the top add
742
"include 'yourmodule.py'". This will import the contents of foo.py into this
743
file at build time - remember that only one module will be loaded at
744
runtime. Now you can subclass classes, or replace functions, and only your
745
changes need to be present in the .pyx file.
747
Note that pyrex does not support all 2.4 programming idioms, so some
748
syntax changes may be required. I.e.
750
- 'from foo import (bar, gam)' needs to change to not use the brackets.
751
- 'import foo.bar as bar' needs to be 'import foo.bar; bar = foo.bar'
753
If the changes are too dramatic, consider
754
maintaining the python code twice - once in the .pyx, and once in the .py,
755
and no longer including the .py file.
757
Making installers for OS Windows
758
================================
759
To build a win32 installer, see the instructions on the wiki page:
760
http://bazaar-vcs.org/BzrWin32Installer
763
:: vim: ft=rst tw=74 ai