1
.. Этот файл в формате ReStructuredText - он может быть отформатирован в HTML,
2
.. или текст. В будущем планируется выделять примеры команд и автоматически
5
.. Данный текст сначала был на Wiki
6
.. http://bazaar.canonical.com/IntroductionToBzr
7
.. но был перемещен в дерево исходного кода что бы синхронизироваться
8
.. с исходным кодом и возможно автоматически тестироваться.
14
Текущая версия для bzr-0.91, 2007-08
20
Если вы уже знакомы с распределенными системами контроля версий, то можете
21
сразу перейти к "Представляем себя Bazaar". Если, с другой стороны, вы знакомы
22
с системами контроля версий, но не знакомы с распределенными системами, тогда
23
стоит начать с "Чем отличаются распределенные системы". Иначе, возьмите кофе
24
или чай, расположитесь поудобнее и продолжим чтение.
26
Назначение контроля версий
27
==========================
29
Есть шансы, что вы уже работали с какими-либо текстовыми данными -- исходниками
30
программ, Web-сайтами, или конфигурационными файлами с которыми имеют дело
31
администраторы систем Unix в /etc. Так же есть хорошие шансы, что вы делали
32
ошибки, которые вызывали потом глубокое сожаление. Возможно вы удалили
33
конфигурационный файл для вашего почтового сервера, или повредили исходный код
34
любимого проекта. Не важно что конкретно случилось, но вы просто удалили важную
35
информацию которую вы безнадежно хотели бы вернуть. Если такое когда либо
36
случалось с вами, то вы возможно готовы для Bazaar.
38
Системы контроля версий, такие как Bazaar дают возможность отслеживать
39
изменения для директории, которую они изменяют в нечто более сложное, что
40
называется **ветка**. Ветка не только сохраняет как директория выглядит в
41
данный момент, но также как она выглядела в различные моменты в прошлом. Затем,
42
когда вы сделаете что-то, что бы вы не хотели делать, вы сможете восстановить
43
директорию в том виде как она выглядела в какой-то момент в прошлом.
45
Системы контроля версий дают пользователям возможность сохранять изменения на
46
ветке "фиксируя **ревизию**". Созданная ревизия фактически является сводкой
47
изменений, которые были сделаны с последнего момента когда дерево было
50
Эти ревизии имеют также и другое назначение. Например, можно комментировать
51
ревизии, записав, что значит данный набор изменений, через необязательную
52
запись в журнале. Реальные записи в журнале могут быть похожи на "Исправлен
53
Web-шаблон для закрытия таблицы" и "Добавлена поддержка SFTP. Исправлен #595"
55
Мы храним этот журнал, что бы позже, в случае каких-либо проблем с SFTP, можно
56
было определить когда могла произойти проблема.
58
Чем отличаются распределенные системы
59
-------------------------------------
61
Многие системы контроля версий хранят данные на серверах. Если кто-то хочет
62
работать с кодом, который хранится в системе тогда ему нужно установить
63
соединение с сервером и "создать рабочую копию" кода. При этом создается
64
директорий в котором можно менять файлы и затем фиксировать изменения. Клиент
65
системы затем соединяется с сервером системы и сохраняет изменения. Этот метод
66
известен как централизованная модель.
68
Централизованная модель может иметь некоторые недостатки. Централизованная
69
система требует наличия соединения с сервером для любых действий по контролю
70
версий. Это может быть проблематичным если сервер находится на другой машине в
71
интернете, а клиент - нет. Или, хуже, клиент **в** интернете, а сервер - нет.
73
Распределенные системы контроля версий обходят эту проблему сохраняя ветки на
74
той же машине на которой находится клиент. В случае с Bazaar, ветка находится в
75
том же самом месте, что и код хранящийся под контролем версий. Это позволяет
76
пользователю сохранять (**фиксировать**) изменения когда он захочет -- даже без
77
сетевого подключения. Пользователю нужен доступ к интернету только когда он
78
хочет получить доступ к чьей-либо ветке в другом месте.
80
Общее требование, что многие люди хотят отслеживать изменения для директории,
81
такие как изменения файлов и изменения в поддиректориях. Отслеживать это
82
"руками" ужасный процесс, который со временем становится громоздким. До тех пор
83
пока вы не попробуете систему контроля версий, такую как Bazaar. Такие
84
инструменты автоматизируют процесс сохранения данных создавая **ревизии**
85
дерева директории когда пользователь запрашивает сделать это.
87
Системы контроля версий, такие как Bazaar, могут делать намного больше чем
88
просто хранить изменения и отменять ошибочные действия. Например, с помощью
89
Bazaar разработчики могут взять изменения кода на одной ветке и объединить их
90
со связанной веткой -- даже если эти изменения хранятся на ветке которую создал
91
кто-то другой. Это позволяет разработчикам сотрудничать без необходимости
92
открывать доступ на запись к репозиторию.
94
Bazaar помнит ''предков'' ревизии: предыдущие ревизии на которых основана
95
текущая ревизия. Одна ревизия может иметь больше одного прямого потомка, каждый
96
из которых со своими изменениями, что представляет дивергенцию в эволюции
97
дерева. Создание веток в Bazaar позволяет нескольким людям сотрудничать в
98
эволюции проекта, без необходимости работать жестко по шагам. Создание веток
99
может быть полезным даже для одного разработчика.
101
Представляем себя Bazaar
102
========================
104
Bazaar installs a single new command, **bzr**. Everything else is a
105
subcommand of this. You can get some help with ``bzr help``. Some arguments
106
are grouped in topics: ``bzr help topics`` to see which topics are available.
108
One function of a version control system is to keep track of who changed
109
what. In a decentralized system, that requires an identifier for each
110
author that is globally unique. Most people already have one of these: an
111
email address. Bazaar is smart enough to automatically generate an email
112
address by looking up your username and hostname. If you don't like the
113
guess that Bazaar makes, then three options exist:
115
1. Set an email address via ``bzr whoami``. This is the simplest way.
117
To set a global identity, use::
119
% bzr whoami "Your Name <email@example.com>"
121
If you'd like to use a different address for a specific branch, enter
122
the branch folder and use::
124
% bzr whoami --branch "Your Name <email@example.com>"
126
#. Setting the email address in the ``~/.bazaar/bazaar.conf`` [1]_ by
127
adding the following lines. Please note that ``[DEFAULT]`` is case
131
email=Your Name <email@isp.com>
133
As above, you can override this settings on a branch by branch basis
134
by creating a branch section in ``~/.bazaar/locations.conf`` and
135
adding the following lines::
137
[/the/path/to/the/branch]
138
email=Your Name <email@isp.com>
141
#. Overriding the two previous options by setting the global environment
142
variable ``$BZR_EMAIL`` or ``$EMAIL`` (``$BZR_EMAIL`` will take
143
precedence) to your full email address.
145
.. [1] On Windows, the users configuration files can be found in the
146
application data directory. So instead of ``~/.bazaar/branch.conf``
147
the configuration file can be found as:
148
``C:\Documents and Settings\<username>\Application Data\Bazaar\2.0\branch.conf``.
149
The same is true for ``locations.conf``, ``ignore``, and the
150
``plugins`` directory.
155
History is by default stored in the .bzr directory of the branch. In a
156
future version of Bazaar, there will be a facility to store it in a
157
separate repository, which may be remote.
159
We create a new branch by running ``bzr init`` in an existing directory::
166
/home/mbp/work/bzr.test/tutorial
173
As with CVS, there are three classes of file: unknown, ignored, and
174
versioned. The **add** command makes a file versioned: that is, changes
175
to it will be recorded by the system::
177
% echo 'hello world' > hello.txt
188
If you add the wrong file, simply use ``bzr remove`` to make it
189
unversioned again. This does not delete the working copy in this case,
190
though it may in others [2]_.
192
.. [2] ``bzr remove`` will remove the working copy if it is currently
193
versioned, but has no changes from the last committed version. You
194
can force the file to always be kept with the ``--keep`` option to
195
``bzr remove``, or force it to always be deleted with ``--force``.
200
All history is stored in a branch, which is just an on-disk directory
201
containing control files. By default there is no separate repository or
202
database as used in svn or svk. You can choose to create a repository if
203
you want to (see the ``bzr init-repo`` command). You may wish to do this
204
if you have very large branches, or many branches of a moderately sized
207
You'll usually refer to branches on your computer's filesystem just by
208
giving the name of the directory containing the branch. bzr also supports
209
accessing branches over http and sftp, for example::
211
% bzr log http://bazaar-vcs.org/bzr/bzr.dev/
212
% bzr log sftp://bazaar-vcs.org/bzr/bzr.dev/
214
By installing bzr plugins you can also access branches using the rsync
217
See the `Publishing your branch`_ section for more about how to put your
218
branch at a given location.
223
Once you have completed some work, you will want to **commit** it to the
224
version history. It is good to commit fairly often: whenever you get a
225
new feature working, fix a bug, or improve some code or documentation.
226
It's also a good practice to make sure that the code compiles and passes
227
its test suite before committing, to make sure that every revision is a
228
known-good state. You can also review your changes, to make sure you're
229
committing what you intend to, and as a chance to rethink your work before
230
you permanently record it.
232
Two bzr commands are particularly useful here: **status** and **diff**.
237
The **status** command tells you what changes have been made to the
238
working directory since the last revision::
244
``bzr status`` hides "boring" files that are either unchanged or ignored.
245
The status command can optionally be given the name of some files or
246
directories to check.
251
The **diff** command shows the full text of changes to all files as a
252
standard unified diff. This can be piped through many programs such as
253
''patch'', ''diffstat'', ''filterdiff'' and ''colordiff''::
256
=== added file 'hello.txt'
257
--- hello.txt 1970-01-01 00:00:00 +0000
258
+++ hello.txt 2005-10-18 14:23:29 +0000
263
With the ``-r`` option, the tree is compared to an earlier revision, or
264
the differences between two versions are shown::
266
% bzr diff -r 1000.. # everything since r1000
267
% bzr diff -r 1000..1100 # changes from 1000 to 1100
269
The ``--diff-options`` option causes bzr to run the external diff program,
270
passing options. For example::
272
% bzr diff --diff-options --side-by-side foo
274
Some projects prefer patches to show a prefix at the start of the path
275
for old and new files. The ``--prefix`` option can be used to provide
277
As a shortcut, ``bzr diff -p1`` produces a form that works with the
278
command ``patch -p1``.
283
When the working tree state is satisfactory, it can be **committed** to
284
the branch, creating a new revision holding a snapshot of that state.
289
The **commit** command takes a message describing the changes in the
290
revision. It also records your userid, the current time and timezone, and
291
the inventory and contents of the tree. The commit message is specified
292
by the ``-m`` or ``--message`` option. You can enter a multi-line commit
293
message; in most shells you can enter this just by leaving the quotes open
294
at the end of the line.
298
% bzr commit -m "added my first file"
300
You can also use the ``-F`` option to take the message from a file. Some
301
people like to make notes for a commit message while they work, then
302
review the diff to make sure they did what they said they did. (This file
303
can also be useful when you pick up your work after a break.)
305
Message from an editor
306
======================
308
If you use neither the ``-m`` nor the ``-F`` option then bzr will open an
309
editor for you to enter a message. The editor to run is controlled by
310
your ``$VISUAL`` or ``$EDITOR`` environment variable, which can be overridden
311
by the ``editor`` setting in ``~/.bazaar/bazaar.conf``; ``$BZR_EDITOR`` will
312
override either of the above mentioned editor options. If you quit the
313
editor without making any changes, the commit will be cancelled.
315
The file that is opened in the editor contains a horizontal line. The part
316
of the file below this line is included for information only, and will not
317
form part of the commit message. Below the separator is shown the list of
318
files that are changed in the commit. You should write your message above
319
the line, and then save the file and exit.
321
If you would like to see the diff that will be committed as you edit the
322
message you can use the ``--show-diff`` option to ``commit``. This will include
323
the diff in the editor when it is opened, below the separator and the
324
information about the files that will be committed. This means that you can
325
read it as you write the message, but the diff itself wont be seen in the
326
commit message when you have finished. If you would like parts to be
327
included in the message you can copy and paste them above the separator.
332
If you give file or directory names on the commit command line then only
333
the changes to those files will be committed. For example::
335
% bzr commit -m "documentation fix" commit.py
337
By default bzr always commits all changes to the tree, even if run from a
338
subdirectory. To commit from only the current directory down, use::
343
Removing uncommitted changes
344
============================
346
If you've made some changes and don't want to keep them, use the
347
**revert** command to go back to the previous head version. It's a good
348
idea to use ``bzr diff`` first to see what will be removed. By default the
349
revert command reverts the whole tree; if file or directory names are
350
given then only those ones will be affected. ``bzr revert`` also clears the
351
list of pending merges revisions.
356
Many source trees contain some files that do not need to be versioned,
357
such as editor backups, object or bytecode files, and built programs. You
358
can simply not add them, but then they'll always crop up as unknown files.
359
You can also tell bzr to ignore these files by adding them to a file
360
called ``.bzrignore`` at the top of the tree.
362
This file contains a list of file wildcards (or "globs"), one per line.
363
Typical contents are like this::
370
If a glob contains a slash, it is matched against the whole path from the
371
top of the tree; otherwise it is matched against only the filename. So
372
the previous example ignores files with extension ``.o`` in all
373
subdirectories, but this example ignores only ``config.h`` at the top level
374
and HTML files in ``doc/``::
379
To get a list of which files are ignored and what pattern they matched,
380
use ``bzr ignored``::
386
It is OK to have either an ignore pattern match a versioned file, or to
387
add an ignored file. Ignore patterns have no effect on versioned files;
388
they only determine whether unversioned files are reported as unknown or
391
The ``.bzrignore`` file should normally be versioned, so that new copies
392
of the branch see the same patterns::
395
% bzr commit -m "Add ignore patterns"
401
There are some ignored files which are not project specific, but more user
402
specific. Things like editor temporary files, or personal temporary files.
403
Rather than add these ignores to every project, bzr supports a global
404
ignore file in ``~/.bazaar/ignore`` [1]_. It has the same syntax as the
405
per-project ignore file.
414
The ``bzr log`` command shows a list of previous revisions. The ``bzr log
415
--forward`` command does the same in chronological order to get most
416
recent revisions printed at last.
418
As with ``bzr diff``, ``bzr log`` supports the ``-r`` argument::
420
% bzr log -r 1000.. # Revision 1000 and everything after it
421
% bzr log -r ..1000 # Everything up to and including r1000
422
% bzr log -r 1000..1100 # changes from 1000 to 1100
423
% bzr log -r 1000 # The changes in only revision 1000
429
The ``bzr info`` command shows some summary information about the working
430
tree and the branch history.
433
Versioning directories
434
======================
436
bzr versions files and directories in a way that can keep track of renames
437
and intelligently merge them::
440
% echo 'int main() {}' > src/simple.c
450
Deleting and removing files
451
===========================
453
You can delete files or directories by just deleting them from the working
454
directory. This is a bit different to CVS, which requires that you also
457
``bzr remove`` makes the file un-versioned, but may or may not delete
458
the working copy [2]_. This is useful when you add the wrong file,
459
or decide that a file should actually not be versioned.
464
% bzr remove -v hello.txt
474
If you remove the wrong file by accident, you can use ``bzr revert`` to
481
Often rather than starting your own project, you will want to submit a
482
change to an existing project. To do this, you'll need to get a copy of
483
the existing branch. Because this new copy is potentially a new branch,
484
the command is called **branch**::
486
% bzr branch http://bazaar-vcs.org/bzr/bzr.dev
489
This copies down the complete history of this branch, so we can do all
490
operations on it locally: log, annotate, making and merging branches.
491
There will be an option to get only part of the history if you wish.
493
You can also get a copy of an existing branch by copying its directory,
494
expanding a tarball, or by a remote copy using something like rsync.
496
Following upstream changes
497
==========================
499
You can stay up-to-date with the parent branch by "pulling" in their
504
After this change, the local directory will be a mirror of the source. This
505
includes the ''revision-history'' - which is a list of the commits done in
506
this branch, rather than merged from other branches.
508
This command only works if your local (destination) branch is either an
509
older copy of the parent branch with no new commits of its own, or if the
510
most recent commit in your local branch has been merged into the parent
513
Merging from related branches
514
=============================
516
If two branches have diverged (both have unique changes) then ``bzr
517
merge`` is the appropriate command to use. Merge will automatically
518
calculate the changes that exist in the branch you're merging from that
519
are not in your branch and attempt to apply them in your branch.
526
If there is a conflict during a merge, 3 files with the same basename
527
are created. The filename of the common base is appended with ".BASE",
528
the filename of the file containing your changes is appended with
529
".THIS" and the filename with the changes from the other tree is
530
appended with ".OTHER". Using a program such as kdiff3, you can now
531
comfortably merge them into one file. In order to commit you have to
532
rename the merged file (".THIS") to the original file name. To
533
complete the conflict resolution you must use the resolve command,
534
which will remove the ".OTHER" and ".BASE" files. As long as there
535
exist files with .BASE, .THIS or .OTHER the commit command will
540
% kdiff3 file.BASE file.OTHER file.THIS
544
[**TODO**: explain conflict markers within files]
547
Publishing your branch
548
======================
550
You don't need a special server to publish a bzr branch, just a normal web
551
server. Just mirror the files to your server, including the .bzr
552
directory. One can push a branch (or the changes for a branch) by one of
553
the following three methods:
555
* The best method is to use bzr itself to do it.
559
% bzr push sftp://servername.com/path/to/directory
561
(The destination directory must already exist unless the
562
``--create-prefix`` option is used.)
564
* Another option is the ``rspush`` plugin that comes with BzrTools, which
565
uses rsync to push the changes to the revision history and the working
568
You can also use copy the files around manually, by sending a tarball, or
569
using rsync, or other related file transfer methods. This is usually
570
less safe than using ``push``, but may be faster or easier in some
573
Moving changes between trees
574
============================
576
It happens to the best of us: sometimes you'll make changes in the wrong
577
tree. Maybe because you've accidentally started work in the wrong directory,
578
maybe because as you're working, the change turns out to be bigger than you
579
expected, so you start a new branch for it.
581
To move your changes from one tree to another, use
586
% bzr merge --uncommitted OLDDIR
588
This will apply all of the uncommitted changes you made in OLDDIR to NEWDIR.
589
It will not apply committed changes, even if they could be applied to NEWDIR
590
with a regular merge. The changes will remain in OLDDIR, but you can use ``bzr
591
revert OLDDIR`` to remove them, once you're satisfied with NEWDIR.
593
NEWDIR does not have to be a copy of OLDDIR, but they should be related.
594
The more different they are, the greater the chance of conflicts.