Управление версиями в Subversion

Для Subversion 1.4

(Соответствует редакции 3829)

Бен Коллинз-Сассман

Брайан У. Фитцпатрик

К. Майкл Пилато

Этот труд выпущен на условиях Creative Commons Attribution License. С текстом данной лицензии можно ознакомиться в интернете по адресу http://creativecommons.org/licenses/by/2.0/, или получить его по почте, отправив заявку по адресу Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.

[Дата выхода в свет будет объявлена дополнительно]


Содержание

Предисловие
Об этой книге
Для кого написана эта книга?
Как читать эту книгу?
Соглашения, принятые в книге
Типографские соглашения
Пиктограммы
Структура книги
Эта книга распространяется свободно
Благодарности
От Ben Collins-Sussman
От Brian W. Fitzpatrick
От C. Michael Pilato
Что такое Subversion?
История Subversion
Возможности Subversion
Архитектура Subversion
Компоненты Subversion
1. Фундаментальные понятия
Хранилище
Модели версионирования
Проблема разделения файлов
Модель Блокирование-Изменение-Разблокирование
Модель Копирование-Изменение-Слияние
Subversion в действии
URL хранилища в Subversion
Рабочие копии
Правки
Как рабочие копии отслеживают хранилище
Смешивание правок в рабочих копиях
Обновления и фиксации отделены друг от друга
Смешивание правок — это нормально
Смешивание правок — это полезно
Смешивание правок имеет ограничения
Подводя итоги
2. Экскурсия по Subversion
Читайте справку!
Импорт
Путешествие во времени вместе с Subversion
Создание рабочей копии
Простейший рабочий цикл
Обновление рабочей копии
Внесение изменений в рабочую копию
Анализ изменений
svn status
svn diff
svn revert
Разрешение конфликтов (при слиянии с чужими изменениями)
Слияние конфликтов вручную
Копирование файла поверх вашего рабочего файла
Использование svn revert
Фиксация изменений
Анализ истории
svn log
svn diff
Анализ локальных изменений
Сравнение рабочей копии с хранилищем
Сравнение хранилища с хранилищем
svn cat
svn list
Заключительное слово об истории
Другие полезные команды
svn cleanup
svn import
Подводя итоги
3. Профессиональное использование Subversion
Способы обозначения правок
Ключевые слова правок
Даты правок
Свойства
Зачем нужны свойства?
Использование свойств
Свойства и рабочий цикл Subversion
Автоматическая установка свойств
Переносимость файлов
Тип содержимого файла
Исполнимость файла
Символы конца строки
Пропуск неверсионированных элементов
Подстановка ключевых слов
Locking
Creating locks
Discovering locks
Breaking and stealing locks
Lock Communication
Внешние зависимости
Стержневые и оперативные правки
4. Ветвление и слияние
Что такое ветка?
Использование веток
Создание ветки
Работа с веткой
Ключевые идеи, стоящие за ветками
Копирование изменений между ветками
Копирование отдельных изменений
Ключевые идеи, стоящие за слиянием
Как правильнее всего использовать слияние
Ручной контроль слияния
Предварительный просмотр результатов слияния
Конфликты при слиянии
Учитывать или игнорировать происхождение
Типовые примеры
Полное объединение двух веток
Отмена изменений
Восстановление удаленных элементов
Типовые приемы использования веток
Ветки релизов
Функциональные ветки
Переключение рабочей копии
Метки
Создание простой метки
Создание комплексной метки
Поддержка веток
Структура хранилища
Продолжительность жизни информации
Vendor branches
General Vendor Branch Management Procedure
svn_load_dirs.pl
Подводя итоги
5. Администрирование хранилища
Repository Basics
Understanding Transactions and Revisions
Unversioned Properties
Repository Data Stores
Berkeley DB
FSFS
Repository Creation and Configuration
Hook Scripts
Berkeley DB Configuration
Repository Maintenance
An Administrator's Toolkit
svnlook
svnadmin
svndumpfilter
Berkeley DB Utilities
Repository Cleanup
Managing Disk Space
Repository Recovery
Migrating a Repository
Repository Backup
Adding Projects
Choosing a Repository Layout
Creating the Layout, and Importing Initial Data
Summary
6. Настройка сервера
Обзор
Http-сервер Apache
Сервер svnserve
svnserve через SSH
Выбор лучшей конфигурации сервера
Сетевая модель
Запросы и отклики
Кэширование клиентской идентификационной информации
Собственный сервер svnserve
Запуск Сервера
Встроенная аутентификация и авторизация
Создание файла пользователей и область хранилища
Установка контроля доступа
SSH идентификация и авторизация
Трюки конфигурирования SSH
Начальная настройка
Controlling the invoked command
httpd, the Apache HTTP server
Prerequisites
Basic Apache Configuration
Authentication Options
Basic HTTP Authentication
SSL Certificate Management
Authorization Options
Blanket Access Control
Per-Directory Access Control
Disabling Path-based Checks
Extra Goodies
Repository Browsing
Other Features
Path-Based Authorization
Supporting Multiple Repository Access Methods
7. Профессиональная настройка Subversion
Параметры времени выполнения
Структура области конфигурации
Конфигурация и реестр Windows
Параметры конфигурации
Servers
Config
Localization
Understanding locales
Subversion's use of locales
Using External Differencing Tools
External diff
External diff3
8. Информация для разработчиков
Layered Library Design
Repository Layer
Repository Access Layer
RA-DAV (Repository Access Using HTTP/DAV)
RA-SVN (Custom Protocol Repository Access)
RA-Local (Direct Repository Access)
Your RA Library Here
Client Layer
Using the APIs
The Apache Portable Runtime Library
URL and Path Requirements
Using Languages Other than C and C++
Inside the Working Copy Administration Area
The Entries File
Pristine Copies and Property Files
WebDAV
9. Полное справочное руководство по Subversion
Клиент командной строки Subversion: svn
Параметры командной строкиsvn
Подкоманды svn
svn add
svn blame
svn cat
svn checkout
svn cleanup
svn commit
svn copy
svn delete
svn diff
svn export
svn help
svn import
svn info
svn list
svn lock
svn log
svn merge
svn mkdir
svn move
svn propdel
svn propedit
svn propget
svn proplist
svn propset
svn resolved
svn revert
svn status
svn switch
svn unlock
svn update
svnadmin
svnadmin Switches
svnadmin Subcommands
svnadmin create
svnadmin deltify
svnadmin dump
svnadmin help
svnadmin hotcopy
svnadmin list-dblogs
svnadmin list-unused-dblogs
svnadmin load
svnadmin lslocks
svnadmin lstxns
svnadmin recover
svnadmin rmlocks
svnadmin rmtxns
svnadmin setlog
svnadmin verify
svnlook
svnlook Switches
svnlook
svnlook author
svnlook cat
svnlook changed
svnlook date
svnlook diff
svnlook dirs-changed
svnlook help
svnlook history
svnlook info
svnlook lock
svnlook log
svnlook propget
svnlook proplist
svnlook tree
svnlook uuid
svnlook youngest
svnserve
svnserve Switches
svnversion
svnversion
mod_dav_svn
mod_dav_svn Configuration Directives
Свойства Subversion
Свойства Subversion
A. Быстрый старт в Subversion
Установка Subversion
Быстрый старт в Subversion
B. Subversion для пользователей CVS
Revision Numbers Are Different Now
Directory Versions
More Disconnected Operations
Distinction Between Status and Update
Status
Update
Branches and Tags
Metadata Properties
Conflict Resolution
Binary Files and Translation
Versioned Modules
Authentication
Converting a Repository from CVS to Subversion
C. WebDAV и автоматическое управление версиями
Basic WebDAV Concepts
Original WebDAV
DeltaV Extensions
Subversion and DeltaV
Autoversioning
Client Interoperability
Standalone WebDAV applications
Microsoft Office, Dreamweaver, Photoshop
Cadaver, DAV Explorer
File-explorer WebDAV extensions
Microsoft Web Folders
Nautilus, Konqueror
WebDAV filesystem implementation
WebDrive, NetDrive
Mac OS X
Linux davfs2
D. Инструменты от сторонних разработчиков
E. Copyright
Предметный указатель
Русский глоссарий

Список иллюстраций

1. Архитектура Subversion
1.1. Типичная клиент/серверная система
1.2. Проблема потери изменений
1.3. Модель блокирование-изменение-разблокирование
1.4. Модель копирование-изменение-слияние
1.5. Модель копирование-изменение-слияние (продолжение)
1.6. Файловая система хранилища
1.7. Хранилище
4.1. Ветки разработки
4.2. Начальная структура хранилища
4.3. Хранилище, содержащее новую копию
4.4. История ветвления для одного файла
8.1. Files and directories in two dimensions
8.2. Versioning time—the third dimension!

Список таблиц

1.1. URL для доступа к хранилищу.
5.1. Repository Data Store Comparison
6.1. Сравнение серверов
8.1. A Brief Inventory of the Subversion Libraries
C.1. Common WebDAV Clients

Список примеров

5.1. txn-info.sh (Reporting Outstanding Transactions)
6.1. A sample configuration for anonymous access.
6.2. A sample configuration for authenticated access.
6.3. A sample configuration for mixed authenticated/anonymous access.
6.4. Disabling path checks altogether
7.1. Пример указания параметров в (.reg) файле реестра.
7.2. diffwrap.sh
7.3. diffwrap.bat
7.4. diff3wrap.sh
7.5. diff3wrap.bat
8.1. Using the Repository Layer
8.2. Using the Repository Layer with Python
8.3. A Python Status Crawler
8.4. Contents of a Typical .svn/entries File

Предисловие

Карл Фогель

Чикаго, 14 марта 2004 г.

Скверный список ответов на часто задаваемые вопросы (ЧаВо) состоит не из тех вопросов, которые были заданы на самом деле, а из тех, на которые автору такого списка хотелось бы дать ответ. Вы наверняка сталкивались с чем-то подобным:

ВОПРОС: Как Glorbosoft XYZ поможет поднять производительность труда наших сотрудников?

ОТВЕТ: Многие наши клиенты хотят знать, как поднять производительность труда при помощи наших патентованных офисных инноваций для коллективной работы. Ответ простой: выберите меню «Файл» и перейдите к пункту «Поднять производительность», затем…

Проблема подобных ЧаВо заключается в том, что они вовсе не являются ответами на часто задаваемые вопросы в буквальном смысле. Какой нормальный человек будет звонить в службу технической поддержки и спрашивать: «как нам поднять производительность труда»? Вопросы, которые обычно звучат в таких случаях, узко специализированы, например: «Как настроить календарь для отправки напоминаний за два дня вместо одного?». Однако, создать список якобы заданных вопросов намного проще, чем подобрать настоящие вопросы из реальной жизни. Такая работа требует упорства и организованности: вопросы, возникающие в процессе жизненного цикла программного продукта, и ответы на них должны бережно сохраняться и систематизироваться, пока на их основе не будет создано логически связанное и удобное для поиска единое целое, наилучшим образом отражающее опыт пользователей. Здесь требуется терпеливость и внимательность, присущие естествоиспытателю, а не великие гипотезы и провидческие заявления. Главное в этой работе — открытые глаза и аккуратное отношение к записям в блокноте.

В этой книге мне больше всего нравится то, что она именно так и была написана, и это заметно на каждой её странице. Она является непосредственным результатом общения авторов с пользователями. Книга началась с того, что Бен Коллинз-Сассман как-то раз заметил в рассылке Subversion, что пользователи всё время задают одни и те же вопросы: какого порядка действий следует придерживаться при работе с Subversion; есть ли отличия от других систем управления версиями при работе с ветками и метками; как узнать, кем было выполнено то или иное изменение?

Устав от ежедневного просмотра одних и тех же вопросов, Бен провёл месяц в напряжённой работе, и летом 2002 года появилось Руководство по Subversion — документ, в котором на 60 страницах описывались все основные приёмы работы с Subversion. Это руководство не претендовало на полноту, но оно было включено в поставку Subversion и помогало преодолеть начинающим пользователям первые трудности, с которыми они сталкивались. После того, как издательство O'Reilly and Associates решило выпустить полноценную книгу о Subversion, путь наименьшего сопротивления был очевиден: нужно было просто расширить Руководство по Subversion.

Таким образом, три соавтора новой книги получили необычную возможность. С одной стороны, перед ними была поставлена задача написать книгу в обычном смысле слова, от автора к читателю, начиная с содержания и первого черновика. Но, с другой стороны, у них также была возможность обращаться у устойчивому потоку — да что там говорить, к неуправляемому фонтану — материалу, поступающему от будущих читателей. Subversion уже был в то время в руках тысяч первых пользователей, которые давали множество отзывов не только о самом Subversion, но и о документации к нему.

Пока шла работа над книгой, Бен, Майк и Брайан постоянно отслеживали рассылки и чаты, скрупулёзно отмечая проблемы, с которыми пользователи сталкивались в реальных жизненных ситуациях. Мониторинг подобных отзывов входил в их служебные обязанности в CollabNet, но в данном случае эта работа оказалась неоценимой при подготовке документации к Subversion. В основу написанной ими книги положен твёрдый фундамент опыта, а не зыбучие пески принятия желаемого за действительное; в этой книге соединяются лучшие качества руководства пользователя и списка ЧаВо. Эта двойственность может быть незаметна при первом прочтении книги. При чтении книги по порядку, от корки до корки, создаётся ощущение, что перед нами прямолинейное описание программного продукта. Нам предлагают общий обзор, непременный в таких случаях вводный курс, главу по администрированию, несколько тем для продвинутых пользователей и, само собой, справочник по командам и способы устранения проблем. Лишь возвращаясь к этой книге снова и снова, вы сможете оценить её самобытность: отличительные подробности, которые могут появиться лишь при встрече с неожиданными ситуациями, примеры, взятые из жизни и, самое главное, внимательность к нуждам пользователей и их точке зрения.

Конечно, никто не может пообещать, что эта книга ответит на все ваши вопросы о Subversion. Иногда точность, с которой книга предвосхищает ваши вопросы, может показаться телепатической, но вполне может случиться и так, что вы столкнётесь с пробелом в коллективном знании сообщества и уйдёте с пустыми руками. Лучшее, что можно сделать в такой ситуации — отправить письмо на адрес с описанием вашей проблемы. Авторы по-прежнему читают эту рассылку, они внимательно наблюдают за вопросами, и, кроме того, сообщество пользователей не ограничивается тремя людьми, имена которых вынесены на обложку этой книги — многие подписчики рассылки также помогают вносить исправления и предлагают новый материал для книги. С точки зрения сообщества, решение вашей конкретной проблемы — это лишь приятный побочный эффект значительно более обширного проекта, а именно, постепенного исправления данной книги и самого Subversion с тем, чтобы как можно ближе соответствовать практике. Эти люди с удовольствием выслушают вас не только потому, что могут помочь, но и потому, что вы можете помочь им. При работе с Subversion, как и с любым другим бурно развивающимся свободным программным обеспечением, вы не будете чувствовать себя одиноким.

Пусть эта книга будет вашим верным помощником.

Об этой книге

 

«It is important not to let the perfect become the enemy of the good, even when you can agree on what perfect is. Doubly so when you can't. As unpleasant as it is to be trapped by past mistakes, you can't make any progress by being afraid of your own shadow during design.»

 
 --Greg Hudson

В мире программного обеспечения с открытым исходным кодом в качестве инструмента управления версиями долгое время использовалась Concurrent Versions System[1] (CVS). На это были свои причины. CVS сама по себе является свободным программным обеспечением, на работу с ней не накладывается ограничений, а поддержка сетевых возможностей позволяет десяткам географически разделённых программистов работать совместно — всё это отлично подходит для мира свободного программного обеспечения, отличающегося духом сотрудничества. CVS и её полубеспорядочная модель разработки стали краеугольными камнями культуры свободного программного обеспечения.

Но и у CVS есть свои недочеты, которые уже давно всем надоели. Здесь на сцене и появляется Subversion. Творцы Subversion стремятся завоевать сердца пользователей CVS сразу с двух сторон: во-первых, Subversion создаётся как система с открытым исходным кодом, которая по своему устройству и ощущениям от работы напоминает CVS, а во-вторых, она пытается исправить наиболее очевидные недостатки CVS. И хотя то, что получается в результате, не обязательно является новым витком в развитии технологий управления версиями, Subversion на самом деле очень мощное, удобное и гибкое средство. Сегодня едва ли не все новые проекты с открытым исходным кодом вместо CVS выбирают Subversion.

Эта книга описывает систему управления версиями Subversion поколения 1.4. Мы стремились охватить материал как можно шире. В то же время следует иметь в виду, что разработкой Subversion занимается активное энергичное сообщество, так что уже сейчас идёт работа над рядом особенностей и улучшений, которые будут внесены в последующие версии Subversion. Эти нововведения могут привести к некоторым расхождениям между командами и соответствующими пояснениями в тексте книги.

Для кого написана эта книга?

Эта книга написана для людей, которые владеют знаниями о компьютерах и хотят использовать Subversion для управления данными. Subversion может работать на разных операционных системах, но основным интерфейсом для взаимодействия с ней является командная строка. Инструмент для командной строки (svn) и ряд вспомогательных программ, это именно то, чему посвящена эта книга.

Для линейности изложения примеры в книге подразумевают, что читатель пользуется Unix-подобной операционной системой и относительно свободно чувствует себя с Unix и интерфейсом командной строки. Однако, программа svn работает и на других платформах, например в Microsoft Windows. Ввод и вывод этой программы в Windows и Unix практически идентичны, за исключением незначительных различий, вроде использования символа обратной косой черты (\) вместо прямой косой (/) в качестве разделителя компонентов пути к файлу.

Многие наши читатели — программисты или системные администраторы, испытывающие потребность отслеживать изменения в исходном коде. Такое использование Subversion является самым распространённым и положено в основу всех примеров в этой книге. Однако, Subversion можно использовать для управления информацией самого разного рода: графика, музыка, базы данных, документация — этот список можно продолжать до бесконечности. Для Subversion любые данные — это просто данные.

С одной стороны, мы писали книгу для читателя, который никогда не пользовался системами управления версиями ранее, а с другой пытались облегчить переход на Subversion пользователям CVS (и других систем). По мере необходимости, в тексте книги встречаются специальные врезки, посвященные другим системам управления версиями, а обзор основных различий между CVS и Subversion вынесен в отдельное приложение.

Обратите внимание, что примеры исходного кода являются всего лишь примерами. Хотя они и могут быть собраны с помощью определённых заклинаний для компилятора, в тексте книги они приводятся для иллюстрации соответствующей проблемы и не обязательно служат примером хорошего стиля программирования.

Как читать эту книгу?

Книга предназначена для людей с самым разным уровнем подготовки — от новичков, не имевших дела с управлением версиями ранее, до опытных системных администраторов. Важность той или иной главы для читателя будет зависеть от уровня его подготовки. Приведём наши рекомендации для разных групп читателей:

Опытные системные администраторы

Предполагается, что читатели этой группы раннее уже использовали систему управления версиями и теперь им не терпится поднять сервер Subversion как можно скорее. В Глава 5, Администрирование хранилища и Глава 6, Настройка сервера показано, как создать первое хранилище и сделать его доступным в сети. Далее можно перейти к изучению клиента Subversion, причём чтение Глава 2, Экскурсия по Subversion и Приложение B, Subversion для пользователей CVS будет наиболее быстрым путём к цели.

Новички

По-видимому, администратор уже установил Subversion в сети и вам необходимо научиться пользоваться клиентом. Если вы раньше не пользовались системой управления версиями, то Глава 1, Фундаментальные понятия будет необходимым введением. А Глава 2, Экскурсия по Subversion содержит основные сведения о клиенте Subversion.

Продвинутые пользователи

Рано или поздно ваш проект будет разрастаться, и тогда, независимо от того, администратор вы или пользователь, вам потребуется узнать, как делать в Subversion более сложные вещи: использовать ветки и осуществлять слияния (Глава 4, Ветвление и слияние), работать со свойствами (Глава 3, Профессиональное использование Subversion), настраивать рабочую среду (Глава 3, Профессиональное использование Subversion) и т.д. Эти главы не являются важными в самом начале работы, но их следует прочесть, когда вы разберётесь с основами.

Разработчики

Предполагается, что вы уже знакомы с Subversion и хотите либо расширить её, либо создать новое программное обеспечение на основе её многочисленных API[2]. Что ж, Глава 8, Информация для разработчиков написана именно для вас.

Книга завершается справочным материалом — Глава 9, Полное справочное руководство по Subversion представляет собой справочное руководство по всем командам Subversion, а несколько полезных тем раскрыто в приложениях. К этим разделам вы скорее всего будете обращаться уже после прочтения книги.

Соглашения, принятые в книге

В этом разделе приводятся соглашения, принятые в книге.

Типографские соглашения

Моноширинный шрифт

Используется для записи команд, результатов их выполнения и параметров командной строки.

Моноширинный шрифт с курсивом

Используется в коде и тексте для обозначения подлежащих замене элементов.

Курсив

Используется для имён файлов и каталогов.

Пиктограммы

[Замечание]Замечание

Замечание, относящееся к окружающему тексту.

[Подсказка]Подсказка

Полезный совет, относящийся к окружающему тексту.

[Внимание]Внимание

Предупреждение, относящееся к окружающему тексту.

Структура книги

Приведём краткий обзор содержания отдельных глав книги.

Об этой книге

В этой главе приводятся сведения об истории Subversion, обсуждаются её возможности, архитектура и компоненты.

Глава 1, Фундаментальные понятия

Глава объясняет основы управления версиями, в ней разбираются различные модели работы с версиями, а также рассказано о хранилищах, рабочих копиях и правках в Subversion.

Глава 2, Экскурсия по Subversion

Один день из жизни пользователя Subversion. Глава поясняет, как использовать клиент Subversion для получения данных, внесения в них изменений и фиксации изменённых данных в хранилище.

Глава 3, Профессиональное использование Subversion

Рассматриваются сложные вопросы, с которыми постоянные пользователи рано или поздно столкнутся. Например, версионирование метаданных, блокирование файлов и peg revisions.

Глава 4, Ветвление и слияние

В этой главе рассматриваются ветки, метки и слияния, показаны эффективные методы выполнения ветвлений и слияний, приводятся типичные примеры использования этих возможностей, а также даются сведения об отмене внесённых изменений. Глава также показывает, как легко переключиться с одной ветки на другую.

Глава 5, Администрирование хранилища

В главе рассматриваются основные особенности хранилища Subversion, включая использование инструментов для создания, настройки и поддержки хранилища.

Глава 6, Настройка сервера

В этой главе показано, как настроить сервер Subversion. Здесь же рассматриваются три способа организации доступа к хранилищу: HTTP, протокол svn и локальный доступ. Кроме того, в главе уделяется внимание вопросам установления личности, проверки прав доступа и организации анонимного доступа к хранилищу.

Глава 7, Профессиональная настройка Subversion

В этой главе подробно рассмотрены файлы для настройки клиента Subversion, обработка текста на национальнных языках и совместная работа Subversion с программами сторонних разработчиков.

Глава 8, Информация для разработчиков

В этой главе обсуждается внутреннее устройство Subversion, файловая система Subversion и служебные области рабочей копии с точки зрения программиста. Здесь же разбирается использование открытых API для написания программ, использующих Subversion, а также приводится информация о том, как вы можете внести вклад в разработку Subversion.

Глава 9, Полное справочное руководство по Subversion

Глава подробно объясняет использование всех подкоманд svn, svnadmin и svnlook. Все пояснения сопровождаются множеством примеров.

Приложение A, Быстрый старт в Subversion

Для самых нетерпеливых, ураганное описание того, как установить и немедленно приступить к использованию Subversion. Мы вас предупредили.

Приложение B, Subversion для пользователей CVS

В приложении рассматриваются сходства и различия между Subversion и CVS, приводится ряд рекомендаций, позволяющих избавиться от вредных привычек, приобретённых с годами работы с CVS. Здесь также приводится информация о нумерации правок в Subversion, рассказывается о возможности управления версиями для каталогов, приводятся сведения об автономных операциях, ветках, метках и метаданных, поясняется различие между подкомандами update и status, затронуты вопросы, связанные с разрешением конфликтов и установлением личности пользователя.

Приложение C, WebDAV и автоматическое управление версиями

Это приложение подробно рассматривает WebDAV и DeltaV и показывает, как настроить хранилище Subversion для подключения в виде совместно используемого ресурса DAV.

Приложение D, Инструменты от сторонних разработчиков

Здесь представлены некоторые программы, которые используют Subversion в своей работе, включая клиенты от сторонних производителей, инструменты для просмотра содержимого хранилища и другие программы.

Эта книга распространяется свободно

Эта книга начиналась с фрагментов документации, написанных разработчиками проекта Subversion, которые затем были собраны в единое целое и отредактированы. Поэтому, она всегда будет распространяться на условиях свободной лицензии (см. Приложение E, Copyright.) Фактически, книга писалась у всех на виду, как часть Subversion, что означает две вещи:

  • Вы всегда можете найти самую последнюю версию книги в хранилище Subversion, созданном специально для неё.

  • Вы можете распространять эту книгу и вносить в неё изменения по своему усмотрению — лицензия на использование книги является свободной. От вас требуется только ссылаться в качестве первоисточника на первоначальных авторов. Конечно, будет лучше всего, если вместо того, чтобы распространять собственную версию книги, вы поделитесь отзывами и исправлениями с сообществом разработчиков Subversion.

Достаточно свежую версию этой книги можно взять в Интернете по адресу http://svnbook.red-bean.com.

Благодарности

Этой книги не было б (или была б не столь полезна), если б не было Subversion. Поэтому, авторы хотят поблагодарить Brian Behlendorf и CollabNet за их решение финансировать такой рискованный и амбициозный проект; Jim Blandy за оригинальное название и дизайн Subversion — мы любим тебя, Jim; Karl Fogel за то, что ты хороший друг и великолепный лидер нашего сообщества.[3]

Благодарим издательство O'Reilly и наших редакторов, Linda Mui и Tatiana Diaz за их терпение и поддержку.

Наконец, мы благодарим всех тех людей, которые участвовали в создании этой книги своими обзорами, мнениями и исправлениями: Без сомнения, это далеко не полный список людей, без помощи которых эта книга была бы неполной и неточной: David Anderson, Jani Averbach, Ryan Barrett, Francois Beausoleil, Jennifer Bevan, Matt Blais, Zack Brown, Martin Buchholz, Brane Cibej, John R. Daily, Peter Davis, Olivier Davy, Robert P. J. Day, Mo DeJong, Brian Denny, Joe Drew, Nick Duffek, Ben Elliston, Justin Erenkrantz, Shlomi Fish, Julian Foad, Chris Foote, Martin Furter, Dave Gilbert, Eric Gillespie, David Glasser, Matthew Gregan, Art Haas, Eric Hanchrow, Greg Hudson, Alexis Huxley, Jens B. Jorgensen, Tez Kamihira, David Kimdon, Mark Benedetto King, Andreas J. Koenig, Nuutti Kotivuori, Matt Kraai, Scott Lamb, Vincent Lefevre, Morten Ludvigsen, Paul Lussier, Bruce A. Mah, Philip Martin, Feliciano Matias, Patrick Mayweg, Gareth McCaughan, Jon Middleton, Tim Moloney, Christopher Ness, Mats Nilsson, Joe Orton, Amy Lyn Pilato, Kevin Pilch-Bisson, Dmitriy Popkov, Michael Price, Mark Proctor, Steffen Prohaska, Daniel Rall, Jack Repenning, Tobias Ringstrom, Garrett Rooney, Joel Rosdahl, Christian Sauer, Larry Shatzer, Russell Steicke, Sander Striker, Erik Sjoelund, Johan Sundstroem, John Szakmeister, Mason Thomas, Eric Wadsworth, Colin Watson, Alex Waugh, Chad Whitacre, Josef Wolf, Blair Zajac, а также всё сообщество Subversion.

От Ben Collins-Sussman

Благодарю мою жену Frances, которая много месяцев вместо обычного «Дорогая, я ещё пишу e-mail» слышала «Дорогая, я ещё работаю над книгой». Я представить не могу, откуда у неё столько терпения! Она — великолепный противовес моему трудоголизму.

Благодарю всю мою родню и друзей за их искреннюю поддержку, несмотря на отсутствие у них настоящего интереса к моему занятию. (Ну, вы знаете, они говорят «О, ты пишешь книгу?», а когда ты говоришь, что это — компьютерная книга, они сразу теряют весь интерес).

Благодарю всех моих близких друзей, сделавших меня очень богатым человеком. Не смотрите на меня так, вы же знаете, кто вы.

Thanks to my parents for the perfect low-level formatting, and being unbelievable role models. Thanks to my son for the opportunity to pass that on.

От Brian W. Fitzpatrick

Огромное спасибо моей жене Marie за её невероятные понимание, поддержку и, прежде всего, терпение. Спасибо моему брату Eric, который познакомил меня с программированием под UNIX. Огромная благодарность моим Маме и Бабушке за всю их поддержку, а так же за то, что не вспоминают, как я на Рождество пришёл домой и с головой залез в свой ноутбук и работал над книгой.

Mike и Ben: было очень приятно работать над книгой вместе с вами. Heck, было приятно работать с тобой на работе!

Всем членам сообщества Subversion и "Apache Software Foundation" — спасибо за то, что был с вами. Не было дня, чтоб я не научился чему-нибудь у кого-нибудь из вас.

Наконец, спасибо моему дедушке, который всегда говорил «свобода равна ответственности». Я не могу не согласиться с этим.

От C. Michael Pilato

Отдельное спасибо моей жене, Amy, за её любовь, терпение, поддержку, за понимание поздними ночами, за то, что читала все разделы этой книги — ты всегда делала больше, чем требовалось, и делала это с невероятным изяществом. Gavin, когда ты дорастёшь до прочтения этой книги, я надеюсь, ты будешь гордиться своим отцом также, как он сейчас гордится тобой. Мама и папа (а также вся моя семья), спасибо вам за вашу постоянную поддержку и энтузиазм.

Снимаю шляпу перед Shep Kendall, который открыл для меня мир компьютеров; перед Ben Collins-Sussman, моим проводником по миру свободного программного обеспечения; перед Karl Fogel — вы мой .emacs; перед Greg Stein, за помощь в программировании; перед Brian Fitzpatrick — за получение писательского опыта с тобой. Многим людям, от которых я постоянно узнаю что-то новое — будьте такими всегда!

Наконец, Тому, кто великолепно продемострировал венец творения — спасибо тебе.

Что такое Subversion?

Subversion — это бесплатная система управления версиями с открытым исходным кодом. Subversion позволяет управлять файлами и каталогами, а так же сделанными в них изменениями во времени. Это позволяет восстановить более ранние версии данных, даёт возможность изучить историю всех изменений. Благодаря этому многие считают систему управления версиями своего рода «машиной времени».

Subversion может работать через сеть, что позволяет использовать её на разных компьютерах. В какой то степени, возможность большого количества людей не зависимо от их местоположения совместно работать над единым комплектом данных поощряет сотрудничество. Когда нет того ответственного звена цепи, того контролирующего элемента, который утверждает все изменения, работа становится более эффективной. При этом не нужно опасаться, что отказ от контролирующего элемента повлияет на качество, ведь благодаря сохранению истории изменений, даже если при изменении данных будут допущены ошибки, всегда можно сделать откат изменений к прежнему состоянию.

Некоторые системы управления версиями выступают также в качестве систем управления конфигурацией программного обеспечения (SCM[4]). Такие системы специально созданы для управления деревьями исходного кода и имеют множество особенностей, непосредственно относящихся к разработке программ: они понимают языки программирования и предоставляют инструменты для сборки программ. Subversion не является такой системой, она представляет собой систему общего назначения, которую можно использовать для управления любым набором файлов. Для Вас это будут исходники Ваших программ, а для кого-то другого это будет список продуктов или сведённое цифровое видео.

История Subversion

В начале 2000 года компания CollabNet, Inc. (http://www.collab.net) начала поиск людей для написания системы, способной заменить CVS. CollabNet предлагает комплекс программных средств для совместной работы, известный под названием CollabNet Enterprise Edition (CEE) [5], одним из составляющих которого является срество для управления версиями. В качестве такого средства в CEE использовалась CVS, хотя её недостатки были очевидны с самого начала, и для CollabNet было ясно, что рано или поздно придётся искать замену. К сожалению, CVS стала стандартом де-факто в мире открытого программного обеспечения, причём по той лишь причине, что ничего лучшего в то время не существовало, по крайней мере среди программ со свободной лицензией. И тогда CollabNet решила написать новую систему управления версиями с нуля, сохранив основные идеи CVS, но без ошибок и неудобств, присущих CVS.

В феврале 2000 года CollabNet связалась с автором книги Open Source Development with CVS [6] Карлом Фогелем [Karl Fogel] и предложила ему принять участие в этом новом проекте. Самое интересное то, что Карл как раз тогда уже обсуждал проект новой системы управления версиями со своим другом Джимом Блэнди [Jim Blandy]. Ещё в 1995 году они создали компанию Cyclic Software, которая занималась поддержкой пользователей CVS, и хотя позднее этот бизнес был продан, друзья продолжали использовать CVS в повседневной работе. Их разочарование в CVS привело Джима к обдумыванию улучшения принципов управления версиями. Впоследствии Джим не только придумал название «Subversion», но и разработал основные принципы устройства хранилища Subversion. Карл сразу согласился на предложение CollabNet, а работодатель Джима, RedHat Software, пожертвовал своим сотрудником для этого проекта, предоставив ему возможность работать над Subversion в течение неограниченного времени. CollabNet взяла на работу Карла и Бена Коллинза-Сассмана [Ben Collins-Sussman], и в мае началась работа по проектированию системы. Благодаря нескольким интуитивно точным шагам, предпринятых Брайаном Белендорфом [Brian Behlendorf] и Джейсоном Роббинсом [Jason Robbins] из CollabNet и Грегом Стайном, на тот момент независимым разработчиком, активно участвующим в создании спецификации WebDAV/DeltaV, вокруг Subversion быстро образовалось сообщество активных разработчиков. Оказалось, что многие люди испытывали похожее чувство разочарования от CVS, и они с радостью приветствовали появившуюся, наконец, возможность изменить положение вещей.

Стартовый коллектив разработчиков решил остановиться на достижении ряда простых целей. Они не собирались изобретать велосипед в подходах к управлению версиями, скорее им просто хотелось исправить CVS. Этот коллектив решил, что Subversion должна соответствовать CVS по набору возможностей, сохранить ту же самую модель разработки и избежать недостатков CVS. Хотя перед ними не стояла задача сделать систему, полностью идентичную CVS, было ясно, что Subverion должна быть похожа на CVS, чтобы любой пользователь CVS мог перейти на новую систему без особых затруднений.

И вот, 31 августа 2001 года, спустя четырнадцать месяцев с начала работы, команда прекратила использовать CVS и перешла на Subversion для управления версиями собственного исходного кода — Subversion стала «самодостаточной».

Хотя CollabNet стоит у истоков проекта и продолжает финансировать основную часть работы, оплачивая полный рабочий день нескольких ведущих разработчиков, Subversion развивается подобно большинству проектов с открытым исходным кодом, управляясь свободным и прозрачным набором правил, поощряющих меритократию. Лицензия CollabNet полностью соответствует принципам свободного программного обеспечения Debian — любой человек может устанавливать, изменять и распространять Subversion так, как ему заблагорассудится; для этого не требуется разрешения ни от CollabNet, ни от кого-либо ещё.

Возможности Subversion

Обсуждать возможности Subversion удобнее всего в разрезе её улучшений по сравнению с CVS. Суть некоторых рассматриваемых здесь возможностей может быть не совсем понятна читателям, которые плохо знакомы с CVS. Если же вы совсем не имеете представления об управлении версиями, то вам лучше сначала прочитать главу 2, «Основные понятия», где даётся доступное введение в управление версиями.

Subversion предоставляет следующие возможности:

Контроль изменений каталогов

CVS следит только за историей отдельных файлов, тогда как Subversion использует «виртуальную» файловую систему с возможностями управления версиями, которая способна отслеживать изменения во времени целых структур каталогов. Под управление версиями попадают и файлы, и каталоги.

Настоящая история версий

CVS контролирует лишь изменения файлов, поэтому такие операции, как копирование и переименование, хотя и относящиеся к файлам, но по существу являющиеся изменениями каталогов, содержащих эти файлы, в CVS не поддерживаются. Кроме того, в CVS вы не можете заменить файл, помещённый под управление версиями, другим файлом с тем же именем, но совершенно иным содержанием, возможно никак не связанным со старым объектом, без наследования таким элементом всей истории изменений. Subversion делает возможным добавление, удаление, копирование и переименование как файлов, так и каталогов. При этом каждый вновь добавленный файл начинает жизнь с чистого листа, сохраняя собственную историю изменений.

Атомарная фиксация изменений

Каждый набор изменений либо попадает в хранилище целиком, либо не попадает туда вовсе. Это позволяет разработчикам создавать и фиксировать изменения логически оправданными кусками, предотвращая тем самым проблемы, которые могут возникать в тех случаях, когда только часть необходимых изменений помещается в хранилище успешно.

Метаданные с версиями

Каждый файл и каталог имеет собственный набор свойств, представленных в виде названия и значения. Вы можете создавать и сохранять любые необходимые пары названий свойств и их значений. Свойства файлов точно так же находятся под управлением версиями, как и их содержимое.

Выбор средств доступа к хранилищу по сети

В Subversion используется абстракция доступа к хранилищу, что позволяет реализовывать самые разные сетевые механизмы доступа. Subversion может быть подключена к серверу HTTP Apache в виде модуля, что даёт ей огромное преимущество с точки зрения устойчивости работы и способности к взаимодействию, а также предоставляет прямой доступ к существующим возможностям этого сервера, включая установление личности, проверку прав доступа и сжатие информации при передаче. Кроме того, имеется лёгкий самостоятельный сервер Subversion, который использует собственный протокол взаимодействия с клиентами и может легко туннелировать данные через SSH.

Единый способ работы с данными

Subversion обнаруживает различия между файлами с помощью специального бинарного алгоритма, который одинаково работает как с текстовыми, так и с бинарными файлами. Файлы записываются в хранилище в сжатом виде независимо от их типа, а различия между отдельными версиями могут передаваться по сети в обоих направлениях.

Эффективные ветки и метки

Плата за использование веток и меток не должна быть пропорциональна размеру проекта. Subversion создаёт ветки и метки путём простого копирования проекта, используя механизм, похожий на жёсткие ссылки в файловых системах. Благодаря этому, операции по созданию веток и меток занимают немного времени.

Дружелюбность по отношению к разработчикам

Subversion не имеет исторического багажа. Она реализована в виде набора динамических библиотек на языке C, API которых хорошо известен. Это делает Subversion чрезвычайно удобной для сопровождения системой, пригодной для взаимодействия с другими приложениями и языками программирования.

Архитектура Subversion

Общий взгляд на устройство Subversion показан на рисунке 1.1, «Архитектура Subversion».

Рисунок 1. Архитектура Subversion

Архитектура Subversion


На одной стороне схемы изображено хранилище Subversion, в котором хранится информация с версиями. На противоположной стороне показана программа-клиент Subversion, которая управляет локальными отражениями различных фрагментов этих данных (также называемыми «рабочими копиями»). Между этими сторонами проложены различные маршруты, проходящие через разные слои доступа к хранилищу[7]. Некоторые из этих маршрутов используют компьютерные сети и сетевые сервера, чтобы достичь хранилища, в то время как другие маршруты в сети не нуждаются и ведут к хранилищу напрямую.

Компоненты Subversion

Установленная Subversion имеет несколько компонентов. Ниже приводится краткий обзор того, что вы получаете. Не тревожьтесь, если краткие описания заставляют вас чесать затылок, в этой книге есть еще много страниц, посвященных облегчению вашего замешательства.

svn

Клиент с интерфейсом командной строки.

svnversion

Программа, показывающая состояние (в пределах ревизий существующих элементов) рабочей копии.

svnlook

Инструмент прямого управления хранилищем Subversion.

svnadmin

Инструмент для создания, настройки или восстановления хранилища Subversion.

svndumpfilter

Программа для фильтрации дамповых потоков хранилища Subversion.

mod_dav_svn

Подключаемый модуль для HTTP-сервера Apache, использующийся для предоставления сетевого доступа к вашему хранилищу.

svnserve

Собственный отдельный сервер, запускаемый как процесс-демон и доступный посредством SSH; еще один способ для предоставления сетевого доступа к хранилищу.

svnsync

Программа для последовательного зеркалирования одного хранилища в другое через сеть.

При условии корректно установленной Subversion вы готовы к старту. Следующие две главы описывают использование svn — CLI-клиента Subversion.




[1] Система параллельного управления версиями

[2] Application Program Interface, интерфейс прикладного программирования

[3] Да, и спасибо, Karl, за твой трудоголизм при написании этой книги.

[4] Software Configuration Management

[5] Кроме того, еще существует CollabNet Team Edition (CTE), предназначенный в основном для небольших команд разработчиков.

[6] «Разработка программн с открытым исходным кодом с помощью CVS»

[7] Repository Access (RA) layers

Глава 1. Фундаментальные понятия

Эта глава представляет собой краткое, промежуточное введение в Subversion. Если управление версиями для вас в новинку, то эта глава специально для вас. Мы начнем с обсуждения основных понятий управления версиями, подойдем к основным идеям, лежащим в основе Subversion и покажем несколько простых примеров использования Subversion.

Несмотря на то, что примеры в этой главе показывают людей, разделяющих между собой набор исходных кодов программ, помните, что Subversion может управлять набором файлов любого типа — она не ограничивается помощью компьютерным программистам.

Хранилище

Subversion является централизованной системой для совместного использования информации. В свой основе это хранилище, являющееся центром хранения данных. Хранилище содержит информацию в форме дерева файлов — типичном представлении файлов и каталогов. Любое количество клиентов подключается к хранилищу и читает или записывает эти файлы. Записывая данные, клиент делает информацию доступной для остальных; читая данные, клиент получает информацию от других. Рисунок 1.1, «Типичная клиент/серверная система» иллюстрирует это.

Рисунок 1.1. Типичная клиент/серверная система

Типичная клиент/серверная система


Почему мы заостряем на этом внимание? Пока это звучит как определение типичного файл-сервера. И действительно, хранилище является разновидностью файл-сервера, однако не совсем обычного. Что делает хранилище Subversion особенным — это то, что он запоминает каждое внесенное изменение: любое изменение любого файла, равно как изменения в самом дереве каталогов, такие как добавление, удаление и реорганизация файлов и каталогов.

При чтении данных из хранилища клиент обычно видит только последнюю версию дерева файлов. Но клиент также имеет возможность просмотреть предыдущие состояния файловой системы. Например, клиент может запросить такие данные как, «Что содержал этот каталог в прошлую среду?» или «Кто был последним изменявшим этот файл и какие вносились изменения?» Вопросы подобного типа являются основополагающими для любой системы управления версиями — системы, разработанной для записи и отслеживания изменений информации во времени.

Модели версионирования

Основной задачей системы управления версиями является обеспечение совместного редактирования и использования информации. Однако разные системы используют разные способы для достижения этой цели. Очень важно понимать отличия между этими способами. Во-первых, это поможет сравнить и сопоставить существующие системы управления версиями, в случае, если вы столкнетесь с другими системами, подобными Subversion. Кроме того, впоследствии это поспособствует и более эфективному использованию Subversion, так как эта система поддерживает несколько различных способов работы.

Проблема разделения файлов

Всем системам управления версиями приходится решать одну и ту же основную проблему: как предоставить пользователям возможность совместного использования информации, при этом не позволяя им наступать друг другу на пятки? Дело в том, что пользователи запросто могут случайно перезаписать в хранилище изменения, сделанные друг другом.

Рассматриваемую ситуацию иллюстрирует Рисунок 1.2, «Проблема потери изменений». Допустим, у нас есть два соразработчика — Гарри и Салли. Каждый из них решил одновременно отредактировать один и тот же файл из хранилища. Если первым свои изменения в хранилище сохранит Гарри, то возможно, что (несколькими минутами позже) Салли может непреднамеренно перезаписать их своей новой версией файла. Несмотря на то, что версия файла Гарри не будет полностью потеряна (так как система помнит каждое изменение), внесенные Гарри изменения не будут отражены в новой версии файла Салли, потому что, начиная, она не видела изменения Гарри. Работа Гарри фактически потеряна — или, по крайней мере, отсутствует в последней версии файла — по случайности. Как раз этой ситуации мы и хотим избежать!

Рисунок 1.2. Проблема потери изменений

Проблема потери изменений


Модель Блокирование-Изменение-Разблокирование

Для того, чтобы несколько авторов не мешало работать друг другу, многие системы управления версиями применяют модель блокирование-изменение-разблокирование. Эта модель запрещает одновременное редактирование файла несколькими пользователями. Эксклюзивность доступа гарантируется блокировками. Перед началом редактирования Гарри должен «заблокировать» файл. Если Гарри заблокирует файл, Салли уже не сможет его заблокировать и внести свои изменения. Ей остается только читать файл и ждать, пока Гарри закончит свои изменения и снимет блокировку. Лишь после того, как Гарри разблокирует файл, Салли сможет получить его, заблокировать и начать редактирование. Рисунок 1.3, «Модель блокирование-изменение-разблокирование» демонстрирует это простое решение.

Рисунок 1.3. Модель блокирование-изменение-разблокирование

Модель блокирование-изменение-разблокирование


Проблемой модели блокирование-изменение-разблокирование является то, что она немного ограниченная и часто доставляет неудобства пользователям:

  • Блокирование может вызвать проблемы администрирования. Иногда Гарри может заблокировать файл, а затем забыть об этом. Между тем, ожидая редактирования файла, у Салли будут связаны руки. А Гарри тем временем уехал в отпуск. Теперь Салли, для снятия блокировки Гарри, нужно обращаться к администратору. Ситуация заканчивается не нужной задержкой и потерянным временем.

  • Блокирование может вызвать излишнюю пошаговость. Вполне вероятна ситуация, когда Гарри редактирует начало текстового файла, а Салли нужно отредактировать концовку этого же файла? Эти изменения совсем не перекрываются. Они могли бы легко редактировать файл одновременно, и при условии корректного слияния изменений это не вызвало бы никаких особенных проблем. Нет никакой необходимости блокировать файл в такой ситуации.

  • Блокирование может вызвать ложное чувство безопасности. Предположим, что Гарри блокирует и редактирует файл А, в то время как Салли одновременно блокирует и редактирует файл В. Но допустим, что А и В зависят друг от друга и сделанные в каждом изменения семантически не совместимы. Неожиданно А и В больше не работают вместе. Блокирующая система бессильна в предотвращении проблемы — вместо этого она обеспечила ложное чувство безопасности. Для Гарри и Салли просто вообразить, что, блокируя файлы каждый начинает безопасную изолированную задачу и не беспокоиться об обсуждении их несовместимых изменений заранее. Зачастую, блокирование подменяет настоящее общение.

Модель Копирование-Изменение-Слияние

Subversion, CVS и ряд других систем управления версиями в качестве альтернативы блокированию пользуются моделью копирование-изменение-слияние. В этой модели каждый пользовательский клиент связывается с хранилищем проекта и создает персональную рабочую копию — локальное отражение файлов и каталогов хранилища. После этого пользователи работают одновременно и независимо друг от друга, изменяя свои личные копии. В конце концов, личные копии сливаются в новую, итоговую версию. Обычно система управления версиями помогает в слиянии, но, разумеется, за его корректное выполнение отвечает человек.

В качестве примера предположим, что Гарри и Салли создали рабочие копии одного и того же проекта, скопировав их из хранилища. Они работают одновременно и в своих рабочих копиях вносят изменения в один и тот же файл А. Первой свои изменения в хранилище сохраняет Салли. Когда позже Гарри попытается сохранить свои изменения, хранилище проинформирует его о том, что его файл А устарел. Другими словами, файл А каким то образом изменился со времени, когда он его последний раз копировал. Поэтому Гарри просит свой клиент слить любые изменения из хранилища в его рабочую копию файла А. По счастливому совпадению, изменения Салли не перекрываются с его собственными; после объединения обоих наборов изменений он сохраняет свою рабочую копию обратно в хранилище. Рисунок 1.4, «Модель копирование-изменение-слияние» и Рисунок 1.5, «Модель копирование-изменение-слияние (продолжение)» показывают этот процесс.

Рисунок 1.4. Модель копирование-изменение-слияние

Модель копирование-изменение-слияние


Рисунок 1.5. Модель копирование-изменение-слияние (продолжение)

Модель копирование-изменение-слияние (продолжение)


А что будет, если изменения Салли перекрывают изменения Гарри? Что тогда? Эта ситуация называется конфликтом и, как правило, это не является большой проблемой. Когда Гарри просит свой клиент слить последние изменения из хранилища в рабочую копию, его копия файла А помечается некоторым образом как находящаяся в состоянии конфликта: у него будет возможность видеть оба набора конфликтующих изменений и вручную сделать между ними выбор. Помните, что ПО не может автоматически разрешать конфликты; только человек способен к пониманию и выполнению осмысленного выбора. Разрешив вручную перекрывающиеся изменения — возможно, после обсуждения с Салли — он может безопасно сохранить объединенный файл обратно в хранилище.

Модель копирование-изменение-слияние может выглядеть немного хаотично, однако, на практике она отлично работает. Пользователи могут работать параллельно, не тратя время на ожидание друг друга. При работе над одними и теми же файлами оказывается, что большинство параллельно вносимых изменений совсем не перекрываются; конфликты бывают редко. И время, которое было потрачено на разрешение конфликтов, как правило, значительно меньше времени, отнимаемого блокирующей системой.

Наконец, все сходится к такому критическому фактору как взаимодействие пользователей. При плохом взаимопонимании увеличивается количество как синтаксических, так и семантических конфликтов. Нет системы, которая может повысить уровень взаимопонимания, и нет системы, которая может определять семантические конфликты. Не стоит возлагать большие надежды на то, что блокирующая система лучше защищена от конфликтов; на практике блокирование снижает продуктивность как ничто другое.

Subversion в действии

Настало время перейти от абстракций к конкретике. В этом разделе мы покажем реальные примеры использования Subversion.

URL хранилища в Subversion

В книге для идентификации файлов и директорий в хранилище Subversion применяются URL. В основном, в этих URL используются стандартные правила записи, позволяющие указывать имя сервера и номер порта как часть URL:

$ svn checkout http://svn.example.com:9834/repos
…

Однако, в обработке URL системой Subversion есть некоторые нюансы, о которых нужно помнить. Например, в соответствии с принятыми соглашениями, URL, использующий метод доступа file: (этот метод доступа используется для локальных хранилищ), должен либо включать имя сервера localhost, либо вообще не содержать имени сервера:

$ svn checkout file:///path/to/repos
…
$ svn checkout file://localhost/path/to/repos
…

Кроме того, тем, кто применяет схему file: на платформе Windows, необходимо использовать неофициальные «стандартные» правила записи при обращении к хранилищу, которое находится на одном компьютере, но на разных дисках с клиентом. Обе приведенные ниже записи будут работать; здесь X — это имя диска, на котором находится хранилище:

C:\> svn checkout file:///X:/path/to/repos
…
C:\> svn checkout "file:///X|/path/to/repos"
…

При второй форме записи для того, чтобы вертикальная черта не расценивалась как канал, необходимо взять URL в кавычки. Также обратите внимание на использование в URL прямого слеша, несмотря на то, что родная (не-URL) форма записи пути в Windows использует обратный слеш.

Ну и наконец, нужно сказать о том, что клиент Subversion при необходимости автоматически кодирует URL точно так же, как это делает веб-браузер. Например, если URL будет содержать пробел или ASCII-символы в верхнем регистре:

$ svn checkout "http://host/path with space/project/españa"

…то Subversion скроет небезопасные символы и будет вести себя так, как будто вы напечатали:

$ svn checkout http://host/path%20with%20space/project/espa%C3%B1a

Если в URL есть пробелы, возьмите его в кавычки, и тогда командная оболочка обработает это все как один аргумент программы svn.

Рабочие копии

Вы уже читали о рабочих копиях; теперь мы покажем как клиент Subversion создает и использует их.

Рабочая копия Subversion представляет собой обычное дерево каталогов на вашем компьютере, содержащее набор файлов. Вы можете по своему усмотрению редактировать эти файлы и, если это исходные коды, вы можете обычным способом скомпилировать из них программу. Ваша рабочая копия — это ваше личное рабочее пространство. Subversion как не смешивает с вашими изменения, вносимые другими, так и не делает доступными для других изменения, сделанные вами, пока вы сами не прикажете сделать это. Вы даже можете иметь несколько рабочих копий одного и того же проекта.

После того, как вы внесли изменения в файлы вашей рабочей копии и убедились в том, что они корректно работают, Subversion предлагает вам команды «публикации» (записи в хранилище) ваших изменений, в результате чего они станут доступными для всех участников проекта. Если другие участники проекта опубликовали свои изменения, Subversion предлагает вам команды для объединения (путем чтения информации из хранилища) этих изменений с вашей рабочей копией.

Рабочая копия содержит несколько дополнительных файлов, созданных и обслуживаемых Subversion, которые помогают ей при выполнении этих команд. В частности, каждый каталог в вашей рабочей копии содержит подкаталог с именем .svn который называется служебным каталогом рабочей копии. Файлы в служебном каталоге помогают Subversion определить какие файлы рабочей копии содержат неопубликованные изменения, и какие файлы устарели по отношению к файлам других участников.

Как правило, хранилище Subversion содержит файлы (или исходный код) нескольких проектов; обычно каждый проект представляется в виде подкаталога файловой системы хранилища. При таком подходе, пользовательская рабочая копия обычно соответствует отдельному подкаталогу хранилища.

Например, предположим, что у вас есть хранилище, содержащее два программных проекта: paint и calc. Каждый проект располагается в своем собственном каталоге как показано на Рисунок 1.6, «Файловая система хранилища».

Рисунок 1.6. Файловая система хранилища

Файловая система хранилища


Для того, чтобы создать рабочую копию, вам нужно получить какой-либо из подкаталогов хранилища. (Возможно, термин получить звучит как что-то, связанное с блокированием или резервированием ресурсов, но это не так; данная команда просто создает для вас личную копию проекта.) Например, если вы получите /calc, у вас будет рабочая копия наподобие этой:

$ svn checkout http://svn.example.com/repos/calc
A    calc/Makefile
A    calc/integer.c
A    calc/button.c
Checked out revision 56.

$ ls -A calc
Makefile  integer.c  button.c  .svn/

Буквы А говорят о том, что Subversion добавил этот элемент в вашу рабочую копию. Теперь у вас есть личная копия каталога /calc хранилища, с одним небольшим добавлением — каталогом .svn, содержащим, как было указано выше, дополнительную информацию, необходимую Subversion.

Предположим, вы внесли изменения в button.c. Так как каталог .svn помнит дату изменения файла и его оригинальное содержимое, Subversion может сказать о том, что вы изменили файл. Subversion не публикует ваших изменений, пока вы не прикажете это сделать. Публикация ваших изменений более известна как фиксация (или checking in) изменений в хранилище.

Для того, чтобы опубликовать ваши изменения, вы можете воспользоваться командой commit.

$ svn commit button.c -m "Fixed a typo in button.c."
Sending        button.c
Transmitting file data .
Committed revision 57.

Теперь ваши изменения в button.c, вместе с примечанием, описывающим эти изменения (а именно: исправление опечатки), зафиксированы в хранилище; если другой пользователь создаст рабочую копию /calc, он увидит ваши изменения в последней версии файла.

Предположим, у вас есть партнер, Салли, которая создала рабочую копию /calc одновременно с вами. Когда вы зафиксировали изменения в button.c, рабочая копия Салли осталась неизмененной, так как Subversion модифицирует рабочие копии только по запросу пользователей.

Для приведения рабочей копии в актуальное состояние Салли может попросить Subversion обновить её рабочую копию, используя команду Subversion update. Это включит ваши изменения в ее рабочую копию, так же как и все другие изменения, зафиксированные после того, как она создавала рабочую копию.

$ pwd
/home/sally/calc

$ ls -A
.svn/ Makefile integer.c button.c

$ svn update
U    button.c
Updated to revision 57.

Вывод команды svn update говорит, что Subversion обновила содержимое button.c. Обратите внимание, что Салли не должна указывать, какой файл обновить; для определения файлов, которые необходимо привести в актуальное состояние, Subversion использует информацию в каталоге .svn, а также информацию из хранилища.

Правки

Операция svn commit публикует изменения любого количества файлов и каталогов за одну атомарную операцию. В своей рабочей копии вы можете менять содержимое файлов, создавать, удалять, переименовывать и копировать файлы и каталоги, а затем зафиксировать все изменения за одну атомарную транзакцию.

Под «атомарной транзакцией» понимается следующее: либо в хранилище вносятся все изменения полностью, либо они не вносятся вообще. Subversion ведёт себя так, принимая в расчет возможные программные сбои, системные сбои, проблемы с сетью, а также неверные действия пользователя.

Каждый раз, когда происходит фиксация, создаётся новое состояние файловой системы, которое называется правкой. Каждая правка получает уникальный номер, на единицу больший номера предыдущей правки. Начальная правка только что созданного хранилища получает номер 0 и не содержит ничего, кроме пустого корневого каталога.

Рисунок 1.7, «Хранилище» отлично иллюстрирует хранилище. Представьте массив номеров правок, начинающийся с 0, с направлением слева направо. Каждый номер правки имеет соответствующее дерево файлов, а каждое дерево представляет собой «снимок» того, как хранилище выглядело после фиксации.

Рисунок 1.7. Хранилище

Хранилище


Важно помнить, что рабочие копии не всегда соответствуют какой-то одной правке в хранилище; они могут содержать файлы из разных правок. Например, вы получили рабочую копию из хранилища, у которого самая последняя правка — 4:

calc/Makefile:4
     integer.c:4
     button.c:4

На данный момент рабочий каталог полностью соответствует правке 4 в хранилище. Допустим, что вы внесли изменения в button.c и зафиксировали эти изменения. При отсутствии других фиксаций ваша фиксация создаст правку под номером 5, и теперь ваша рабочая копия выглядит следующим образом:

calc/Makefile:4
     integer.c:4
     button.c:5

Предположим, что после этого Салли фиксирует изменения integer.c, создавая правку 6. Если вы воспользуетесь svn update для приведения своей рабочей копии в актуальное состояние, то она станет выглядеть так:

calc/Makefile:6
     integer.c:6
     button.c:6

Изменения, внесенные Салли в integer.c будут отражены в вашей рабочей копии, и ваши изменения в button.c также будут присутствовать. В этом примере текст Makefile в правках 4, 5 и 6 идентичен, однако Subversion проставляет номер правки 6 для вашей рабочей копии Makefile, чтобы показать что файл не устарел. Таким образом, после того как вы выполните полное обновление вашей рабочей копии, она будет полностью соответствовать текущему состоянию хранилища.

Как рабочие копии отслеживают хранилище

В служебном каталоге .svn/ для каждого файла рабочего каталога Subversion записывает информацию о двух важнейших свойствах:

  • на какой правке основан ваш рабочий файл (это называется рабочая правка файла), и

  • временной (ударение на последний слог) метке, определяющей, когда рабочая копия последний раз обновлялась из хранилища.

Используя эту информацию при соединении с хранилищем, Subversion может сказать, в каком из следующих четырех состояний находится рабочий файл:

Не изменялся и не устарел

Файл не изменялся в рабочем каталоге, а в хранилище также не фиксировались изменения этого файла со времени создания его рабочей правки. Команды svn commit и svn update никаких операций делать не будут.

Изменялся локально и не устарел

Файл был изменен в рабочей копии, но в хранилище не фиксировались изменения этого файла последнего обновления рабочей копии. Есть локальные изменения, которые не были зафиксированы в хранилище, поэтому svn commit выполнит фиксацию ваших изменений, а svn update не сделает ничего.

Не изменялся и устарел

В рабочем каталоге файл не изменялся, но был изменен в хранилище. Необходимо выполнить обновление файла для того, чтобы он соответствовал текущей опубликованной правке. Команда svn commit не сделает ничего, а svn update обновит вашу рабочую копию файла в соответствии с последними изменениями.

Изменялся локально и устарел

Файл был изменен как в рабочем каталоге, так и в хранилище. svn commit потерпит неудачу, выдав ошибку «out-of-date». Файл необходимо сначала обновить; svn update попытается объединить локальные изменения с опубликованными. Если Subversion не сможет выполнить объединение самостоятельно, она предложит пользователю разрешить конфликт вручную.

Может показаться, что следить за актуальным состоянием рабочей копии сложно. Это не так. Для того, чтобы узнать состояние любого элемента в вашей рабочей копии, существует команда svn status. За более подробной информацией об этой команде обратитесь к «svn status».

Смешивание правок в рабочих копиях

Subversion старается быть гибкой настолько, насколько это возможно. Например, существует возможность иметь рабочую копию, содержащую файлы и каталоги, имеющие смешанные номера рабочих правок. Но, к сожалению, эта гибкость иногда смущает некоторых новых пользователей. Если раньше примеры, показывающие смешанные правки, вызывали у вас чувство растерянности, то это руководство, которое рассказывает, для чего такая возможность существует и как ее использовать, предназначена для вас.

Обновления и фиксации отделены друг от друга

Одно из фундаментальных правил Subversion заключается в том, что «передающее» действие не приводит к «принимаемому», и наоборот. То, что вы готовы внести изменения в хранилище, не означает, что вы готовы принять изменения от других. А если вы все еще работаете над новыми изменениями, то svn update изящно объединит изменения из хранилища с вашими собственными, вместо того, чтобы заставлять вас опубликовать их.

Главным побочным эффектом этого правила является то, что рабочая копия должна вести дополнительный учет при смешивании правок и быть аккуратной при любом смешивании. И то, что каталоги попадают под контроль версий, делает это еще более сложным для понимания.

Допустим, у вас есть рабочая копия, полностью соответствующая правке 10. После изменения файла foo.html, вы выполняете команду svn commit, которая создает в хранилище правку 15. После выполнения фиксации большая часть новичков ожидают, что вся рабочая копия будет иметь правку 15, однако это не так. Между правками 10 и 15 в хранилище могло быть внесено любое количество изменений. Так как команда svn update не выполнялась, а svn commit не загружает изменений, клиент ничего не знает о находящихся в хранилище изменениях. С другой стороны, если бы команда svn commit автоматически загружала последние изменения, то всей рабочей копии можно было бы назначить соответствующий номер правки - 15. Однако это нарушило бы фундаментальное правило, согласно которому «передача» и «получение» являются независимыми операциями. Следовательно, все, что может сделать клиент Subversion, это пометить один файл — foo.html — как соответствующий правке 15. Остальная рабочая копия продолжает соответствовать правке 10. Только при выполнении svn update будут загружены последние изменения, и вся рабочая копия будет помечена как соответствующая правке 15.

Смешивание правок — это нормально

Фактически, каждый раз при выполнении svn commit правки рабочей копии смешиваются. Только что зафиксированные элементы отмечаются как имеющие больший номер рабочей правки, чем все остальные. После нескольких фиксаций (без выполнения обновлений между ними) правки рабочей копии будут полностью перемешаны. Даже если вы являетесь единственным пользователем хранилища, вы все равно с этим столкнетесь. Для просмотра этой смеси рабочих правок воспользуйтесь командой svn status --verbose (см. «svn status»).

Часто новые пользователи даже не подозревают о том, что их рабочая копия содержит смешанные правки. Это может сбить с толку, так как многие команды клиента чувствительны к рабочей правке элемента, с которым он работает. Например, команда svn log используется для вывода истории изменения файла или каталога (см. «svn log»). Когда пользователь вызывает эту команду применительно к объекту рабочей копии, он ожидает увидеть полную историю этого объекта. Однако если рабочая правка объекта очень старая (из-за того, что команда svn update долго не выполнялась) будет показана история для более старой версии этого объекта.

Смешивание правок — это полезно

Если у вас очень большой проект, вы можете найти полезным время от времени принудительно «возвращать» части рабочей копии к более ранним правкам; как это делается, вы узнаете в Глава 2, Экскурсия по Subversion. Возможно, вы захотите протестировать более раннюю версию модуля, находящегося в подкаталоге или точно узнать, когда в конкретном файле появилась ошибка. Это — «машина времени», тот аспект системы управления версиями, который позволяет перемещать в истории любую часть рабочей копии вперед и назад.

Смешивание правок имеет ограничения

Несмотря на то, что в рабочей копии можно использовать смешивание правок, у этой гибкости существуют ограничения.

Во-первых, нельзя зафиксировать удаление устаревшего файла или каталога. Если в хранилище существует более новая версия элемента, попытка удаления будет отклонена для предотвращения возможности непреднамеренного уничтожения изменений о которых вы не в курсе.

Во-вторых, нельзя зафиксировать изменение метаданных для необновленного каталога. О присвоении «свойств» элементам вы узнаете в Глава 3, Профессиональное использование Subversion. Рабочая правка каталога определяет конкретный набор входящих в нее элементов и свойств, поэтому фиксация изменений свойств для устаревшего каталога может привести к уничтожению свойств, о которых вы не знаете.

Подводя итоги

В этой главе мы рассмотрели ряд фундаментальных концепций Subversion:

  • Мы ввели такие понятия как центральное хранилище, рабочая копия и массив правок хранилища.

  • Мы рассмотрели на нескольких простых примерах, как при помощи Subversion два партнера могут публиковать и получать изменения, сделанные друг другом, используя модель «копирование-изменение-слияние».

  • Мы немного поговорили о том, как Subversion отслеживает и управляет информацией в рабочей копии.

На данный момент у вас должно быть хорошее представление о том, как вообще работает Subversion. Теперь, вооруженные этими знаниями, вы готовы перейти к следующей главе, которая представляет собой подробный обзор команд и возможностей Subversion.

Глава 2. Экскурсия по Subversion

Перейдем к более тесной работе с Subversion. К тому моменту, когда вы дойдёте до конца этой главы, вы сможете выполнить практически все задачи, возникающие при повседневном использовании Subversion. Вы начнете с первоначального создания рабочей копии вашего кода и пройдете через внесение изменений и проверку этих изменений. Вы познакомитесь с тем, как внедрить изменения, сделанные другими, в вашу рабочую копию и проверить их, а также сможете решить возможные конфликты.

Обратите внимание на то, что эта глава не ставит цели быть всеобъемлющим описанием всех команд Subversion — скорее это неформальное введение в наиболее типичные задачи, решаемые с помощью Subversion. Эта глава предполагает, что вы прочитали и поняли Глава 1, Фундаментальные понятия и хорошо разобрались с общей моделью Subversion. За подробным описанием всех команд обратитесь в Глава 9, Полное справочное руководство по Subversion.

Читайте справку!

Прежде чем продолжить чтение, запомните самую главную из всех команд Subversion: svn help. Клиент Subversion с интерфейсом командной строки самодокументирован — команда svn help <subcommand> в любой момент подскажет синтаксис, описание параметров и поведения подкоманды subcommand.

Импорт

Чтобы импортировать новый проект в хранилище Subversion, воспользуйтесь командой svn import. Хотя, вероятно, это будет первым, что вы сделаете при установке сервера Subversion, впоследствии вы будете заниматься этим нечасто. Подробное описание команды «svn import» приводится далее в этой главе.

Путешествие во времени вместе с Subversion

Как уже было сказано в «Правки», правка представляет собой «снимок» хранилища в конкретный момент времени. Однако по-настоящему полезной Subversion (как и любую другую систему управления версиями) делает не то, что она просто хранит все версии файлов и каталогов. Главное заключается в том, что вы реально можете что-то делать с этими старыми версиями! А для того, чтобы совершать подобные путешествия во времени, нужен механизм идентификации этих «снимков».

Номера правок в Subversion — очень простая штука: обычные, монотонно увеличивающиеся целые числа. При создании хранилища Subversion оно начинает свое существование с правки 0, и каждая последующая фиксация увеличивает номер правки на единицу. Subversion не прячет эти номера — они являются неотъемлемой частью истории версионированной информации. К примеру, после выполнения фиксации клиент Subversion информирует вас о новом номере правки:

$ svn commit --message "Corrected number of cheese slices."
Sending        sandwich.txt
Transmitting file data .
Committed revision 3.

В будущем, в любой момент времени, если вам нужно будет сослаться на эту правку, вы сможете сделать это, обратившись к ней как к правке «3». Некоторые причины, по которым может возникнуть такая необходимость, будут приведены далее в этой главе.

Клиент для командной строки svn предлагает на выбор две опции для указания правок, которые вы хотите использовать. Более общей из них является --revision (-r), которая принимает в качестве параметра как одиночный указатель правки (-r REV), так и пару правок, разделенную двоеточием (-r REV1:REV2). Второй вариант используется для указания диапазона правок, что в свою очередь полезно для команд, сравнивающих два снимка или обрабатывающих включительно все правки между двумя указанными пределами.

В Subversion 1.4 была введена вторая опция для указания диапазона правок --change (-c). Эта опция является просто сокращением для указания диапазона правок, границами которого являются соседние целые числа. Другими словами, -cREV является тем же самым, что и -rREV-1:REV. Кроме того, так же просто можно указать и обратный диапазон, поместив дефис перед номером правки, -c -REV.

Создание рабочей копии

Как правило, работа с хранилищем Subversion начинается с создания рабочей копии проекта. При создании рабочей копии на локальной машине создается копия хранилища. Эта копия содержит HEAD (последнюю правку) хранилища, указанного вами в командной строке:

$ svn checkout http://svn.collab.net/repos/svn/trunk
A  trunk/subversion.dsw
A  trunk/svn_check.dsp
A  trunk/COMMITTERS
A  trunk/configure.in
A  trunk/IDEAS
…
Checked out revision 2499.

Хотя в приведенном примере рабочая копия создается на основе корневого каталога, вы можете легко создать рабочую копию на основе подкаталога любой степени вложенности, указав при создании рабочей копии подкаталог в URL:

$ svn checkout http://svn.collab.net/repos/svn/trunk/doc/book/tools
A  tools/readme-dblite.html
A  tools/fo-stylesheet.xsl
A  tools/svnbook.el
A  tools/dtd
A  tools/dtd/dblite.dtd
…
Checked out revision 2499.

Так как Subversion использует модель «копирование-изменение-слияние» вместо модели «блокирование-изменение-разблокирование» (см. Глава 1, Фундаментальные понятия), вы уже можете начинать вносить изменения в файлы и каталоги своей рабочей копии. Ваша рабочая копия ничем не отличается от любого другого набора файлов в вашей системе. Вы можете редактировать и менять их, перемещать, вы даже можете полностью удалить рабочую копию и забыть о ней.

[Замечание]Замечание

Несмотря на то, что рабочая копия выглядит «как и любой другой набор файлов в вашей системе», необходимо ставить Subversion в известность в том случае, если вы собираетесь что-либо реорганизовывать в рабочей копии. Если вы хотите скопировать или переместить элемент в рабочей копии, вы должны использовать команду svn copy или svn move вместо аналогичных команд операционной системы. Мы еще обсудим их в этой главе более подробно.

Исключение составляют случаи, когда вы готовы зафиксировать новый файл или каталог, либо внести изменения в один из существующих файлов или каталогов. Эти операции не требуют дополнительного уведомления сервера Subversion.

Хотя вы, конечно, можете создать рабочую копию, указав в качестве единственного аргумента URL хранилища, вы можете также указать после него каталог. Тогда ваша рабочая копия будет находиться в новом каталоге с указанным вами именем. Например:

$ svn checkout http://svn.collab.net/repos/svn/trunk subv
A  subv/subversion.dsw
A  subv/svn_check.dsp
A  subv/COMMITTERS
A  subv/configure.in
A  subv/IDEAS
…
Checked out revision 2499.

Эта команда создаст рабочую копию в каталоге с именем subv, вместо каталога trunk как мы делали раньше.

Простейший рабочий цикл

Хотя Subversion имеет множество возможностей, опций и украшательств, в каждодневной практике используются только некоторые из них. В этом разделе мы пройдемся по задачам, наиболее часто выполняемым в течение рабочего дня.

Типичный рабочий цикл выглядит примерно так:

  • Обновление рабочей копии

    • svn update

  • Внесение изменений

    • svn add

    • svn delete

    • svn copy

    • svn move

  • Анализ изменений

    • svn status

    • svn diff

    • svn revert

  • Слияние изменений, выполненных другими, с вашей рабочей копией

    • svn update

    • svn resolved

  • Фиксация изменений

    • svn commit

Обновление рабочей копии

При командной работе над проектом обновление рабочей копии необходимо для получения любых изменений, внесенных другими разработчиками проекта с момента вашего последнего обновления. Используйте svn update для синхронизации вашей рабочей копии с последней правкой в хранилище.

$ svn update
U  foo.c
U  bar.c
Updated to revision 2.

В данном случае, кто-то другой зафиксировал изменения в файлах foo.c и bar.c после вашего последнего обновления, и Subversion обновила вашу рабочую копию, включив эти изменения.

Рассмотрим поподробнее информацию, выводимую командой svn update. Когда сервер отправляет изменения в вашу рабочую копию, для каждого элемента выводится латинская буква — код, определяющий действие, выполненное Subversion для приведения вашей рабочей копии в актуальное состояние:

U foo

Файл foo был Updated — обновлен (получил изменения с сервера).

A foo

Файл или каталог foo был Added — добавлен в рабочую копию.

D foo

Файл или каталог foo был Deleted — удален из рабочей копии.

R foo

Файл или каталог foo был Replaced — заменен в рабочей копии; это значит, что foo был удален, а новый элемент с таким же именем был добавлен. Несмотря на то, что они могут иметь одинаковое имя, хранилище рассматривает их как разные объекты с отдельной историей.

G foo

Файл foo получил новые изменения из хранилища, однако ваша локальная копия в то же время содержит ваши собственные изменения. Изменения, полученные из хранилища, либо не пересекаются, либо они точно такие же как ваши локальные изменения, поэтому Subversion успешно выполнила merGed — слияние изменений хранилища с файлом.

C foo

Файл foo получил от сервера Conflicting — конфликтующие изменения. Изменения с сервера пересекаются с вашими изменениями файла. Однако это не повод для паники. Такое перекрытие просто нуждается в разрешении человеком (вами); мы обсудим эту ситуацию позднее в этой главе.

Внесение изменений в рабочую копию

Теперь вы можете приступать к делу и вносить изменения в рабочую копию. Как правило, целесообразнее всего работать отдельно по каждому частному изменению (или набору изменений), такому как реализация новой функциональной возможности, исправление ошибки и т. п. Здесь вы будете пользоваться такими командами Subversion как svn add, svn delete, svn copy и svn move. Однако, если вы просто редактируете файлы, которые уже находятся под контролем Subversion, ни одна из этих команд вам не нужна. В своей рабочей копии вы можете делать следующие изменения:

Изменения файлов

Это самый простой вид изменений. Вам не нужно сообщать Subversion о своем намерении изменить файл; просто берите и вносите изменения. Subversion сможет автоматически определить измененные файлы.

Изменения в структуре

Вы можете попросить Subversion «отметить» файлы и каталоги для удаления, добавления, копирования или перемещения. Хотя эти изменения сразу же отразятся в рабочей копии, в хранилище не произойдет ни добавления, ни удаления до тех пор, пока вы не выполните фиксацию изменений.

Для внесения изменений в файлы используйте свой текстовый редактор, текстовый процессор, графическую программу или любой другой инструмент, который вы обычно используете. Subversion обрабатывает бинарные файлы так же легко как и текстовые — и настолько же эффективно.

Рассмотрим четыре подкоманды Subversion, которые вы чаще всего будете использовать при внесении изменений в структуру (команды svn import и svn mkdir мы рассмотрим позже).

[Внимание]Внимание

Хотя вы можете редактировать файлы любыми программными средствами, не следует менять структуру рабочей копии, не проинформировав о своих действиях Subversion. Для изменения структуры рабочей копии используйте команды svn copy, svn delete и svn move, а для добавления новых файлов и каталогов под контроль версий используйте svn add.

svn add foo

Запланировать файл, каталог или символьную ссылку foo для добавления в хранилище. При следующей фиксации foo станет компонентом своего родительского каталога. Обратите внимание на то, что если foo является каталогом, то все содержащееся в foo будет запланировано для добавления. Чтобы добавить отдельно только сам каталог foo, воспользуйтесь параметром --non-recursive (-N).

svn delete foo

Запланировать удаление из хранилища файла, каталога или символьной ссылки foo. Если foo является файлом или ссылкой, он сразу же удаляется из вашей рабочей копии. Если foo является каталогом, он не удаляется, но Subversion запланирует его удаление. foo будет удален из рабочей копии и хранилища при фиксации изменений.[8]

svn copy foo bar

Создать новый элемент bar как копию foo. bar будет автоматически запланирован для добавления. Когда при следующей фиксации bar будет добавлен в хранилище, в его истории будет отмечено копирование (то, что первоисточником является foo). svn copy не создает промежуточных каталогов.

svn move foo bar

Эта команда полностью аналогична выполнению svn copy foo bar; svn delete foo. Поэтому, bar будет запланирован для добавления как копия foo, а foo будет запланирован для удаления. svn move не создает промежуточных каталогов.

Анализ изменений

После внесения изменений вы должны зафиксировать их в хранилище, но перед этим было бы неплохо посмотреть, что же, собственно, вы изменили. Проанализировав перед фиксацией свои изменения, вы сможете составить более аккуратное лог-сообщение. Кроме того, вы можете обнаружить, что изменили файл непреднамеренно, что позволит еще до фиксации вернуть файл к предыдущему состоянию. К тому же, это хорошая возможность пересмотреть и проверить изменения перед их публикацией. Чтобы увидеть все сделанные изменения, вы можете воспользоваться svn status, svn diff и svn revert. Первые две команды вы можете использовать для того, чтобы найти измененные файлы рабочей копии, а затем, при помощи третьей, отменить некоторые (или все) изменения.

Subversion была оптимизирована для решения такой задачи и способна выполнять множество действий без обращения к хранилищу. В частности, рабочая копия содержит в .svn-области скрытую кэшированую «нетронутую» копию каждого версионированного файла. За счет этого Subversion может быстро показать, как изменились ваши рабочие файлы или даже предоставить, не связываясь с хранилищем, возможность откатить изменения.

svn status

Наверное, команду svn status вы будете использовать чаще, чем любую другую команду Subversion.

При запуске svn status без параметров из корневого каталога рабочей копии будут найдены все сделанные вами изменения файлов и структуры. Ниже приведены примеры различных буквенных кодов, возвращаемых svn status. (Обратите внимание, что текст, следующий за #, на самом деле svn status не печатает.)

  L     some_dir            # svn оставила блокировку в .svn-области для some_dir
M       bar.c               # содержимое bar.c имеет локальные изменения
 M      baz.c               # в baz.c есть изменения в свойствах, а в содержимом нет
X       3rd_party           # каталог является частью внешней зависимости
?       foo.o               # svn не управляет foo.o
!       some_dir            # svn управляет этим элементом, но он отсутствует или поврежден
~       qux                 # элемент версионировался как файл/каталог/ссылка, но тип был изменен
I       .screenrc           # svn не управляет этим элементом и настроена на его игнорирование
A  +    moved_dir           # добавлен с историей своего происхождения
M  +    moved_dir/README    # добавлен с историей и имеет локальные изменения
D       stuff/fish.c        # файл запланирован для удаления
A       stuff/loot/bloo.h   # файл запланирован для добавления
C       stuff/loot/lump.c   # файл имеет текстовый конфликт с момента обновления
 C      stuff/loot/glub.c   # файл имеет конфликт в свойствах с момента обновления
R       xyz.c               # файл запланирован для замены
    S   stuff/squawk        # файл или каталог были переключены на ветку
     K  dog.jpg             # файл заблокирован локально; присутствует маркер блокирования
     O  cat.jpg             # файл заблокирован в хранилище другим пользователем
     B  bird.jpg            # файл заблокирован локально, но блокировка была нарушена
     T  fish.jpg            # файл заблокирован локально, но блокировка была снята

svn status печатает пять колонок букв, затем несколько пробелов, затем имя файла или каталога. Первая колонка показывает статус файла или каталога и/или ее содержимого. При этом используются следующие коды:

A item

Файл, каталог или символьная ссылка item был запланирован для добавления в хранилище.

C item

Файл item находится в состоянии конфликта. Это означает, что изменения, полученные от сервера, при обновлении пересекаются с локальными изменениями, имеющимися в рабочей копии. Перед фиксацией изменений вам необходимо разрешить этот конфликт.

D item

Файл, каталог или символьная ссылка item запланирован для удаления из хранилища.

M item

Содержимое файла item было изменено.

R item

Файл, каталог или символьная ссылка запланирован для замены item в хранилище. Это значит, что сначала объект был удален, а затем другой объект с таким же именем был добавлен, все в одной правке.

X item

Каталог item не версионирован, но относится к внешним зависимостям Subversion. Более подробно о внешних зависимостях см. в «Внешние зависимости».

? item

Файл, каталог или символьная ссылка не находится под контролем версий. Вы можете убрать знаки вопроса либо воспользовавшись параметром --quiet (-q) команды svn status, либо установив свойство svn:ignore родительского каталога. Дополнительную информацию об игнорировании файлов см. в «Пропуск неверсионированных элементов».

! item

Файл, каталог или символьная ссылка item находится под контролем версий, но отсутствует в рабочей копии или поврежден. Элемент может отсутствовать, если он был удален без использования команд Subversion. В частном случае, каталог может оказаться поврежденным, если вы прервали создание рабочей копии или обновление. Быстрый запуск svn update заново вытащит файл или каталог из хранилища, либо svn revert file восстановит отсутствующий файл.

~ item

Файл, каталог или символьная ссылка item в хранилище является объектом одного типа, а то, что на самом деле находится в рабочей копии, является чем-то другим. Например, в хранилище Subversion может иметь файл, а вы удалили файл и создали на его месте каталог, не используя для этого команды svn delete или svn add.

I item

Файл, каталог или символьная ссылка item находится под контролем версий, и Subversion настроена на его игнорирование при операциях svn add, svn import и svn status. Дополнительную информацию об игнорированных файлах см. в «Пропуск неверсионированных элементов». Обратите внимание на то, что этот символ появляется при использовании опции --no-ignore для svn status — иначе файл игнорируется и не показывается вообще!

Вторая колонка показывает статус свойств файлов и каталогов (подробнее о свойствах см. в «Свойства»). Если во второй колонке показывается M, свойства были изменены. Если в этой колонке показывается C, то это означает, что свойства файла находятся в состоянии конфликта, который должен быть разрешен до фиксации изменений в хранилище. Во всех других случаях будет выведен пробел.

Третья колонка может содержать только пробел или L, это значит, что у каталога заблокирована рабочая область .svn. Вы увидите L, если запустите svn status в каталоге, в котором выполняется svn commit — например, когда вы редактируете лог-сообщение.

Четвертая колонка может содержать только пробел или +, это означает, что элемент был запланирован для «добавления с историей». Это может быть файл или корень скопированного каталога. + означает, что элемент является частью поддерева, запланированного для «добавления с историей», т. е. один из родительских каталогов был скопирован, и этот элемент просто его часть. M  + означает, что элемент является частью поддерева, запланированного для «добавления с историей», и имеет локальные изменения. При выполнении фиксации вначале будет «добавлен с историей» родительский каталог, что означает автоматическое наличие файла в копии. После этого в копию будут загружены локальные изменения.

Пятая колонка может содержать только пробел или S. Это означает, что файл или каталог был переключен с пути остальной рабочей копии на ветку (используя svn switch).

Шестая колонка показывает информацию о блокировках, которые подробно рассмотрены в «Locking». (Это не те блокировки, которые отмечаются L в третьей колонке; см. Three meanings of «lock»)

Если вы укажете конкретный путь для svn status, то получите информацию только об этом элементе:

$ svn status stuff/fish.c
D      stuff/fish.c

Кроме того, svn status имеет параметр --verbose (-v), который покажет вам статус каждого элемента в рабочей копии, даже если он не менялся:

$ svn status --verbose
M               44        23    sally     README
                44        30    sally     INSTALL
M               44        20    harry     bar.c
                44        18    ira       stuff
                44        35    harry     stuff/trout.c
D               44        19    ira       stuff/fish.c
                44        21    sally     stuff/things
A                0         ?     ?        stuff/things/bloo.h
                44        36    harry     stuff/things/gloo.c

Это «длинная форма» представления вывода svn status. Первая колонка осталась та же самая, а вот вторая колонка показывает рабочую правку элемента. Третья и четвертая колонки показывают правку, в которой элемент последний раз изменялся и автора этих изменений.

Ни один из указанных выше вызовов svn status не обращается к хранилищу, они работают только локально, сравнивая метаданные каталога .svn с рабочей копией. Отметим, что есть параметр --show-updates (-u), указывающий на соединение с хранилищем и добавляющий информацию об устаревании элементов:

$ svn status --show-updates --verbose
M      *        44        23    sally     README
M               44        20    harry     bar.c
       *        44        35    harry     stuff/trout.c
D               44        19    ira       stuff/fish.c
A                0         ?     ?        stuff/things/bloo.h
Status against revision:   46

Обратите внимание на две звездочки: если сейчас вы запустите svn update вы получите изменения для README и trout.c. Это очень полезная информация — перед фиксацией вам необходимо обновить и получить изменения с сервера для README, или же хранилище отклонит вашу фиксацию как не соответствующую актуальному состоянию. (Подробнее об этом чуть позже.)

svn diff

Еще один механизм для анализа изменений — это команда svn diff. Запустив svn diff без аргументов, можно увидеть, какие именно изменения вы внесли, в результате будут выведены изменения файлов в едином формате представления различий:[9]

$ svn diff
Index: bar.c
===================================================================
--- bar.c (revision 3)
+++ bar.c (working copy)
@@ -1,7 +1,12 @@
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <stdio.h>

 int main(void) {
-  printf("Sixty-four slices of American Cheese...\n");
+  printf("Sixty-five slices of American Cheese...\n");
 return 0;
 }

Index: README
===================================================================
--- README  (revision 3)
+++ README  (working copy)
@@ -193,3 +193,4 @@
+Note to self:  pick up laundry.

Index: stuff/fish.c
===================================================================
--- stuff/fish.c  (revision 1)
+++ stuff/fish.c  (working copy)
-Welcome to the file known as 'fish'.
-Information on fish will be here soon.

Index: stuff/things/bloo.h
===================================================================
--- stuff/things/bloo.h (revision 8)
+++ stuff/things/bloo.h (working copy)
+Here is a new file to describe
+things about bloo.

Команда svn diff формирует свой вывод, сравнивая ваши рабочие файлы с кэшированными «нетронутыми» копиями из .svn. Весь текст запланированных для добавления файлов показывается как добавленный, а весь текст запланированных для удаления файлов показывается как удаленный.

Вывод происходит в едином формате представления различий. При этом удаленные строки предваряются знаком -, а добавленные — знаком +. Кроме этого svn diff печатает имена файлов и информацию о сдвиге информации, которая необходима программе patch, и, следовательно, вы можете получать «патчи», перенаправив вывод различий в файл:

$ svn diff > patchfile

Вы можете, например, отправить по электронной почте файл патча другому разработчику для ознакомления или тестирования перед фиксацией.

svn revert

Теперь предположим, что, просмотрев вывод команды diff, вы обнаружили, что изменения в README ошибочны — к примеру, потому, что в своем редакторе вы случайно набрали текст, предназначавшийся для другого файла.

В такой ситуации как нельзя кстати окажется команда svn revert.

$ svn revert README
Reverted 'README'

Subversion возвращает файл в состояние, предшествующее модификации, путем замены файла его кэшированной «первоначальной» копией из .svn-области. Кроме того, обратите внимание, что svn revert может отменить любые запланированные операции — например, вы можете прийти к решению всё-таки не добавлять новый файл:

$ svn status foo
?      foo

$ svn add foo
A         foo

$ svn revert foo
Reverted 'foo'

$ svn status foo
?      foo
[Замечание]Замечание

svn revert ITEM будет иметь точно такой же эффект, как и удаление ITEM из вашей рабочей копии, а затем выполнение svn update -r BASE ITEM. Однако, если вы отменяете изменения для файла, svn revert будет иметь одно значительное отличие — для восстановления файла не происходит соединения с хранилищем.

Или, допустим, вы ошибочно удалили файл из-под контроля версий:

$ svn status README
       README

$ svn delete README
D         README

$ svn revert README
Reverted 'README'

$ svn status README
       README

Разрешение конфликтов (при слиянии с чужими изменениями)

Мы уже видели, как svn status -u может предупредить о конфликтах. Предположим, вы запустили svn update и увидели кое-что интересное:

$ svn update
U  INSTALL
G  README
C  bar.c
Updated to revision 46.

Коды U и G интереса не представляют; эти файлы без проблем поглотили изменения из хранилища. Файлы, отмеченные U, локальных изменений не содержат и были Updated — обновлены изменениями из хранилища. Отмеченные G были merGed — слиты, это значит, что файл имел локальные изменения, но изменения, пришедшие из хранилища, не перекрываются с локальными изменениями.

А вот файлы, отмеченные C, имеют конфликт. Это значит, что изменения с сервера пересеклись с вашими личными, и теперь вам нужно вручную сделать между ними выбор.

Всякий раз, когда возникает конфликт, в его обнаружении и разрешении вам, как правило, помогают три вещи:

  • Subversion печатает C во время обновления и запоминает, что файл в состоянии конфликта.

  • Если Subversion считает, что тип файла допускает слияние изменений, она включает в него маркеры конфликта — специальные текстовые строки, отделяющие «стороны» конфликта — чтобы визуально показать пересекающиеся области. (Subversion использует свойство svn:mime-type для определения возможности контекстного, построчного слияния. См. «Тип содержимого файла» для более подробной информации.)

  • Для каждого конфликтного файла Subversion добавляет в рабочую копию до трех не версионированных дополнительных файлов:

    filename.mine

    Это ваш файл в том виде, в каком он присутствовал в рабочей копии до обновления — без маркеров конфликта. Этот файл содержит в себе только ваши изменения и ничего больше. (Если Subversion решает, что файл не пригоден для слияния изменений, то файл .mine не создается, так как он будет идентичным рабочему файлу.)

    filename.rOLDREV

    Это файл правки BASE, где BASE — правка, которая была до обновления рабочей копии. Иными словами, это файл, который был у вас до внесения изменений.

    filename.rNEWREV

    Это файл, который ваш Subversion-клиент получил с сервера при обновлении рабочей копии. Этот файл соответствует правке HEAD хранилища.

    Здесь OLDREV — это номер правки файла в каталоге .svn, а NEWREV — номер правки HEAD хранилища.

Например, Салли внесла изменения в файл sandwich.txt из хранилища. Одновременно Гарри изменил файл в своей рабочей копии и зафиксировал его. Салли обновляет свою рабочую копию перед фиксацией и получает конфликт:

$ svn update
C  sandwich.txt
Updated to revision 2.
$ ls -1
sandwich.txt
sandwich.txt.mine
sandwich.txt.r1
sandwich.txt.r2

Теперь Subversion не позволит зафиксировать файл sandwich.txt, пока не будут удалены три временных файла.

$ svn commit --message "Add a few more things"
svn: Commit failed (details follow):
svn: Aborting commit: '/home/sally/svn-work/sandwich.txt' remains in conflict

Для разрешения конфликта у вас есть три варианта:

  • Объединить конфликтующий текст «вручную» (путем анализа и редактирования маркеров конфликта в файле).

  • Скопировать один из временных файлов поверх своего рабочего файла.

  • Выполнить svn revert <filename> для отказа от всех ваших локальных изменений.

После разрешения конфликта вам нужно известить об этом Subversion, выполнив svn resolved. Эта команда удалит три временных файла, и Subversion больше не будет считать, что файл находится в состоянии конфликта. [10]

$ svn resolved sandwich.txt
Resolved conflicted state of 'sandwich.txt'

Слияние конфликтов вручную

Слияние конфликтов вручную может показаться пугающим, когда вы делаете это в первый раз, но после небольшой практики станет для вас таким же простым, как езда на велосипеде.

Возьмем пример. По недоразумению вы и ваш соразработчик Салли одновременно редактируете файл sandwich.txt. Салли зафиксировала свои изменения, и поэтому при обновлении своей рабочей копии вы получите конфликт, для разрешения которого вам необходимо отредактировать sandwich.txt. Для начала посмотрим на файл:

$ cat sandwich.txt
Top piece of bread
Mayonnaise
Lettuce
Tomato
Provolone
<<<<<<< .mine
Salami
Mortadella
Prosciutto
=======
Sauerkraut
Grilled Chicken
>>>>>>> .r2
Creole Mustard
Bottom piece of bread

Строки, начинающиеся со знаком «меньше чем», «равно» и «больше чем», являются маркерами конфликта. Перед следующей фиксацией вам нужно будет убедиться, что они удалены из файла. Текст между первыми двумя маркерами состоит из ваших изменений в конфликтующей области:

<<<<<<< .mine
Salami
Mortadella
Prosciutto
=======

Текст между вторым и третьим маркером конфликта — это текст из фиксации Салли:

=======
Sauerkraut
Grilled Chicken
>>>>>>> .r2

Скорее всего вы не захотите просто удалить маркеры конфликта и изменения, сделанные Салли, — она ужасно удивится, когда дойдет до сандвича и не увидит того, что ожидала. Это как раз тот случай, когда вы снимаете трубку или пересекаете офис и объясняете Салли, что не можете получить из итальянского гастронома квашеную капусту. [11] После того, как вы согласуете изменения, нужно будет выполнить фиксацию. Для этого отредактируйте ваш файл и удалите маркеры конфликта.

Top piece of bread
Mayonnaise
Lettuce
Tomato
Provolone
Salami
Mortadella
Prosciutto
Creole Mustard
Bottom piece of bread

Теперь выполните svn resolved, и вы готовы к фиксации изменений:

$ svn resolved sandwich.txt
$ svn commit -m "Go ahead and use my sandwich, discarding Sally's edits."

Обратите внимание на то, что svn resolved, в отличие от большинства команд, с которыми мы имели дело в этой главе, требует аргумент. В любом случае будьте осторожны и выполняйте svn resolved тогда, когда вы убеждены, что исправили конфликт в файле. После того как временные файлы будут удалены, Subversion позволит вам зафиксировать файл, даже если он все еще содержит маркеры конфликта.

Если вы испытываете затруднения при редактировании конфликтующего файла, всегда можно обратиться к тем трем файлам, которые Subversion создает в рабочей копии — включая ваш файл в том виде, в каком он был до обновления. Для анализа этих трех файлов вы даже можете воспользоваться программами для слияния изменений от сторонних разработчиков.

Копирование файла поверх вашего рабочего файла

Если вы получили конфликт и решили отказаться от своих изменений, вы можете просто скопировать один из временных файлов, созданных Subversion, поверх файла в рабочей копии:

$ svn update
C  sandwich.txt
Updated to revision 2.
$ ls sandwich.*
sandwich.txt  sandwich.txt.mine  sandwich.txt.r2  sandwich.txt.r1
$ cp sandwich.txt.r2 sandwich.txt
$ svn resolved sandwich.txt

Использование svn revert

Если вы получили конфликт и, проанализировав, решили отбросить изменения и начать сначала, просто отмените ваши изменения:

$ svn revert sandwich.txt
Reverted 'sandwich.txt'
$ ls sandwich.*
sandwich.txt

Обратите внимание, что при возврате конфликтующего файла к исходному состоянию вам не нужно выполнять svn resolved.

Фиксация изменений

Наконец-то! Вы закончили с редактированием, слили все изменения с сервера и готовы к тому, чтобы зафиксировать их в хранилище.

Команда svn commit отправляет все ваши изменения в хранилище. При фиксации изменений необходимо описать ваши изменения в тексте лог-сообщения. Лог-сообщение будет присоединено к созданной правке. Если ваше лог-сообщение короткое, вы можете указать его в командной строке, используя опцию --message (или -m):

$ svn commit --message "Corrected number of cheese slices."
Sending        sandwich.txt
Transmitting file data .
Committed revision 3.

Однако, если вы заранее составляли лог-сообщение в процессе работы, можно попросить Subversion взять его из файла, передав имя этого файла в параметре --file:

$ svn commit --file logmsg
Sending        sandwich.txt
Transmitting file data .
Committed revision 4.

Если вы не укажете ни опции --message, ни опции --file, для составления лог сообщения Subversion автоматически запустит ваш любимый редактор (см. editor-cmd в разделе «Config»).

[Подсказка]Подсказка

Если, набирая сообщение в редакторе, вы решите отменить фиксацию, то можете просто выйти из редактора без сохранения изменений. Если вы уже сохранили сообщение, просто удалите текст и выполните сохранение еще раз.

$ svn commit
Waiting for Emacs...Done

Log message unchanged or not specified
a)bort, c)ontinue, e)dit
a
$

Хранилище, в общем-то, не знает ничего о смысле ваших изменений; оно только контролирует, чтобы никто не изменил те же файлы, что и вы. Если это все-таки случилось, вся фиксация будет отклонена, и вы получите сообщение о том, что один или несколько файлов устарели:

$ svn commit --message "Add another rule"
Sending        rules.txt
svn: Commit failed (details follow):
svn: Out of date: 'rules.txt' in transaction 'g'

В таком случае вам нужно выполнить svn update, разобраться со всеми слияниями и конфликтами и попытаться выполнить фиксацию снова.

Мы рассмотрели простейший рабочий цикл использования Subversion. В Subversion существует много других возможностей, которые вы можете применять для управления рабочей копией и хранилищем; но очень многое можно сделать, используя исключительно команды, рассмотренные в этой главе.

Анализ истории

Как мы уже говорили, хранилище похоже на машину времени. Оно хранит запись о любом когда-либо зафиксированном изменении и позволяет вам просмотреть его хронологию путем анализа предыдущих версий файлов и каталогов, а также присоединенных к ним метаданных. Одной командой Subversion вы можете создать рабочую копию (или восстановить существующую) точно в том виде, в каком она была в любой момент времени или после фиксации правки с указанным номером. Однако, иногда вам просто нужно заглянуть в прошлое, но не возвращаться в него.

Существует несколько команд, которые могут предоставить вам хронологическую информацию из хранилища:

svn log

Показывает вам развернутую информацию: лог-сообщения, присоединенные к правкам, с указанием даты изменений и их авторов, а также изменения путей к файлам в каждой правке.

svn diff

Показывает подробности того, как изменился файл с течением времени.

svn cat

Эта команда используется для получения отдельного файла в том виде, в каком он был в конкретной ревизии и вывода его на экран.

svn list

Показывает список файлов в каталоге для любой указанной правки.

svn log

Для того, чтобы найти информацию о хронологии файла или каталога, воспользуйтесь командой svn log. svn log показывает информацию о том, кто изменял файл или каталог, в какой правке это произошло, дату и время правки и присоединенное к фиксации лог-сообщение, если оно доступно.

$ svn log
------------------------------------------------------------------------
r3 | sally | Mon, 15 Jul 2002 18:03:46 -0500 | 1 line

Added include lines and corrected # of cheese slices.
------------------------------------------------------------------------
r2 | harry | Mon, 15 Jul 2002 17:47:57 -0500 | 1 line

Added main() methods.
------------------------------------------------------------------------
r1 | sally | Mon, 15 Jul 2002 17:40:08 -0500 | 1 line

Initial import
------------------------------------------------------------------------

Обратите внимание на то, что по умолчанию лог сообщения выводятся в обратном хронологическом порядке. Если вам нужно увидеть другой диапазон правок в заранее определенном порядке или только одну правку, укажите параметр --revision (-r):

$ svn log --revision 5:19    # shows logs 5 through 19 in chronological order

$ svn log -r 19:5            # shows logs 5 through 19 in reverse order

$ svn log -r 8               # shows log for revision 8

Кроме того, можно проанализировать историю лог-сообщений отдельного файла или каталога. Например:

$ svn log foo.c
…
$ svn log http://foo.com/svn/trunk/code/foo.c
…

В результате будут показаны лог-сообщения только для тех правок, в которых изменялся рабочий файл (или URL).

Если вам нужно еще больше информации о файле или каталоге, то для svn log есть параметр --verbose (-v). Так как Subversion позволяет перемещать и копировать файлы и каталоги, важно отслеживать изменения путей в файловой системе. Поэтому в режиме расширенного вывода svn log включает перечень измененных в правке путей:

$ svn log -r 8 -v
------------------------------------------------------------------------
r8 | sally | 2002-07-14 08:15:29 -0500 | 1 line
Changed paths:
M /trunk/code/foo.c
M /trunk/code/bar.h
A /trunk/code/doc/README

Frozzled the sub-space winch.

------------------------------------------------------------------------

Кроме того, svn log имеет параметр --quiet (-q), сокращающий лог сообщение. При его объединении с --verbose выдаются только имена измененных файлов.

svn diff

Ранее мы уже познакомились с svn diff — эта команда показывает различия файла в едином формате представления различий; она используется для того, что бы показать локальные изменения, внесенные в рабочую копию, перед их фиксацией в хранилище.

Вообще, существует три возможных варианта использования svn diff:

  • Анализ локальных изменений

  • Сравнение рабочей копии с хранилищем

  • Сравнение хранилища с хранилищем

Анализ локальных изменений

Как мы уже знаем, запуск svn diff без параметров сравнивает рабочие файлы с кэшированными в .svn «первоначальными» копиями:

$ svn diff
Index: rules.txt
===================================================================
--- rules.txt (revision 3)
+++ rules.txt (working copy)
@@ -1,4 +1,5 @@
 Be kind to others
 Freedom = Responsibility
 Everything in moderation
-Chew with your mouth open
+Chew with your mouth closed
+Listen when others are speaking
$

Сравнение рабочей копии с хранилищем

Если в --revision (-r) указан один номер, то рабочая копия сравнивается с указанной правкой хранилища.

$ svn diff --revision 3 rules.txt
Index: rules.txt
===================================================================
--- rules.txt (revision 3)
+++ rules.txt (working copy)
@@ -1,4 +1,5 @@
 Be kind to others
 Freedom = Responsibility
 Everything in moderation
-Chew with your mouth open
+Chew with your mouth closed
+Listen when others are speaking
$

Сравнение хранилища с хранилищем

Если через --revision (-r) передаются две правки, разделенные двоеточием, то непосредственно сравниваются две правки.

$ svn diff --revision 2:3 rules.txt
Index: rules.txt
===================================================================
--- rules.txt (revision 2)
+++ rules.txt (revision 3)
@@ -1,4 +1,4 @@
 Be kind to others
-Freedom = Chocolate Ice Cream
+Freedom = Responsibility
 Everything in moderation
 Chew with your mouth open
$

svn diff можно использовать не только для сравнения файлов, присутствующих в рабочей копии. Если вы укажете в качестве аргумента URL, то сможете анализировать различия между элементами, даже не имея рабочей копии. Это полезно в случае, если вы хотите проверить изменения файла тогда, когда у вас нет его рабочей копии на локальной машине:

$ svn diff --revision 4:5 http://svn.red-bean.com/repos/example/trunk/text/rules.txt
…
$

svn cat

Если вы хотите проанализировать ранние версии файла, а не различия между двумя файлами, можно воспользоваться svn cat:

$ svn cat --revision 2 rules.txt
Be kind to others
Freedom = Chocolate Ice Cream
Everything in moderation
Chew with your mouth open
$

Или вы можете перенаправить вывод прямо в файл:

$ svn cat --revision 2 rules.txt > rules.txt.v2
$

Наверное, вам интересно, почему для замены файла старой правкой мы не воспользовались svn update --revision. Есть несколько причин, по которым нам оказалось предпочтительнее воспользоваться svn cat.

Во-первых, вы могли захотеть увидеть различия между двумя правками одного файла, используя внешнюю программу просмотра различий (возможно, с графическим интерфейсом или работающую с файлами таких форматов, для которых единый формат представления различий не пригоден). В этом случае вам нужно вытащить копию старой правки, перенаправить ее в файл и передать этот файл вместе с файлом рабочей копии внешней программе просмотра различий.

Во-вторых, иногда проще посмотреть полную старую версию файла чем различия между ним и его другой правкой.

svn list

Команда svn list показывает содержимое каталога в хранилище, при этом не закачивая его на локальную машину:

$ svn list http://svn.collab.net/repos/svn
README
branches/
clients/
tags/
trunk/

Если вам нужна более подробная информация, воспользуйтесь флагом --verbose (-v), и вы увидете что-то подобное:

$ svn list --verbose http://svn.collab.net/repos/svn
   2755 harry          1331 Jul 28 02:07 README
   2773 sally               Jul 29 15:07 branches/
   2769 sally               Jul 29 12:07 clients/
   2698 harry               Jul 24 18:07 tags/
   2785 sally               Jul 29 19:07 trunk/

Колонки показывают правку, в которой файл или каталог последний раз изменялись, имя пользователя, вносившего изменения, размер (если это файл), дату последнего изменения и имя элемента.

Заключительное слово об истории

В дополнение ко всем упомянутым выше командам, можно воспользоваться svn update и svn checkout с параметром --revision, чтобы переместить рабочую копию «назад во времени»[12]:

$ svn checkout --revision 1729 # Checks out a new working copy at r1729
…
$ svn update --revision 1729 # Updates an existing working copy to r1729
…

Другие полезные команды

Хотя эти команды используются не так часто, как рассмотренные ранее в этой главе, иногда они вам все-таки пригодятся.

svn cleanup

Когда Subversion изменяет рабочую копию (или любую информацию в области .svn), она пытается делать это как можно более осторожно. Перед изменением рабочей копии Subversion записывает свои намерения в лог-файл. Затем для выполнения запрошенных изменений она выполняет команды из лог-файла, устанавливая блокировку той части рабочей копии, с которой работает — это делается для предотвращения работы других Subversion-клиентов с той рабочей копией, которая находится в промежуточном состоянии. После выполнения запрошеных действий Subversion удаляет лог файл. Архитектурно это напоминает журналируемую файловую систему. Если работа Subversion была прервана (в результате того, что процесс был убит или, например, из-за машинного сбоя), лог файлы остаются на диске. Перезапустив выполнение лог файлов, Subversion может завершить предварительно начатые операции, и рабочая копия снова вернется в согласованное состояние.

Именно это, собственно, и делает svn cleanup: она ищет в рабочей копии и выполняет незавершенные лог-файлы, удаляя по ходу выполнения блокировки в рабочей копии. Если Subversion когда-нибудь говорила вам о том, что часть рабочей копии «заблокирована», то вам нужно запустить эту команду. Кроме того, svn status покажет для заблокированных элементов букву L:

$ svn status
  L    somedir
M      somedir/foo.c

$ svn cleanup
$ svn status
M      somedir/foo.c

Не путайте эти блокировки рабочей копии с обычными блокировками, которые устанавливают пользователи Subversion, использующие модель конкурентного управления версиями «блокировка-изменение-разблокировка»; за более подробным определением обратитесь к Three meanings of «lock»

svn import

Команда svn import — это быстрый способ скопировать неверсионированное дерево файлов в хранилище, cоздавая при необходимости подкаталоги.

$ svnadmin create /usr/local/svn/newrepos
$ svn import mytree file:///usr/local/svn/newrepos/some/project \
             -m "Initial import"
Adding         mytree/foo.c
Adding         mytree/bar.c
Adding         mytree/subdir
Adding         mytree/subdir/quux.h

Committed revision 1.

В предыдущем примере выполняется копирование содержимого каталога mytree в каталог some/project хранилища:

$ svn list file:///usr/local/svn/newrepos/some/project
bar.c
foo.c
subdir/

Обратите внимание на то, что после завершения импорта оригинальное дерево файлов не конвертируется в рабочую копию. Чтобы начать работать, вам необходимо создать новую рабочую копию (svn checkout) дерева файлов.

Подводя итоги

К настоящему моменту мы рассмотрели большинство команд клиента Subversion, за исключением тех, которые предназначены для работы с ветвлениями и слияниями (см. Глава 4, Ветвление и слияние) и свойствами (см. «Свойства»). Кроме этого, найдите время просмотреть Глава 9, Полное справочное руководство по Subversion, чтобы получить представление обо всем многообразии имеющихся у Subversion команд — и о том, как с их помощью вы можете упростить свою работу.




[8] Конечно, ничего полностью из хранилища не удаляется — удаление касается только HEAD правки хранилища. Вы можете восстановить все, что вы удалили, создав рабочую копию (или обновив существующую) на основе более ранней правки, чем та, в которой вы удалили элемент.

[9] Subversion использует свой внутренний механизм обнаружения различий, который по умолчанию использует для вывода единый формат представления различий. Если вы хотите получить различия в другом формате, укажите внешнюю программу поиска различий, используя --diff-cmd и передав любые аргументы, которые вы хотите использовать, в параметре --extensions. Например, для того чтобы увидеть контекстные локальные изменения в файле foo.c, игнорируя изменения в числе пробелов, запустите svn diff --diff-cmd /usr/bin/diff --extensions '-bc' foo.c.

[10] Вы можете удалить временные файлы самостоятельно — но стоит ли это делать, если можно переложить эту работу на Subversion? Нам так не кажется.

[11] А если вы их об этом попросите, они лишь посмеются над вами.

[12] Видите? Мы же говорили вам, что Subversion — это машина времени.

Глава 3. Профессиональное использование Subversion

Если вы читали эту книгу последовательно, глава за главой, то к настоящему моменту должны иметь достаточно знаний для выполнения с помощью Subversion-клиента типовых операций управления версиями. Вы умеете создавать рабочую копию, знаете, как с помощью команд svn commit и svn update отправлять и получать изменения. Возможно, у вас уже даже выработался рефлекс бессознательного запуска svn status. Вы готовы применять Subversion в большинстве типовых ситуаций.

Однако возможности Subversion не ограничиваются «типовыми операциями управления версиями». В Subversion реализован функционал, выходящий за пределы простого обмена различиями с центральным хранилищем.

В этой главе рассказывается о тех возможностях Subversion, которые, несмотря на свою важность, не используются в типичном ежедневном рабочем цикле. Чтобы читать дальше эту главу, необходимо хорошо представлять себе механизмы версионированния файлов и каталогов в Subversion. Если вы этого не знаете, прочитайте сначала Глава 1, Фундаментальные понятия и Глава 2, Экскурсия по Subversion. Овладев основами и изучив приемы, рассмотренные в этой главе, вы станете действительно продвинутым пользователем Subversion!

Способы обозначения правок

Как вы уже заметили в «Путешествие во времени вместе с Subversion», номера правок в Subversion — это не более чем целые числа, монотонно возрастающие при каждой фиксации изменений версионированных данных. Пройдет совсем немного времени, и вы уже не сможете точно вспомнить, что произошло в каждой из правок. К счастью, типовая практика работы с Subversion не часто предполагает указание вами конкретных правок, к которым следует применить ту или иную операцию. Для операций, которые требуют обязательной ссылки на конкретную правку, чаще всего указывают номер правки, который известен из сообщения о фиксации, вывода некоторых других операций Subversion или из каких-либо других обстоятельств, которые могли бы дать этот конкретный номер.

Однако, иногда у вас может возникнуть необходимость сослаться на момент времени, для которого у вас уже не осталось в памяти или в записях точного номера правки. Поэтому, кроме целочисленных номеров правок, svn позволяет использовать дополнительные формы обозначения правок — ключевые слова и даты правок.

[Замечание]Замечание

При указании диапазонов правок можно смешивать различные способы их обозначения, допустимые в Subversion. Например, вы можете использовать -r REV1:REV2, где REV1 — это ключевое слово, а REV2 — обычный номер правки, или где REV1 — дата, а REV2 — ключевое слово, и так далее. Каждое обозначение правки будет интерпретироваться независимо друг от друга, поэтому вы можете указать по другую сторону от двоеточия что угодно.

Ключевые слова правок

Клиент Subversion понимает ряд ключевых слов. Эти ключевые слова можно использовать вместо целочисленных аргументов опции --revision, при этом Subversion переведет их в конкретные номера правок:

HEAD

Последняя (или «самая новая») правка хранилища

BASE

Номер правки элемента в рабочей копии. Если элемент редактировался, то «BASE версия» соответствует тому, как выглядел этот элемент до внесения локальных изменений.

COMMITTED

Правка, в которой элемент последний раз изменялся (предшествующая либо равная BASE).

PREV

Правка, непосредственно предшествующая той правке, в которой элемент был последний раз изменен. (То есть, фактически, COMMITTED - 1.)

Из данного описания можно сделать очевидный вывод о том, что ключевые слова PREV, BASE, и COMMITTED могут использоваться только при ссылках на пути в рабочей копии; они не применимы к URL-адресам хранилища. Напротив, ключевое слово HEAD можно использовать совместно с обоими типами путей.

Ниже приведено несколько примеров использования ключевых слов правок:

$ svn diff --revision PREV:COMMITTED foo.c

# показать последнее изменение, зафиксированное для foo.c

$ svn log --revision HEAD

# показать лог-сообщение для последней фиксации в хранилище

$ svn diff --revision HEAD

# сравнить ваш рабочий файл (с учетом локальных изменений)
# с последней правкой в хранилище

$ svn diff --revision BASE:HEAD foo.c

# сравнить ваш «исходный» foo.c (без учета локальных
# изменений) с последней версией в хранилище

$ svn log --revision BASE:HEAD

# показать все логи фиксаций со времени вашего последнего обновления

$ svn update --revision PREV foo.c

# отменить последние изменения в foo.c, понизив рабочую правку foo.c
      
$ svn diff -r BASE:14 foo.c

# сравнить неизмененную версию foo.c и версию foo.c в правке 14

Даты правок

Номера правок не несут никакой информации об окружающем мире за пределами системы управления версиями, тогда как вам иногда требуется сопоставить момент времени в реальной жизни с моментом в истории версий. Чтобы помочь вам в этом, опция --revision допускает указание даты, которую заключают в фигурные скобки ({ и }). Subversion принимает дату и время в формате, соответствующем стандарту ISO-8601, а также в некоторых других. Ниже приведено несколько примеров. (Не забывайте брать в кавычки любые даты, содержащие пробелы.)

$ svn checkout -r {2006-02-17}
$ svn checkout -r {15:30}
$ svn checkout -r {15:30:00.200000}
$ svn checkout -r {"2006-02-17 15:30"}
$ svn checkout -r {"2006-02-17 15:30 +0230"}
$ svn checkout -r {2006-02-17T15:30}
$ svn checkout -r {2006-02-17T15:30Z}
$ svn checkout -r {2006-02-17T15:30-04:00}
$ svn checkout -r {20060217T1530}
$ svn checkout -r {20060217T1530Z}
$ svn checkout -r {20060217T1530-0500}
…

Когда вы указываете дату, Subversion находит в хранилище наиболее близкую к ней правку, после чего продолжает работу с вычисленным номером правки.

$ svn log -r {2006-11-28}
------------------------------------------------------------------------
r12 | ira | 2006-11-27 12:31:51 -0600 (Mon, 27 Nov 2006) | 6 lines
…

Также вы можете задавать диапазоны дат. Subversion найдет все правки между обеими датами включительно:

$ svn log -r {2006-11-20}:{2006-11-29}
…
[Внимание]Внимание

Временные метки правок сохраняются как их неверсионированные изменяемые свойства (см. «Свойства» ). Исходя из этого, изменением временных меток можно легко исказить истинную хронологию, или даже удалить совсем информацию о времени правки. Это может привести к неожиданным результатам при внутреннем преобразовании дат в номера правок, выполняемом Subversion.

Свойства

Мы уже подробно рассмотрели, каким образом Subversion сохраняет и извлекает различные версии файлов и каталогов из хранилища. Несколько глав было посвящено этой самой фундаментальной функциональной возможности данного инструмента. И даже если бы поддержка версионирования этим исчерпывалась, Subversion все равно мог бы считаться полноценным средством управления версиями.

Однако Subversion этим не ограничивается.

Помимо версионированния каталогов и файлов, Subversion позволяет для каждого версионированного каталога или файла добавлять, изменять и удалять версионированные метаданные. Мы обращаемся к этим метаданным как к свойствам, которые можно представить в виде таблицы с двумя столбцами, присоединенной к каждому элементу рабочей копии и сопоставляющей имена свойств соответствующим значениям. Вообще, имена и значения свойств могут быть какими угодно; единственное ограничение — имена должны быть читаемым текстом. Самое главное — то, что свойства версионированы точно так же, как и текстовое содержимое файлов. Изменять, фиксировать свойства или возвращать их в исходное состояние так же просто, как и делать то же самое с содержимым файлов. Отправка и получение измененных свойств происходит точно так же, как и обычные фиксации и обновления — для этого нет необходимости менять обычный порядок действий.

В Subversion существует еще одна разновидность свойств. Так же, как и файлы и каталоги, произвольные свойства и соответствующие им значения может иметь каждая правка. Ограничения здесь те же самые — свойство должно иметь читаемое имя и может принимать любое бинарное значение. Главное отличие заключается в том, что свойства правок не версионируются. Другими словами, если изменить значение свойства правки или удалить такое свойство, Subversion не сможет восстановить предыдущее значение.

В Subversion нет жестко определенных правил по использованию свойств. Она требует только того, чтобы имена свойств не начинались с префикса svn:, поскольку это пространство имен закреплено для служебного использования. Subversion действительно использует свойства, как версионированные, так и неверсионированные, для внутренних целей. Ряд версионированных свойств играет особую роль при поиске файлов и каталогов или хранит определенную информацию о правках, в которых они найдены. Ряд свойств автоматически присоединяется к правкам в процессе фиксации, и несет о них определенную информацию . Большинство таких свойств упоминаются в этой или других главах при обсуждении более обших тем, к которым они относятся. Исчерпывающий список предопределенных свойств Subversion приводится в Свойства Subversion.

В этом разделе мы рассмотрим полезность поддержки свойств как для пользователя, так и для самой Subversion. Вы узнаете о командах svn, относящихся к свойствам, и о том, как изменение свойств влияет на привычный рабочий цикл. Надеемся, вы убедитесь в том, что свойства в Subversion расширяют возможности управления версиями.

Зачем нужны свойства?

Итак, Subversion использует свойства, чтобы хранить дополнительную информацию файлах, каталогах и правках. Вы можете найти свойствам аналогичное применение. Наличие места рядом с версионированными данными, в котором можно хранить пользовательские метаданные об этих данных, может пригодиться для поддержки ваших регламентов работы с кодом, или, возможно, для использования какими-то дополнительными утилитами.

Допустим, вы разрабатываете веб-сайт, содержащий много цифровых фотографий и показывающий их с подписями и датой. Набор этих фотографий постоянно изменяется, поэтому сайт нужно по возможности максимально автоматизировать. Фотографии могут быть большого размера, поэтому, как обычно делают на таких сайтах, посетителям потребуется показывать миниатюры изображений.

Эту задачу можно решить с помощью обычных файлов. Рядом, в одном каталоге, вы можете иметь файлы image123.jpg и image123-thumbnail.jpg. Если важно сохранить оригинальное имя файла, миниатюры могут размещаться в отдельном каталоге (например, thumbnails/image123.jpg). Таким же образом, отдельно от основного графического файла, можно хранить описание и дату. Проблема заключается в том, что файловая структура будет сильно разрастаться при каждом добавлении фотографии на сайт.

Теперь представим, как можно организовать работу того же веб-сайта, используя Subversion-свойства файлов. Допустим, имеется файл image123.jpg и у этого файла установлены свойства caption, datestamp и даже thumbnail. В этом случае рабочая копия выглядит гораздо нагляднее. Фактически, она выглядит так, как будто содержит только сами графические файлы, и ничего больше. Однако ваши скрипты автоматизации знают, что с помощью svn (а еще лучше языковой обвязки Subversion — см. «Using Languages Other than C and C++») можно получить дополнительную, необходимую для показа на сайте информацию, не занимаясь чтением индексного файла или манипуляциями с путями.

Не менее часто используются пользовательские свойства правок. Одним из типичных примеров является свойство, хранящее ID записи в трекере, с которой сопоставлена данная правка — например, потому что внесенные в правке изменения исправляют ошибку, зафиксированную в трекере с данным ID. Другие варианты использования свойств правок — задание правке более содержательного имени. Нелегко запомнить, что, к примеру, правка 1935 полностью протестирована! Если же, скажем, задать свойству результаты тестирования в этой правке значение пройдены все тесты, получится абсолютно четкая информация.

Использование свойств

Команда svn предоставляет несколько способов добавления или изменения свойств файлов и каталогов. Чтобы добавить свойство с коротким читаемым значением, наверное, проще всего указать его имя и значение в командной строке подкоманды propset.

$ svn propset copyright '(c) 2006 Red-Bean Software' calc/button.c
property 'copyright' set on 'calc/button.c'
$

Однако мы уже знаем о том, насколько гибкими могут быть свойства Subversion. И если вам необходимо задать свойству многострочное текстовое или даже бинарное значение, передавать его через командную строку будет неудобно. Для таких случаев команда propset имеет параметр --file (-F), позволяющий указать имя файла с новым значением свойства.

$ svn propset license -F /path/to/LICENSE calc/button.c
property 'license' set on 'calc/button.c'
$

На имена свойств накладывается ряд ограничений. Имя должно начинаться с буквы, двоеточия (:) или подчеркивания (_); после них можно использовать цифры, тире (-) и точки (.). [13]

Кроме команды propset, svn предлагает команду propedit. Эта команда использует для добавления или изменения свойства заданную программу-редактор (см. «Config»). При выполнении команды svn вызывает редактор с временным файлом, содержащим текущее значение свойства (или с пустым файлом, если добавляется новое свойство). Затем вы просто изменяете в редакторе значение, пока оно не станет таким, каким вы хотели бы его видеть, сохраняете временный файл и выходите из редактора. Если Subversion обнаружит, что вы действительно изменили существующее значение свойства, будет записано новое значение. Если вы вышли из редактора, не внеся никаких изменений, модификации свойства не произойдет.

$ svn propedit copyright calc/button.c  ### exit the editor without changes
No changes to property 'copyright' on 'calc/button.c'
$

Обращаем ваше внимание на то, что, подобно другим командам svn, команды, относящиеся к свойствам, могут применяться к нескольким путям за раз. Это дает возможность одной командой изменять свойства целого набора файлов. Например, можно сделать вот так:

$ svn propset copyright '(c) 2006 Red-Bean Software' calc/*
property 'copyright' set on 'calc/Makefile'
property 'copyright' set on 'calc/button.c'
property 'copyright' set on 'calc/integer.c'
…
$

Все эти добавления и редактирования свойств были бы не слишком полезны, если бы нельзя было просто узнать значение свойства. Чтобы посмотреть имена и значения свойств, заданных для файлов и каталогов, в svn есть две подкоманды. Команда svn proplist перечисляет существующие для указанного пути свойства. После того как вы узнаете имя свойства, с помощью svn propget можно запросить его значение. Эта команда выведет в стандартный поток ввода-вывода значение свойства для элемента по указанному пути (или путям) и с указанным именем.

$ svn proplist calc/button.c
Properties on 'calc/button.c':
  copyright
  license
$ svn propget copyright calc/button.c
(c) 2006 Red-Bean Software

Существует даже вариант команды proplist, перечисляющий как имена, так и значения свойств. Нужно просто добавить параметр --verbose (-v).

$ svn proplist --verbose calc/button.c
Properties on 'calc/button.c':
  copyright : (c) 2006 Red-Bean Software
  license : ================================================================
Copyright (c) 2006 Red-Bean Software.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions, and the recipe for Fitz's famous
red-beans-and-rice.
…

Последняя команда, относящаяся к свойствам — propdel. Несмотря на то, что Subversion позволяет сохранять свойства с пустыми значениями, полностью удалить свойство с помощью propedit или propset нельзя. Например, такая команда не даст желаемого эффекта:

$ svn propset license '' calc/button.c
property 'license' set on 'calc/button.c'
$ svn proplist --verbose calc/button.c
Properties on 'calc/button.c':
  copyright : (c) 2006 Red-Bean Software
  license :
$

Для полного удаления свойств необходимо пользоваться подкомандой propdel. Ее синтаксис такой же, как и у других команд для работы со свойствами:

$ svn propdel license calc/button.c
property 'license' deleted from 'calc/button.c'.
$ svn proplist --verbose calc/button.c
Properties on 'calc/button.c':
  copyright : (c) 2006 Red-Bean Software
$

Помните, мы говорили о неверсионированных свойствах правок? Их тоже можно изменять с помощью svn. Просто добавьте параметр командной строки --revprop и укажите правку, свойство которой вы хотите изменить. Поскольку правки глобальны, указывать пути не требуется до тех пор, пока вы находитесь в рабочей копии того хранилища, свойство правки в котором вам нужно изменить. В противном случае, нужно просто указать URL любого пути в интересующем вас хранилище (в том числе это может быть и корневой URL хранилища). Например, вы можете заменить лог-сообщение фиксации в существующей правке. [14] Если текущий рабочий каталог является частью рабочей копии хранилища, можно просто выполнить команду svn propset, не указывая целевой путь:

$ svn propset svn:log '* button.c: Fix a compiler warning.' -r11 --revprop
property 'svn:log' set on repository revision '11'
$

Но даже если вы не выгружали из хранилища рабочую копию, можно изменить свойство, указав корневой URL хранилища:

$ svn propset svn:log '* button.c: Fix a compiler warning.' -r11 --revprop \
              http://svn.example.com/repos/project
property 'svn:log' set on repository revision '11'
$

Обратите внимание на то, что изменение этих неверсионированных свойств должно быть явно разрешено администратором (см. «Hook Scripts»). Учитывая то, что свойства не версионируются, при неаккуратном редактировании вы рискуете потерять информацию. Чтобы предотвратить потерю информации, администратор хранилища может принять меры предосторожности, и по умолчанию изменение неверсионированных свойств запрещено.

[Подсказка]Подсказка

Пользователям следует, по возможности, пользоваться svn propedit вместо svn propset. Хотя конечный результат обеих команд будет одинаков, первая позволит увидеть текущее значение свойства перед изменением, и таким образом удостовериться, что вносятся именно те изменения, которые были задуманы. В особенности это справедливо для модификации неверсионированных свойств правок. Да и изменять свойства с многострочными значениями гораздо проще в текстовом редакторе, а не в командной строке.

Свойства и рабочий цикл Subversion

Теперь, когда вы познакомились со всеми командами svn, имеющими отношение к свойствам, давайте посмотрим, как изменения свойств влияют на привычный порядок работы с Subversion. Как мы уже говорили, свойства файлов и каталогов версионированы аналогично содержимому файлов. Поэтому Subversion предоставляет те же возможности по слиянию — в случае конфликтных ситуаций — чужих изменений с вашими собственными.

Так же как и в случае с содержимым файлов, изменения свойств являются локальной модификацией и становятся постоянными только при их фиксации в хранилище с помощью svn commit. Изменение свойств можно легко отменить — команда svn revert восстановит файлы и каталоги в их первоначальное состояние, включая содержимое, свойства и все остальное. Кроме того, интересную информацию о состоянии свойств файлов и каталогов можно получить с помощью команд svn status и svn diff.

$ svn status calc/button.c
 M     calc/button.c
$ svn diff calc/button.c
Property changes on: calc/button.c
___________________________________________________________________
Name: copyright
   + (c) 2006 Red-Bean Software

$

Обратите внимание на то, что подкоманда status показала M не в первой, а во второй колонке. Это произошло потому, что в calc/button.c изменились свойства, а не текстовое содержимое. Если бы мы изменили и то и другое, в первой колонке также стояла бы буква M (см. «svn status»).

Кроме того, нужно помнить о нестандартном подходе, используемом Subversion при выводе различий для свойств. Безусловно, можно запустить svn diff и перенаправить вывод для создания работоспособного патч-файла. Но программа patch будет просто игнорировать различия свойств — как правило, она игнорирует любой мусор, который не может обработать. К сожалению, это означает, что для полного применения патча, сгенерированного svn diff, изменения свойств придется вносить вручную.

Автоматическая установка свойств

Поддержка свойств — мощная функциональная особенность Subversion. Свойства служат базовым механизмом для реализации многих других функций Subversion, обсуждаемых в книге — поддержки текстового поиска различий и слияния, подстановки ключевых слов, трансляции символов перевода строки и т. д. Однако, чтобы получить реальную выгоду от свойств, их нужно задавать для соответствующих файлов и каталогов. К сожалению, среди повседневных забот об этом очень легко забыть, особенно учитывая то, что неустановка значения свойства обычно не приводит к явно заметным ошибкам (по сравнению, скажем, с недобавлением файла под версионный контроль). Чтобы помочь в установке свойств для нужных элементов, Subversion обеспечивает пару простых, но полезных функций.

При каждом добавлении файла под версионный контроль с помощью команд svn add или svn import Subversion пытается автоматически установить несколько базовых свойств файлов. Во-первых, в операционных системах, файловые системы которых поддерживают бит разрешения выполнения, Subversion автоматически задает свойство svn:executable для вновь добавленных или импортированных файлов, у которых этот бит установлен. (Обратитесь к «Исполнимость файла» за дополнительной информации об этом свойстве.) Во-вторых, Subversion выполняет очень простую эвристическую процедуру, чтобы определить, имеет ли файл читаемое содержимое. Если это не так, Subversion автоматически устанавливает свойство svn:mime-type этого файла в значение application/octet-stream (это базовый MIME-тип, обозначающий «набор байтов»). Конечно, если Subversion угадает тип файла неправильно, или если вы пожелаете присвоить свойству svn:mime-type более точное значение — например, image/png или application/x-shockwave-flash — вы всегда можете удалить или отредактировать это свойство. (За дополнительной информацией об использовании MIME-типов в Subversion обратитесь к «Тип содержимого файла».)

Через собственную систему конфигурирования среды исполнения (см. «Параметры времени выполнения») Subversion также поддерживает более гибкую возможность автоматической установки свойств, которая позволяет задавать соответствия между масками имен файлов и именами и значениями свойств. Еще раз: эти соответствия воздействуют на добавление и импорт, и могут не только переопределять решение о MIME-типе по умолчанию, принимаемое Subversion в ходе этих операций, но и устанавливать другие стандартные или пользовательские свойства. Например, вы могли бы задать соответствие, чтобы при каждом добавлении JPEG-файла — то есть элемента, соответствующего маске *.jpg — Subversion автоматически присваивал бы свойству svn:mime-type значение image/jpeg. Или, к примеру, для всех файлов, соответствующих маске *.cpp, свойство svn:eol-style устанавливалось бы в native, а svn:keywords — в Id. Поддержка автоматических свойств — это, пожалуй, наиболее удобный инструмент Subversion в части работы со свойствами среди всего набора доступных средств. См. «Config» для дополнительной информации о настройке такой поддержки.

Переносимость файлов

К радости пользователей Subversion, регулярно работающих с различными компьютерами и операционными системами, утилита командной строки Subversion везде работает практически одинаково. Если вы знаете, как обращаться с svn на одной платформе, вы справитесь с ней и на любой другой платформе.

Однако, это не всегда справедливо для других классов программного обеспечения, а также для конкретных файлов, хранящихся в Subversion. Например, на компьютере под управлением Windows «текстовые файлы» выглядят почти так же как и в Linux, но при этом есть одно существенное отличие — последовательность символов, используемая для маркировки конца строки в таких файлах. Имеются и другие различия. Unix-платформы имеют символьные ссылки (и Subversion их поддерживает), а Windows — не имеет. На Unix-платформах исполнимость файла определяется с помощью прав доступа на уровне файловой системы; Windows использует для этого расширения имен файлов.

Subversion не ставит цели подчинить весь мир некоторым общим определениям и реализовать все на свете. Поэтому максимум, что она может сделать — попытаться упростить жизнь при работе с версионированными файлами и каталогами на различных компьютерах и операционных системах. Далее мы опишем, каким образом Subversion достигает этой цели.

Тип содержимого файла

Subversion принадлежит к многочисленному семейству приложений, распознающих и использующих для типизации содержимого многоцелевые расширения интернет-почты (Multipurpose Internet Mail Extensions — MIME). Свойство svn:mime-type не только является универсальным местом хранения информации о типе содержимого файла, но и определяет некоторые особенности поведения Subversion.

Например, одной из полезных возможностей Subversion является контекстное, построчное слияние изменений, полученных от сервера во время обновления, с рабочей копией. Однако, для файлов, не содержащих текстовых данных, как правило, не существует понятия «строки». Поэтому для версионированных файлов, чье свойство svn:mime-type указывает на нетекстовый MIME-тип (как правило, это все, что не начинается с text/, хотя есть несколько исключений), Subversion не будет пытаться провести контекстное слияние во время обновления. Вместо этого, каждый раз когда вы локально модифицируете рабочую копию бинарного файла, и выполняете после этого обновление, файл будет переименован с добавлением расширения .orig, после чего Subversion запишет под оригинальным именем новый файл рабочей копии, c изменениями, полученными в процессе обновления, но без ваших локальных исправлений. Такое поведение призвано защитить пользователя от неудачных попыток выполнить контекстное слияние для файлов, к которым его нельзя применить.

Кроме того, если для файла определено свойство svn:mime-type, Apache-модуль Subversion будет использовать его значение при формировании HTTP-заголовка Content-type: в ответ на GET-запросы. Благодаря этому ваш браузер (в том случае, если он будет использоваться для просмотра содержимого Subversion-хранилища) будет знать, как правильно отобразить этот файл.

Исполнимость файла

На многих операционных системах возможность выполнения файла как команды определяется битом разрешения выполнения. Обычно по умолчанию этот бит не задан; он должен быть явно установлен пользователем для тех файлов, которым это необходимо. Однако, было бы слишком сложным запоминать, какие именно файлы в только что созданной рабочей копии должны иметь установленный бит выполнения, и устанавливать этот бит. Поэтому Subversion поддерживает свойство svn:executable, позволяющее указать, для каких файлов должен быть установлен бит исполнения. При создании рабочей копии Subversion самостоятельно установит этот бит для таких файлов.

Это свойство не оказывает никакого эффекта на файловых системах, не использующих бита разрешения выполнения, таких как FAT32 и NTFS. [16]. Кроме того, хотя значение этого свойства не задано, Subversion принудительно устанавливает ему значение *. Наконец, это свойство действительно только для файлов, но не для каталогов.

Символы конца строки

Subversion считает, что файл содержит читаемые данные, если на обратное не указывает версионированное свойство файла svn:mime-type. В общем-то, Subversion необходимо знать об этом только для того, чтобы определить возможность построения контекстного отчета о различиях. В противном случае Subversion будет воспринимать файл лишь как набор байтов.

Сказанное означает, что по умолчанию Subversion не уделяет никакого внимания используемой в файлах разновидности маркера конца строки (EOL). К сожалению, различные операционные системы используют различные соглашения о том, какая последовательность символов означает конец текстовой строки в файле. Например, программы под Windows обычно используют в качестве признака конца строки последовательность из двух управляющих символов ASCII — возврата каретки (CR) и перевода строки (LF). В то же время программы под Unix для обозначения конца строки используют единственный символ LF.

Далеко не все програмы способны понимать файлы, в которых признак конца строки отличается по формату от принятого стиля завершения строк в данной операционной системе. Обычным делом является ситуация, когда программы под Unix рассматривают символ CR, присутствующий в файлах Windows, как обычный символ (часто представляя его как ^M), или когда программы под Windows слепляют все строки файла Unix в одну гигантскую строку, поскольку в нем отсутствуют комбинации символов возврата каретки и перевода строки (или CRLF), обозначающие концы строк.

Такая чувствительность к чужеродным EOL-маркерам может стать серьезной проблемой для людей, совместно использующих одни и те же файлы в различных операционных системах. Возьмем для примера файл с исходным кодом программы и разработчиков, редактирующих этот файл как под Windows, так и под Unix. Если все разработчики будут всегда использовать инструменты, сохраняющие в файле прежний стиль завершения строк, проблем не возникнет.

Но на практике многие распространенные утилиты либо не умеют правильно считывать файлы с чужеродными EOL-маркерами, либо конвертируют концы строк в файле к родному стилю при сохранении файла. Если разработчик сталкивается с первым случаем, он оказывается вынужденным пользоваться внешними утилитами конвертации (такими как dos2unix или ее аналоги, unix2dos), чтобы подготовить файл к редактированию. Во втором случае дополнительная подготовка файлов не требуется. Однако, в обоих случаях получается файл, каждая строка в котором отличается от исходной! Прежде чем фиксировать свои изменения, пользователь может сделать одно из двух. Он может либо использовать утилиту конвертации, чтобы восстановить в модифицированном файле прежний стиль завершения строк; либо просто зафиксировать файл с новыми EOL-маркерами.

Результатом такого сценария станут напрасная трата времени и нежелательные изменения в фиксируемых файлах. Напрасная трата времени сама по себе обходится довольно дорого. А когда фиксация вносит изменения в каждую строку файла, становится невозможным определить, какие строки файла действительно изменились по существу. Был ли устранен тот самый баг? В какой строке имелась синтаксическая ошибка?

Данную проблему решает свойство svn:eol-style. Когда этому свойству задано одно из допустимых значений, Subversion использует его для того, чтобы определить вариант специальной обработки файла, производимой для того, чтобы стиль завершения строки не изменялся туда-сюда при каждой фиксации, выполняемой из другой операционной системы. Допустимы следующие значения:

native

Файл будет содержать EOL-маркеры, принятые в той операционной системе, на которой работает Subversion. Иными словами, если пользователь на машине с Windows создает рабочую копию файла, у которого свойство svn:eol-style установлено в native, этот файл будет содержать EOL-маркеры CRLF. Пользователь Unix, создавая рабочую копию того же самого файла, увидит в нем EOL-маркер LF.

Учтите, что на самом деле Subvversion будет записывать файл в хранилище, используя нормализованный EOL-маркер LF, вне зависимости от операционной системы. Хотя обычно это прозрачно для пользователя.

CRLF

Файл будет содержать в качестве EOL-маркеров последовательность CRLF, независимо от используемой операционной системы.

LF

Файл будет содержать в качестве EOL-маркера символ LF, независимо от используемой операционной системы.

CR

Файл будет содержать в качестве EOL-маркера символ CR, независимо от используемой операционной системы. Данный стиль завершения строки не слишком распространен. Он использовался на устаревших платформах Macintosh (на которых Subversion даже никогда не запускался).

Пропуск неверсионированных элементов

В любой реальной рабочей копии среди версионированных файлов и каталогов почти наверняка обнаружатся и другие файлы и каталоги, которые не версионированы и не должны быть таковыми. Текстовые редакторы мусорят, создавая каталоги с резервными копиями файлов. Компиляторы программного кода генерируют временные — или даже результирующие — файлы, которые обычно нет смысла версионировать. Сами пользователи также бросают различные файлы и каталоги там, где им проще — в том числе нередко и в каталогах рабочей копии.

Было бы нелепо ожидать, что рабочие копии Subversion окажутся в стороне от такого рода мусора и беспорядка. При этом Subversion считает своей важной особенностью то, что ее рабочие копии являются самыми обычными каталогами, такими же как и неверсионированные структуры каталогов. Однако не подлежащие версионированию файлы и каталоги могут вызывать у пользователей Subversion некоторое раздражение. Например, поскольку команды svn add и svn import по умолчанию действуют рекурсивно и не знают, какие из вновь созданных файлов в данном каталоге вы не собираетесь версионировать, очень легко случайно добавить под версионный контроль всякий хлам, о котором вы даже не думали. Кроме того, много лишнего может выводить команда svn status, поскольку по умолчанию она выдает отчет по каждому элементу в рабочей копии, включая неверсионированные файлы и каталоги.

Исходя из этого, Subversion поддерживает два способа для того, чтобы указать, на какие файлы желательно просто не обращать внимание. Первый способ затрагивает систему настройки среды исполнения Subversion (см. «Параметры времени выполнения»), и, следовательно, применяется ко всем операциям Subversion, использующим эти настройки среды исполнения (которые, как правило, производятся на конкретном компьютере или конкретным пользователем компьютера). Другой способ использует поддерживаемые в Subversion свойства каталогов, он более тесно связан с самим версионированным деревом каталогов и, следовательно, действует для всех, кто оперирует рабочей копией этого дерева. Оба механизма используют маски файлов.

Система настройки среды исполнения Subversion имеет параметр global-ignores, значением которой служит разделенный пробелами набор масок файлов. Эти маски применяются к файлам, являющимся кандидатами на добавление под версионный контроль, а также к неверсионированным файлам, попадающим в поле зрения команды svn status. Если имя файла соответствуют одной из масок, Subversion будет действовать так, как будто файла вовсе не существует. Это действительно полезно для масок файлов, которые вы однозначно не хотите версионировать — например, файлов резервных копий, создаваемых редакторами, таких как файлы *~ и .*~ от Emacs.

Свойство svn:ignore, задаваемое для версионированного каталога, содержит список масок файлов (каждая маска записывается с новой строки), с помощью которого Subversion должна определять, какие объекты следует игнорировать в этом каталоге. Эти маски не переопределяют те, что заданы параметром среды исполнения global-ignores, а дополняют их. Стоит отметить, что в отличие от параметра global-ignores, маски, перечисленные в свойстве svn:ignore, применяются только к тому каталогу, в свойстве которого они заданы, не затрагивая любые его подкаталоги. Свойство svn:ignore — это хороший способ попросить Subversion пропускать файлы, которые, вероятно, присутствуют во всех пользовательских рабочих копиях — например, результаты компиляции или, если взять пример, более подходящий этой книге, файлы HTML, PDF или PostScript, генерируемые в результате преобразования исходных файлов формата DocBook XML в более удобный для чтения выходной формат.

[Внимание]Внимание

Реализованная в Subverion поддержка масок пропуска файлов действует только в момент добавления неверсионированного файла или каталога под версионный контроль. Если объект уже находится под управлением Subversion, механизм масок пропуска больше к нему не применяется. Иными словами, не следует ожидать, что Subversion не будет фиксировать изменения, сделанные в версионированном файле, только на том основании, что его имя соответствует маске пропуска — Subversion всегда просматривает все версионированные объекты.

Глобальный список масок пропуска в большей степени подходит для задания личных предпочтений, и завязан больше на конкретный набор пользовательских инструментов, чем на специфику конкретной рабочей копии. Исходя из этого, остаток данной главы будет посвящен использованию свойства svn:ignore.

Допустим, что команда svn status выдает нам следующее:

$ svn status calc
 M     calc/button.c
?      calc/calculator
?      calc/data.c
?      calc/debug_log
?      calc/debug_log.1
?      calc/debug_log.2.gz
?      calc/debug_log.3.gz

В примере видно, что вы изменили некоторые свойства файла button.c, и, кроме того, в рабочей копии есть несколько неверсионированных файлов: программа calculator, скомпилированная из исходных кодов, файл исходного кода data.c и набор файлов с отладочными сообщениями. Вам известно, что ваша система сборки всегда генерирует программу с именем calculator. [17] Также вам известно, что после тестового прогона всегда остаются те самые файлы с отладочными сообщениями. Это справедливо не только для вашей, но и для всех остальных рабочих копий данного проекта. Вы точно знаете, что вам не хотелось бы видеть эти отладочные файлы при каждом запуске команды svn status, и вы абсолютно уверены, что так же их не хотелось бы видеть и остальным. Исходя из этого, можно добавить необходимые маски пропуска для каталога calc, выполнив команду svn propedit svn:ignore calc. Например, вы могли бы добавить в значение свойства svn:ignore такие строки:

calculator
debug_log*

Результатом добавления этого свойства станет локальное изменение свойств в каталоге calc. Обратите внимание, чем еще отличается теперь вывод команды svn status:

$ svn status
 M     calc
 M     calc/button.c
?      calc/data.c

Заметьте, весь "мусор" исчез из вывода! Конечно, скомпилированная программа calculator и упоминавшиеся файлы отладочных сообщений никуда не делись из вашей рабочей копии. Просто Subversion больше не напоминает вам об их существовании. Теперь, когда весь не представляющий интереса "мусор" исчез с экрана, вам остается разобраться с более интересными элементами — в частности, с исходным файлом data.c, который вы, вероятно, забыли добавить под версионный контроль.

Конечно же, вам доступен не только этот короткий отчет о статусе вашей рабочей копии. Если в какой-то момент времени вам действительно захочется увидеть в составе статусного отчета проигнорированные файлы, вы можете воспользоваться опцией --no-ignore:

$ svn status --no-ignore
 M     calc
 M     calc/button.c
I      calc/calculator
?      calc/data.c
I      calc/debug_log
I      calc/debug_log.1
I      calc/debug_log.2.gz
I      calc/debug_log.3.gz

Как отмечалось выше, список файловых масок для пропуска также учитывается командами svn add и svn import. В результате обеих операций Subversion берет под управление некоторое множество файлов и каталогов. Прежде чем требовать у пользователя, чтобы он выбирал те файлы в структуре каталогов, которые необходимо версионировать, Subversion применяет маски пропуска — как глобальные, так и назначенные отдельным каталогам — чтобы определить, какие файлы не должны подхватываться системой управления версиями в ходе рекурсивной операции добавления или импорта. И снова вы можете воспользоваться опцией --no-ignore, чтобы предложить Subversion не учитывать списки пропуска и обрабатывать все имеющиеся файлы и каталоги.

Подстановка ключевых слов

Subversion умеет выполнять подстановку ключевых слов — элементов полезной динамической информации о версионированном файле — в составе этого файла. Чаще всего ключевые слова замещают информацию о времени последнего изменения файла. Поскольку эта информация меняется при каждом изменении файла, и, что особенно важно, сразу после того, как файл будет изменен, никакой другой процесс, кроме системы управления версиями, не в состоянии поддерживать полную актуальность этих данных. Будучи отданной на откуп человеку, эта информация неизбежно будет оказываться устаревшей.

Предположим, у вас есть файл, в тексте которого вы хотели бы всегда видеть дату его последнего изменения. Вы могли бы вменить в обязанность каждому автору этого документа, чтобы непосредственно перед фиксацией своих изменений он также исправлял в нем запись о времени последнего внесения изменений. Но рано или поздно кто-нибудь забудет сделать это! Чтобы такого не случалось, мы можем попросить Subversion производить подстановку на место ключевого слова LastChangedDate. Позиция, куда должна производиться подстановка, определяется местоположением указателя ключевого слова в содержании файла. Этот указатель представляет собой обычную текстовую строку, имеющую формат $KeywordName $.

Все ключевые слова чувствительны к регистру, когда идет речь об указателях на них в файлах: вы должны использовать правильный регистр символов в написании ключевого слова. Значение свойства svn:keywords также следует рассматривать как чувствительное к регистру — и хотя некоторые имена ключевых слов распознаются независимо от регистра, рассчитывать на это не стоит.

В Subversion определен список ключевых слов, доступных для подстановки. Он содержит следующие пять ключевых слов; некоторые из них имеют псевдонимы, которые вы также можете использовать:

Date

Это ключевое слово замещает время последнего изменения файла в хранилище и выглядит примерно так: $Date: 2006-07-22 21:42:37 -0700 (Sat, 22 Jul 2006) $. Также его можно задать как LastChangedDate.

Revision

Это ключевое слово замещает номер последней правки, в которой файл был изменен в хранилище, и выглядит примерно так: $Revision: 144 $. Также его можно задать как LastChangedRevision или Rev.

Author

Это ключевое слово замещает имя пользователя, который последним изменил этот файл в хранилище, и выглядит примерно так: $Author: harry $. Также его можно задать как LastChangedBy.

HeadURL

Это ключевое слово замещает полный URL к последней версии файла в хранилище, и выглядит примерно так: $HeadURL: http://svn.collab.net/repos/trunk/README $. Оно может быть сокращено до URL.

Id

Это ключевое слово — компактная комбинация всех остальных. Его подстановка выглядит примерно так: $Id: calc.c 148 2006-07-28 21:30:43Z sally $, и означает, что файл calc.c последний раз был изменен в правке 148, зафиксированной вечером 28 июля 2006 года пользователем sally.

Если просто разместить в тексте файла указатель ключевого слова, ничего не произойдет. Subversion никогда не пытается осуществить текстовую подстановку в содержании файла, пока вы явно его об этом не попросите. В конце концов, вы ведь могли бы написать документ [18] о том, как пользоваться ключевыми словами, и вы, очевидно, не захотите, чтобы Subversion заместил указатели на ключевые слова, приведенные вами в качестве примера!

Чтобы указать Subversion, следует ли ему выполнять подстановку ключевых слов в конкретном файле, снова обратимся к подкомандам для работы со свойствами. Свойство svn:keywords, устанавливаемое для версионированного файла, задает перечень ключевых слов, которые будут замещаться в этом файле. Его значение представляет собой список имен ключевых слов или псевдонимов из приведенной выше таблицы, разделенных пробелами.

В качестве примера допустим, что у вас есть версионированный файл с именем weather.txt, который выглядит следующим образом::

Here is the latest report from the front lines.
$LastChangedDate$
$Rev$
Cumulus clouds are appearing more frequently as summer approaches.

Если для этого файла не задать свойство svn:keywords, Subversion не будет делать ничего особенного. Давайте разрешим теперь подстановку ключевого слова LastChangedDate.

$ svn propset svn:keywords "Date Author" weather.txt
property 'svn:keywords' set on 'weather.txt'
$

Итак, вы произвели локальное изменение свойства файла weather.txt. Вы не увидите никаких изменений в содержании файла (если вы, конечно, не вносили своих изменений до того, как задать свойство). Заметьте, что файл содержал также указатель на ключевое слово Rev, которое мы не стали включать в значение свойства. Subversion без проблем проигнорирует подстановку тех ключевых слов, которые не присутствуют в файле, а также не будет замещать ключевые слова, не перечисленные в значении свойства svn:keywords.

Сразу же после того, как вы зафиксируете изменение свойства, Subversion обновит файл рабочей копии с новым текстом подстановки. Вместо указателя ключевого слова $LastChangedDate$ вы увидите результат подстановки. Этот результат так же будет содержать имя ключевого слова, и по-прежнему будет ограничен знаками доллара ($). Как мы и предсказывали, подстановки ключевого слова Rev не произошло, поскольку мы не просили об этом Subversion.

Заметим также, что мы установили свойству svn:keywords значение «Date Author», в то время как указатель ключевого слова использовал псевдоним $LastChangedDate$. Тем не менее, его замещение прошло корректно.

Here is the latest report from the front lines.
$LastChangedDate: 2006-07-22 21:42:37 -0700 (Sat, 22 Jul 2006) $
$Rev$
Cumulus clouds are appearing more frequently as summer approaches.

Теперь, если кто-то другой зафиксирует изменения в weather.txt, ваша копия этого файла продолжит показывать прежний результат подстановки — до тех пор, пока вы не обновите рабочую копию. При обновлении в вашем файле weather.txt будет произведена переподстановка ключевого слова той информацией, которая отражает наиболее свежую фиксацию этого файла.

Subversion 1.2 предлагает новый вариант синтаксиса для работы с ключевыми словами, который предоставляет дополнительные, весьма полезные — хотя, вероятно, не совсем типичные — функциональные возможности. Теперь вы можете попросить Subversion сохранять фиксированную длину для результата подстановки ключевого слова (имеется в виду число занимаемых байтов). Для этого используйте удвоенное двоеточие (::) после имени ключевого слова, вслед за которым поместите столько пробелов, сколько нужно для задания фиксированной длины. Когда Subversion на место ключевого слова будет подставлять ключевое слово и его значение, она заменит только эти пробельные символы, оставив неизменной полную длину поля с ключевым словом. Если подставляемое значение окажется короче, чем заданная ширина поля, оно будет дополнено на конце символами-заполнителями (пробелами). Если подставляемое значение окажется слишком длинным, оно будет усечено, при этом непосредственно перед закрывающим знаком доллара (ограничителем) будет помещен специальный хэш-символ (#).

Допустим, к примеру, что в вашем документе имеется раздел табулированных данных, отражающих значение ключевых слов Subversion для этого документа. При использовании исходного синтаксиса подстановки ключевых слов Subversion ваш файл мог бы выглядеть примерно так:

$Rev$:     Revision of last commit
$Author$:  Author of last commit
$Date$:    Date of last commit

Поначалу он выглядит красиво и похож на таблицу. Но когда вы выполните фиксацию этого файла (конечно же, при разрешенной подстановке ключевых слов), то увидите следующее:

$Rev: 12 $:     Revision of last commit
$Author: harry $:  Author of last commit
$Date: 2006-03-15 02:33:03 -0500 (Wed, 15 Mar 2006) $:    Date of last commit

Результат уже не столь красив. Возможно, вам даже захочется выровнять содержимое файла после подстановки, чтобы он снова выглядел как таблица. Но выравнивание будет держаться только до тех пор, пока значение ключевого слова будет иметь неизменную длину. Если в номере последней зафиксированной правки добавится новый разряд (скажем, при переходе от 99 к 100), или фиксацию выполнит другой человек с более длинным именем пользователя, ваши труды снова пойдут насмарку. Однако, если вы используете Subversion версии 1.2 или выше, вы можете пользоваться новым синтаксисом ключевых слов с фиксированной длиной, задавая полям такую длину, чтобы получить аккуратный внешний вид. Теперь ваш файл мог бы выглядеть примерно так:

$Rev::               $:  Revision of last commit
$Author::            $:  Author of last commit
$Date::              $:  Date of last commit

Зафиксируем эти изменения в вашем файле. Теперь Subversion заметит новый синтаксис ключевых слов с фиксированной длиной и сохранит ширину полей такой, какой она была задана с помощью пробелов, помещенных вами между удвоенным двоеточием и замыкающим знаком доллара. После выполнения подстановки ширина поля совершенно не изменится — короткие значения для Rev и Author будут дополнены пробелами, а длинное поле Date будет обрезано хэш-символом:

$Rev:: 13            $:  Revision of last commit
$Author:: harry      $:  Author of last commit
$Date:: 2006-03-15 0#$:  Date of last commit

Использование ключевых слов с фиксированной длиной особенно удобно, когда подстановки производятся в сложных файловых форматах, которые сами используют поля фиксированной длины для своих данных, либо в которых достаточно трудно изменить размер определенного поля данных, не прибегая к использованию родного для данного формата приложения (в качестве примера можно привести документы Microsoft Office).

[Внимание]Внимание

Помните, что, поскольку ширина поля для ключевого слова измеряется в байтах, существует опасность повреждения многобайтовых символов. Например, имя пользователя, содержащее многобайтовые символы UTF-8, может подвергнуться усечению посреди строки байтов, отрезав часть байтов одного из символов. Результатом может стать не только усечение, видимое на байтовом уровне, но и строка с некорректным или искаженным последним символом при ее просмотре как текста в формате UTF-8. Вполне возможно, что некоторые приложения при загрузке такого файла обнаружат поврежденный текст UTF-8 и посчитают поврежденным весь файл, отказавшись из-за этого с ним работать.

Locking

Subversion's copy-modify-merge version control model lives and dies on its data merging algorithms, specifically on how well those algorithms perform when trying to resolve conflicts caused by multiple users modifying the same file concurrently. Subversion itself provides only one such algorithm, a three-way differencing algorithm which is smart enough to handle data at a granularity of a single line of text. Subversion also allows you to supplement its content merge processing with external differencing utilities (as described in «External diff3»), some of which may do an even better job, perhaps providing granularity of a word or a single character of text. But common among those algorithms is that they generally work only on text files. The landscape starts to look pretty grim when you start talking about content merges of non-textual file formats. And when you can't find a tool that can handle that type of merging, you begin to run into problems with the copy-modify-merge model.

Let's look at a real-life example of where this model runs aground. Harry and Sally are both graphic designers working on the same project, a bit of marketing collateral for an automobile mechanic. Central to the design of a particular poster is an image of a car in need of some body work, stored in a file using the PNG image format. The poster's layout is almost finished, and both Harry and Sally are pleased with the particular photo they chose for their damaged car—a baby blue 1967 Ford Mustang with an unfortunate bit of crumpling on the left front fender.

Now, as is common in graphic design work, there's a change in plans which causes the car's color to be a concern. So Sally updates her working copy to HEAD, fires up her photo editing software, and sets about tweaking the image so that the car is now cherry red. Meanwhile, Harry, feeling particularly inspired that day, decides that the image would have greater impact if the car also appears to have suffered greater impact. He, too, updates to HEAD, and then draws some cracks on the vehicle's windshield. He manages to finish his work before Sally finishes hers, and after admiring the fruits of his undeniable talent, commits the modified image. Shortly thereafter, Sally is finished with the car's new finish, and tries to commit her changes. But, as expected, Subversion fails the commit, informing Sally that now her version of the image is out of date.

Here's where the difficulty sets in. Were Harry and Sally making changes to a text file, Sally would simply update her working copy, receiving Harry's changes in the process. In the worst possible case, they would have modified the same region of the file, and Sally would have to work out by hand the proper resolution to the conflict. But these aren't text files—they are binary images. And while it's a simple matter to describe what one would expect the results of this content merge to be, there is precious little chance that any software exists which is smart enough to examine the common baseline image that each of these graphic artists worked against, the changes that Harry made, and the changes that Sally made, and spit out an image of a busted-up red Mustang with a cracked windshield!

Clearly, things would have gone more smoothly if Harry and Sally had serialized their modifications to the image. If, say, Harry had waited to draw his windshield cracks on Sally's now-red car, or if Sally had tweaked the color of a car whose windshield was already cracked. As is discussed in «Модель Копирование-Изменение-Слияние», much of these types problems go away entirely where perfect communication between Harry and Sally exists. [19] But as one's version control system is, in fact, one form of communication, it follows that having that software facilitate the serialization of non-parallelizable energies is no bad thing. And this where Subversion's implementation of the lock-modify-unlock model steps into the spotlight. This is where we talk about Subversion's locking feature, which is similar to the «reserved checkouts» mechanisms of other version control systems.

Subversion's locking feature serves two main purposes:

  • Serializing access to a versioned object. By allowing a user to programmatically claim the exclusive right to change to a file in the repository, that user can be reasonably confident that energy invested on unmergeable changes won't be wasted—his commit of those changes will succeed.

  • Aiding communication. By alerting other users that serialization is in effect for particular versioned object, those other users can reasonably expect that the object is about to be changed by someone else, and they, too, can avoid wasting their time and energy on unmergeable changes that won't be committable due to eventual out-of-dateness.

When referring to Subversion's locking feature, one is actually talking about a fairly diverse collection of behaviors which include the ability to lock a versioned file [20] (claiming the exclusive right to modify the file), to unlock that file (yielding that exclusive right to modify), to see reports about which files are locked and by whom, to annotate files for which locking before editing is strongly advised, and so on. In this section, we'll cover all of these facets of the larger locking feature.

Creating locks

In the Subversion repository, a lock is a piece of metadata which grants exclusive access to one user to change a file. This user is said to be the lock owner. Each lock also has a unique identifier, typically a long string of characters, known as the lock token. The repository manages locks, ultimately handling their creation, enforcement, and removal. If any commit transaction attempts to modify or delete a locked file (or delete one of the parent directories of the file), the repository will demand two pieces of information—that the client performing the commit be authenticated as the lock owner, and that the lock token has been provided as part of the commit process as a sort of proof that client knows which lock it is using.

To demonstrate lock creation, let's refer back to our example of multiple graphic designers working with on the same binary image files. Harry has decided to change a JPEG image. To prevent other people from committing changes to the file while he is modifying it (as well as alerting them that he is about to change it), he locks the file in the repository using the svn lock command.

$ svn lock banana.jpg --message "Editing file for tomorrow's release."
'banana.jpg' locked by user 'harry'.
$

There are a number of new things demonstrated in the previous example. First, notice that Harry passed the --message option to svn lock. Similar to svn commit, the svn lock command can take comments (either via --message (-m) or --file (-F)) to describe the reason for locking the file. Unlike svn commit, however, svn lock will not demand a message by launching your preferred text editor. Lock comments are optional, but still recommended to aid communication.

Secondly, the lock attempt succeeded. This means that the file wasn't already locked, and that Harry had the latest version of the file. If Harry's working copy of the file had been out-of-date, the repository would have rejected the request, forcing Harry to svn update and reattempt the locking command. The locking command would also have failed if the file already been locked by someone else.

As you can see, the svn lock command prints confirmation of the successful lock. At this point, the fact that the file is locked becomes apparent in the output of the svn status and svn info reporting subcommands.

$ svn status
     K banana.jpg

$ svn info banana.jpg
Path: banana.jpg
Name: banana.jpg
URL: http://svn.example.com/repos/project/banana.jpg
Repository UUID: edb2f264-5ef2-0310-a47a-87b0ce17a8ec
Revision: 2198
Node Kind: file
Schedule: normal
Last Changed Author: frank
Last Changed Rev: 1950
Last Changed Date: 2006-03-15 12:43:04 -0600 (Wed, 15 Mar 2006)
Text Last Updated: 2006-06-08 19:23:07 -0500 (Thu, 08 Jun 2006)
Properties Last Updated: 2006-06-08 19:23:07 -0500 (Thu, 08 Jun 2006)
Checksum: 3b110d3b10638f5d1f4fe0f436a5a2a5
Lock Token: opaquelocktoken:0c0f600b-88f9-0310-9e48-355b44d4a58e
Lock Owner: harry
Lock Created: 2006-06-14 17:20:31 -0500 (Wed, 14 Jun 2006)
Lock Comment (1 line):
Editing file for tomorrow's release.

$

That the svn info command, which does not contact the repository when run against working copy paths, can display the lock token reveals an important fact about lock tokens—that they are cached in the working copy. The presence of the lock token is critical. It gives the working copy authorization to make use of the lock later on. Also, the svn status command shows a K next to the file (short for locKed), indicating that the lock token is present.

Now that Harry has locked banana.jpg, Sally is unable to change or delete that file:

$ svn delete banana.jpg
D         banana.jpg
$ svn commit -m "Delete useless file."
Deleting       banana.jpg
svn: Commit failed (details follow):
svn: DELETE of
'/repos/project/!svn/wrk/64bad3a9-96f9-0310-818a-df4224ddc35d/banana.jpg':
423 Locked (http://svn.example.com)
$

But Harry, after touching up the banana's shade of yellow, is able to commit his changes to the file. That's because he authenticates as the lock owner, and also because his working copy holds the correct lock token:

$ svn status
M    K banana.jpg
$ svn commit -m "Make banana more yellow"
Sending        banana.jpg
Transmitting file data .
Committed revision 2201.
$ svn status
$

Notice that after the commit is finished, svn status shows that the lock token is no longer present in working copy. This is the standard behavior of svn commit—it searches the working copy (or list of targets, if you provide such a list) for local modifications, and sends all the lock tokens it encounters during this walk to the server as part of the commit transaction. After the commit completes successfully, all of the repository locks that were mentioned are released—even on files that weren't committed. This is meant to discourage users from being sloppy about locking, or from holding locks for too long. If Harry haphazardly locks thirty files in a directory named images because he's unsure of which files he needs to change, yet only only changes four of those file, when he runs svn commit images, the process will still release all thirty locks.

This behavior of automatically releasing locks can be overridden with the --no-unlock option to svn commit. This is best used for those times when you want to commit changes, but still plan to make more changes and thus need to retain existing locks. You can also make this your default behavior by setting the no-unlock runtime configuration option (see «Параметры времени выполнения»).

Of course, locking a file doesn't oblige one to commit a change to it. The lock can be released at any time with a simple svn unlock command:

$ svn unlock banana.c
'banana.c' unlocked.

Discovering locks

When a commit fails due to someone else's locks, it's fairly easy to learn about them. The easiest of these is svn status --show-updates:

$ svn status --show-updates
M              23   bar.c
M    O         32   raisin.jpg
       *       72   foo.h
Status against revision:     105
$

In this example, Sally can see not only that her copy of foo.h is out-of-date, but that one of the two modified files she plans to commit is locked in the repository. The O symbol stands for «Other», meaning that a lock exists on the file, and was created by somebody else. If she were to attempt a commit, the lock on raisin.jpg would prevent it. Sally is left wondering who made the lock, when, and why. Once again, svn info has the answers:

$ svn info http://svn.example.com/repos/project/raisin.jpg
Path: raisin.jpg
Name: raisin.jpg
URL: http://svn.example.com/repos/project/raisin.jpg
Repository UUID: edb2f264-5ef2-0310-a47a-87b0ce17a8ec
Revision: 105
Node Kind: file
Last Changed Author: sally
Last Changed Rev: 32
Last Changed Date: 2006-01-25 12:43:04 -0600 (Sun, 25 Jan 2006)
Lock Token: opaquelocktoken:fc2b4dee-98f9-0310-abf3-653ff3226e6b
Lock Owner: harry
Lock Created: 2006-02-16 13:29:18 -0500 (Thu, 16 Feb 2006)
Lock Comment (1 line):
Need to make a quick tweak to this image.
$

Just as svn info can be used to examine objects in the working copy, it can also be used to examine objects in the repository. If the main argument to svn info is a working copy path, then all of the working copy's cached information is displayed; any mention of a lock means that the working copy is holding a lock token (if a file is locked by another user or in another working copy, svn info on a working copy path will show no lock information at all). If the main argument to svn info is a URL, then the information reflects the latest version of an object in the repository, and any mention of a lock describes the current lock on the object.

So in this particular example, Sally can see that Harry locked the file on February 16th to «make a quick tweak». It being June, she suspects that he probably forgot all about the lock. She might phone Harry to complain and ask him to release the lock. If he's unavailable, she might try to forcibly break the lock herself or ask an administrator to do so.

Breaking and stealing locks

A repository lock isn't sacred—in Subversion's default configuration state, locks can be released not only by the person who created them, but by anyone at all. When somebody other than the original lock creator destroys a lock, we refer to this as breaking the lock.

From the administrator's chair, it's simple to break locks. The svnlook and svnadmin programs have the ability to display and remove locks directly from the repository. (For more information about these tools, see «An Administrator's Toolkit».)

$ svnadmin lslocks /usr/local/svn/repos
Path: /project2/images/banana.jpg
UUID Token: opaquelocktoken:c32b4d88-e8fb-2310-abb3-153ff1236923
Owner: frank
Created: 2006-06-15 13:29:18 -0500 (Thu, 15 Jun 2006)
Expires:
Comment (1 line):
Still improving the yellow color.

Path: /project/raisin.jpg
UUID Token: opaquelocktoken:fc2b4dee-98f9-0310-abf3-653ff3226e6b
Owner: harry
Created: 2006-02-16 13:29:18 -0500 (Thu, 16 Feb 2006)
Expires:
Comment (1 line):
Need to make a quick tweak to this image.

$ svnadmin rmlocks /usr/local/svn/repos /project/raisin.jpg
Removed lock on '/project/raisin.jpg'.
$

The more interesting option is allowing users to break each other's locks over the network. To do this, Sally simply needs to pass the --force to the unlock command:

$ svn status --show-updates
M              23   bar.c
M    O         32   raisin.jpg
       *       72   foo.h
Status against revision:     105
$ svn unlock raisin.jpg
svn: 'raisin.jpg' is not locked in this working copy
$ svn info raisin.jpg | grep URL
URL: http://svn.example.com/repos/project/raisin.jpg
$ svn unlock http://svn.example.com/repos/project/raisin.jpg
svn: Unlock request failed: 403 Forbidden (http://svn.example.com)
$ svn unlock --force http://svn.example.com/repos/project/raisin.jpg
'raisin.jpg' unlocked.
$

Now, Sally's initial attempt to unlock failed because she ran svn unlock directly on her working copy of the file, and no lock token was present. To remove the lock directly from the repository, she needs to pass a URL to svn unlock. Her first attempt to unlock the URL fails, because she can't authenticate as the lock owner (nor does she have the lock token). But when she passes --force, the authentication and authorization requirements are ignored, and the remote lock is broken.

Of course, simply breaking a lock may not be enough. In the running example, Sally may not only want to break Harry's long-forgotten lock, but re-lock the file for her own use. She can accomplish this by running svn unlock --force and then svn lock back-to-back, but there's a small chance that somebody else might lock the file between the two commands. The simpler thing to is steal the lock, which involves breaking and re-locking the file all in one atomic step. To do this, Sally passes the --force option to svn lock:

$ svn lock raisin.jpg
svn: Lock request failed: 423 Locked (http://svn.example.com)
$ svn lock --force raisin.jpg
'raisin.jpg' locked by user 'sally'.
$

In any case, whether the lock is broken or stolen, Harry may be in for a surprise. Harry's working copy still contains the original lock token, but that lock no longer exists. The lock token is said to be defunct. The lock represented by the lock-token has either been broken (no longer in the repository), or stolen (replaced with a different lock). Either way, Harry can see this by asking svn status to contact the repository:

$ svn status
     K raisin.jpg
$ svn status --show-updates
     B         32   raisin.jpg
$ svn update
  B  raisin.jpg
$ svn status
$

If the repository lock was broken, then svn status --show-updates displays a B (Broken) symbol next to the file. If a new lock exists in place of the old one, then a T (sTolen) symbol is shown. Finally, svn update notices any defunct lock tokens and removes them from the working copy.

Lock Communication

We've seen how svn lock and svn unlock can be used to create, release, break, and steal locks. This satisfies the goal of serializing commit access to a file. But what about the larger problem of preventing wasted time?

For example, suppose Harry locks an image file and then begins editing it. Meanwhile, miles away, Sally wants to do the same thing. She doesn't think to run svn status --show-updates, so she has no idea that Harry has already locked the file. She spends hours editing the file, and when she tries to commit her change, she discovers that either the file is locked or that she's out-of-date. Regardless, her changes aren't mergeable with Harry's. One of these two people has to throw away their work, and a lot of time has been wasted.

Subversion's solution to this problem is to provide a mechanism to remind users that a file ought to be locked before the editing begins. The mechanism is a special property, svn:needs-lock. If that property is attached to a file (regardless of its value, which is irrelevant), then Subversion will try to use filesystem-level permissions to make the file read-only, unless, of course, the user has explicitly locked the file. When a lock-token is present (as a result of running svn lock), the file becomes read-write. When the lock is released, the file becomes read-only again.

The theory, then, is that if the image file has this property attached, then Sally would immediately notice something is strange when she opens the file for editing. Many applications alert users immediately when a read-only file is opened for editing. And nearly all applications would at least prevent her from saving changes to the file. This reminds her to lock the file before editing, whereby she discovers the pre-existing lock:

$ /usr/local/bin/gimp raisin.jpg
gimp: error: file is read-only!
$ ls -l raisin.jpg
-r--r--r--   1 sally   sally   215589 Jun  8 19:23 raisin.jpg
$ svn lock raisin.jpg
svn: Lock request failed: 423 Locked (http://svn.example.com)
$ svn info http://svn.example.com/repos/project/raisin.jpg | grep Lock
Lock Token: opaquelocktoken:fc2b4dee-98f9-0310-abf3-653ff3226e6b
Lock Owner: harry
Lock Created: 2006-06-08 07:29:18 -0500 (Thu, 08 June 2006)
Lock Comment (1 line):
Making some tweaks.  Locking for the next two hours.
$
[Подсказка]Подсказка

Users and administrators alike are encouraged to attach the svn:needs-lock property to any file which cannot be contextually merged. This is the primary technique for encouraging good locking habits and preventing wasted effort.

Note that this property is a communication tool which works independently from the locking system. In other words, any file can be locked, whether or not this property is present. And conversely, the presence of this property doesn't make the repository require a lock when committing.

Unfortunately, the system isn't flawless. It's possible that even when a file has the property, the read-only reminder won't always work. Sometimes applications misbehave and «hijack» the read-only file, silently allowing users to edit and save the file anyway. There's not much that Subversion can do in this situation—at the end of the day, there's simply no substitution for good interpersonal communication. [21]

Внешние зависимости

Иногда полезно иметь рабочую копию, собранную из разных источников. К примеру, может понадобиться, чтобы различные рабочие подкаталоги выгружались из разных каталогов хранилища, или даже из разных хранилищ. Безусловно, всё это можно сделать вручную, с помощью вызовов команды svn checkout создав рабочую копию с нужной структурой. Но, ели подобная структура требуется всем пользователям хранилища, каждому из них нужно будет повторить все те же операции по созданию рабочей копии, которые делали вы сами.

Чтобы этого избежать, Subversion обеспечивает поддержку внешних зависимостей. Внешняя зависимость является сопоставлением локального каталога к URL версионированного каталога (или к его конкретной правке). Групповое объявление внешних зависимостей делается в Subversion при помощи свойства svn:externals. Установка и редактирование этого свойства выполняется с помощью команд svn propset и svn propedit (см. «Использование свойств»). Свойство может быть установлено для любого версионированного каталога, значение свойства представляет собой таблицу с путями к подкаталогам (относительно того каталога, для которого это свойство устанавливается) и полными абсолютными URL в Subversion-хранилище.

$ svn propget svn:externals calc
third-party/sounds             http://sounds.red-bean.com/repos
third-party/skins              http://skins.red-bean.com/repositories/skinproj
third-party/skins/toolkit -r21 http://svn.red-bean.com/repos/skin-maker

Удобство свойства svn:external заключается в том, что после его задания для версионированного каталога все, кто будет создавать рабочую копию с этим каталогом, получат возможность пользоваться преимуществами внешней зависимости. Другими словами, после того как кто-то из участников проекта обозначил необходимую структуру рабочей копии, больше никому не придется об этом беспокоиться — при создании рабочей копии Subversion, кроме оригинальных данных, сделает рабочие копии данных, определенных как внешние зависимости.

Посмотрите на предыдущий пример с внешними зависимостями. Когда кто-нибудь будет создавать рабочую копию каталога calc, Subversion создаст, в том числе, и копии элементов, определенных как внешние зависимости.

$ svn checkout http://svn.example.com/repos/calc
A  calc
A  calc/Makefile
A  calc/integer.c
A  calc/button.c
Checked out revision 148.

Fetching external item into calc/third-party/sounds
A  calc/third-party/sounds/ding.ogg
A  calc/third-party/sounds/dong.ogg
A  calc/third-party/sounds/clang.ogg
…
A  calc/third-party/sounds/bang.ogg
A  calc/third-party/sounds/twang.ogg
Checked out revision 14.

Fetching external item into calc/third-party/skins
…

Если необходимо изменить внешние зависимости, сделать это можно с помощью обычных команд редактирования свойств. После того как вы зафиксируете изменения свойства svn:externals, при следующем запуске svn update Subversion синхронизирует существующие копии элементов в соответствии с внесенными во внешние зависимости изменениями. Тоже самое произойдет и когда другие участники проекта обновят свои рабочие копии и получат изменения во внешних зависимостях.

[Подсказка]Подсказка

Учитывая, что свойство svn:externals имеет многострочное значение, крайне рекомендуется вместо команды svn propset использовать svn propedit.

[Подсказка]Подсказка

Вам стоит всерьез подумать про использование явно указанного номера правки для всех внешних зависимостей. Поступая таким образом, вы сможете выбирать момент перехода на другой снимок внешней информации и явно указывать какой это будет снимок. Кроме того что это позволяет избежать получения неожиданных изменений из сторонних хранилищ, которые вы, возможно, никак не контролируете, явное указание номера правки означает, что откат вашей рабочей копии к более ранней правке приведет к откату и для внешних зависимостей, к тому состоянию, в котором они были в той, предыдущей, правке, то есть это значит, что внешние рабочие копии будут выглядеть так, как они выглядели на момент той правки вашего хранилища. Для программных проектов это может быть вопросом удачной или неудачной сборки старого снимка сложной и запутанной базы программного кода.

Команда svn status умеет определять внешние зависимости, показывая код статуса X для подкаталогов, выгруженных из внешних зависимостей, и рекурсивно проходя по этим подкаталогам для отображения статуса самих внешних элементов.

Вместе с тем, текущая реализация поддержки внешних зависимостей в Subversion может вводить в заблуждение. Во-первых, внешние зависимости могут указывать только на папки, но не на файлы. Во-вторых, внешние зависимости не могут указывать на относительные пути (например, такие как ../../skins/myskin). В-третьих, рабочие копии, созданные через внешние зависимости, являются оторванными от первичной рабочей копии (от того каталога, для которого установлено свойство svn:externals). А Subversion полноценно работает только на неотсоединенных рабочих копиях. Это означает, что если вы захотите зафиксировать изменения, сделанные в одной или нескольких таких рабочих копиях, вам придется принудительно выполнять команду svn commit для этих рабочих копий — фиксация в первичной рабочей копии не распространяется на внешние зависимости.

Кроме того, поскольку зависимости используют абсолютные URL, перемещение или копирование папки, к которой они присоединены, не будет влиять на то, что будет выгружаться из хранилища в виде внешней зависимости (при этом, локальные подкаталоги, назначенные как целевые для внешних зависимостей, при переименовании родительского каталога будут, естественно, перемещены вместе с ним). В определенных ситуациях это может сбивать с толку и запутывать. Например, у вас есть корневой каталог my-project и для одного из его подкаталогов (my-project/some-dir) вы назначаете внешнюю зависимость, отслеживающую изменения другого подкаталога (my-project/external-dir).

$ svn co http://svn.example.com/projects .
A    my-project
A    my-project/some-dir
A    my-project/external-dir
…
Fetching external item into 'my-project/some-dir/subdir'
Checked out external at revision 11.

Checked out revision 11.
$ svn pget svn:externals my-project/some-dir
subdir http://svn.example.com/projects/my-project/external-dir

$

Переименуем с помощью команды svn move каталог my-project. Теперь внешние зависимости продолжают продолжают указывать на путь в каталоге my-project, а самого этого каталога уже не существует.

$ svn mv -q my-project renamed-project
$ svn ci -m "Rename my-project to renamed-project."
Deleting       my-project
Adding         my-renamed-project

Committed revision 12.
$ svn up

Fetching external item into 'renamed-project/some-dir/subdir'
svn: Target path does not exist
$

Тот факт, что внешние зависимости используют абсолютные URL, может вызвать проблемы при работе с хранилищами, доступными через несколько URL-схем. Интересная проблема может возникнуть, если, например, сервер Subversion позволяет любому пользователю создать рабочую копию, подключившись через http:// или https://, а фиксации позволяет выполнять только через https://. Если внешние зависимости используют http:// вариант URL хранилища, то для рабочих копий, созданных для этих внешних зависимостей, нельзя будет выполнить фиксацию изменений. С другой стороны, если использовался https:// вариант URL, то пользователи, которые создают рабочую копию через http:// потому, что их клиент не поддерживает https://, не смогут получить внешние элементы. Обратите внимание и на то, что при переопределении рабочей копии (с помощью команды svn --relocate) внешние зависимости не будут переопределены.

Наконец, могут быть ситуации, в которых предпочтительно, чтобы подкоманды svn не идентифицировали и не оперировали рабочими копиями, созданными как внешние зависимости. Для таких случаев при вызове подкоманды можно использовать параметр --ignore-externals.

Стержневые и оперативные правки

Мы постоянно копируем, перемещаем, переименовываем и полностью заменяем файлы и каталоги на наших компьютерах. И вашей системе управления версиями вовсе не обязательно знать, каким образом вы производите эти операции с файлами и каталогами, находящимися под версионным контролем. Поддержка управления файлами в Subversion очень либеральна, она допускает такую гибкость при работе с версионированными файлами, какая доступна для неверсионированных файлов. Но такая гибкость означает, что на протяжении жизненного цикла вашего хранилища определенный версионированный объект может иметь различные пути, и, напротив, определенный путь может указывать на различные, совершенно не связанные версионированные объекты. Такое положение дел вносит определенные сложности в ваше взаимодействие с этими путями и объектами.

Subversion весьма сообразителен в отслеживании ситуаций, когда история версий объекта включает подобные «изменения адреса». Например, если вы запросите журнал истории правок конкретного файла, который был переименован на прошлой неделе, Subversion предоставит его вам без всяких проблем. В нем будут отмечены правка, в которой произошло переименование, а также журнал правок, имеющих отношение к объекту и произошедших как до, так и после переименования. Таким образом, чаще всего вам даже не придется задумываться о таких вещах. Но иногда Subversion все-таки потребуется ваша помощь, чтобы устранить неоднозначности.

Простейшим примером может служить ситуация, когда каталог или файл сначала удаляют из версионного контроля, а затем создают новый элемент с тем же именем и добавляют его под версионный контроль. Безусловно, то, что вы удалили и то, что вы впоследствии добавили — это разные вещи. Просто так получилось, что они имеют одинаковый путь, например /trunk/object. Что должен выдать Subversion, когда вы запросите у него историю /trunk/object? Имеете ли вы ввиду то, что находится по этому пути в текущий момент, или тот старый объект, который вы удалили? Спрашиваете ли вы об операциях, совершенных со всеми объектами, которые когда-либо располагались по этому пути? Очевидно, Subversion требуется подсказка о том, что же вы действительно хотите получить.

Благодаря перемещениям история версионированного объекта может получиться гораздо более извилистой, чем в только что рассмотренном примере. Допустим, что у вас есть каталог с именем concept, содержащий недавно начатый проект разработки программы, с которым вы усиленно экспериментируете. В один прекрасный момент этот проект дорастет до того, что вы признаете идею действительно стоящей и ценой неимоверных усилий все-таки решите дать проекту имя. [22] Допустим, вы назвали вашу программу Frabnaggilywort. При этом не помешало бы переименовать каталог, чтобы он отражал новое имя проекта, поэтому concept переименовывается в frabnaggilywort. Жизнь идет дальше, выпускается версия Frabnaggilywort 1.0, она доступна для скачиванися и ежедневно используется кучей людей, жаждущих улучшить свою жизнь.

Это действительно хорошая история — но она на этом не заканчивается. У такого предприимчивого человека как вы в голове уже родилась новая идея. Поэтому вы создаете новый каталог с именем concept, и цикл начинается снова. На самом деле, этот цикл с годами повторяется многократно, каждый раз начинаясь со старого каталога concept, который впоследствии иногда переименовывается (когда идея оказывается хороша), а иногда удаляется (когда идея оказывается неудачной). Чтобы совсем запутаться, предположим, что вы сначала переименовали concept во что-то еще, а впоследствии по какой-то причине переименовали его обратно в concept.

При возникновении подобных ситуаций пытаться объяснить Subversion, как работать с этими многократно используемыми путями — все равно что сказать автомобилисту в западных пригородах Чикаго, чтобы он ехал на восток вниз по Roosevelt Road, а затем повернул налево на Main Street. Меньше чем за двадцать минут можно пересечь «Main Street» в Уитоне, Глен Эллине и Ломбарде. И это будут три разных улицы. Нашему автомобилисту, как и Subversion, нужно больше подробностей, чтобы поступить правильно.

Начиная с версии 1.1, Subversion позволяет вам точно указать, какую именно Main Street вы имеете ввиду. Для этого используется так называемая стержневая правка (peg revision) — то есть правка, указываемая Subversion исключительно для того, чтобы однозначно идентифицировать отдельную линию в истории. Поскольку в любой конкретный момент времени (или, говоря точнее, в любой конкретной правке) определенному пути может соответствовать не более одного версионированного объекта, комбинации пути и стержневой правки достаточно для однозначной ссылки на определенную линию в истории. Для указания стержневых правок в клиенте Subversion с интерфейсом командной строки используется at-синтаксис, который получил такое название, потому что включает добавление «символа at» (@) и номера стержневой правки после пути, который связан с данной правкой.

Ну а как же параметр --revision (-r), о котором мы так много говорили в этой книге? Эта правка (или множество правок) называется оперативной правкой (или диапазоном оперативных правок). Идентифицировав конкретную линию в истории с помощью пути и стержневой правки, Subversion выполняет требуемые операции, используя оперативную правку (или правки). Возвращаясь к нашей аналогии с улицами Чикаго, если нам объясняют, как проехать к дому 606 N. по Main Street в Уитоне, [23] мы можем рассматривать «Main Street» как путь и «Уитон» как стержневую правку. Эти два элемента информации однозначно идентифицируют путь, по которому нам следует ехать (на север или на юг Main Street), и позволяет нам избежать поездок верх и вниз по неправильным Main Street в поиске точки назначения. Далее мы рассматриваем «606 N.» как своего рода оперативную правку, и мы точно знаем, куда нам ехать.

Допустим, что хранилище создано давным давно, и в правке 1 была добавлен наш первый каталог concept, а также файл IDEA внутри этого каталога, содержащий описание концепции. После нескольких правок, в которых добавлялся и изменялся реальный программный код, в правке 20 мы переименовали этот каталог в frabnaggilywort. В правке 27 у нас появилась новая идея, для которой мы создали новый каталог concept и новый файл IDEA с описание наших мыслей. Спустя пять лет и двадцать тысяч правок они будут уже частью одной древней истории.

Теперь, спустя годы, мы интересуемся, как же выглядел файл IDEA в правке 1. Но Subversion нужно знать, спрашиваем ли мы о том, как выглядел в правке 1 текущий файл, или интересуемся содержанием того файла, который когда-то, в правке 1 имел путь concepts/IDEA? Эти вопросы, конечно же, будут иметь разные ответы, и благодаря стержневым правкам мы можем задать оба из них. Чтобы найти, как выглядел в той старой правке текущий файл IDEA, мы выполним такую команду:

$ svn cat -r 1 concept/IDEA 
svn: Unable to find repository location for 'concept/IDEA' in revision 1

Конечно же, в данном примере, текущего файла IDEA в правке 1 еще не было и в помине, поэтому Subversion выдаст ошибку. Вышеприведенная команда — это сокращение более длинной записи, включающей явную ссылку на стержневую правку. Расширенная запись будет выглядеть так:

$ svn cat -r 1 concept/IDEA@BASE
svn: Unable to find repository location for 'concept/IDEA' in revision 1

Ее выполнение приведет к тому же ожидаемому результату. Стержневой правкой по умолчанию считается BASE (правка, представленная в текущий момент в вашей рабочей копии) при указании путей рабочей копии, и HEAD при указании URL-адресов.

Проницательный читатель, вероятно, поинтересуется, как же быть с at-синтаксисом в случае, если пути рабочей копии или URL сами по себе содержат символ at. Откуда svn узнает, является ли news@11 именем каталога в моей файловой структуре, или же синтаксисом для «правки 11 каталога news»? К счастью, хотя svn предполагает последнее, существует тривиальный обходной прием. Нужно всего лишь добавить символ at в конец пути, записав его как news@11@. svn обращает внимание только на последний символ at в аргументе и не считaет ошибкой, если вы опустите указание стержневой правки после символа at. Этот обходной прием применим даже к путям, которые оканчиваются символом at — укажите filename@@, чтобы сослаться на файл с именем filename@.

Давайте зададимся теперь вторым вопросом — какого было в правке 1 содержание файла, располагавшегося по адресу concepts/IDEA? Получить ответ нам поможет явное указание стержневой правки.

$ svn cat concept/IDEA@1
The idea behind this project is to come up with a piece of software
that can frab a naggily wort.  Frabbing naggily worts is tricky
business, and doing it incorrectly can have serious ramifications, so
we need to employ over-the-top input validation and data verification
mechanisms.

Заметьте, что на этот раз мы не указали оперативную правку. Это возможно, поскольку при отсутствии указания на оперативную правку Subversion по умолчанию предполагает, что она такая же, как и стержневая правка.

Судя по выведенному тексту файла, это именно то, что мы ожидали получить. В тексте даже упоминается frabbing naggily worts, так что почти наверняка этот файл описывает программу, называющуюся теперь Frabnaggilywort. Мы можем в этом удостовериться, явно указав и стержневую, и оперативную правки. Нам известно, что в правке HEAD проект Frabnaggilywort располагается в каталоге frabnaggilywort. Поэтому мы укажем, что хотим увидеть, как выглядела в правке 1 та линия истории, которая идентифицируется в HEAD как путь frabnaggilywort/IDEA.

$ svn cat -r 1 frabnaggilywort/IDEA@HEAD
The idea behind this project is to come up with a piece of software
that can frab a naggily wort.  Frabbing naggily worts is tricky
business, and doing it incorrectly can have serious ramifications, so
we need to employ over-the-top input validation and data verification
mechanisms.

И стержневая, и оперативная правки не обязательно должны быть столь тривиальными. Предположим, что frabnaggilywort удален из HEAD, но при этом нам известно, что он существовал в правке 20, и мы хотим увидеть различия для файла IDEA между правками 4 и 10. Мы можем указать стержневую правку 20 вместе с URL, по которому располагался файл IDEA проекта Frabnaggilywort в правке 20, а затем использовать 4 и 10 как указатели диапазона оперативных правок.

$ svn diff -r 4:10 http://svn.red-bean.com/projects/frabnaggilywort/IDEA@20
Index: frabnaggilywort/IDEA
===================================================================
--- frabnaggilywort/IDEA	(revision 4)
+++ frabnaggilywort/IDEA	(revision 10)
@@ -1,5 +1,5 @@
-The idea behind this project is to come up with a piece of software
-that can frab a naggily wort.  Frabbing naggily worts is tricky
-business, and doing it incorrectly can have serious ramifications, so
-we need to employ over-the-top input validation and data verification
-mechanisms.
+The idea behind this project is to come up with a piece of
+client-server software that can remotely frab a naggily wort.
+Frabbing naggily worts is tricky business, and doing it incorrectly
+can have serious ramifications, so we need to employ over-the-top
+input validation and data verification mechanisms.

К счастью, большинство людей не сталкивается со столь сложными ситуациями. Но если такое все-таки случится, помните, что стержневые правки — это дополнительная подсказка, которая нужна Subversion для устранения неоднозначности.




[13] Если вы знакомы с XML, то синтаксис XML "Name" допускает практически то же подмножество символов ASCII.

[14] Исправление в лог-сообщениях орфографических, грамматических ошибок, «просто ошибочных» записей — наверное, самый распространенный случай использования параметра --revprop.

[15] Вы думаете, это всё? В тот же самый период времени WordPerfect также предпочитал использовать расширение .DOC для своего собственного закрытого формата файлов!

[16] Для указания исполняемых файлов файловая система Windows использует расширения файлов (а именно .EXE, .BAT и .COM).

[17] Это все, что создает система сборки?

[18] … или даже, возможно, параграф в книге …

[19] Communication wouldn't have been such bad medicine for Harry and Sally's Hollywood namesakes, either, for that matter.

[20] Subversion does not currently allow locks on directories.

[21] Except, perhaps, a classic Vulcan mind-meld.

[22] «You're not supposed to name it. Once you name it, you start getting attached to it.» — Mike Wazowski

[23] 606 N. Main Street, Wheaton, Illinois, is the home of the Wheaton History Center. Get it—«History Center»? It seemed appropriate….

Глава 4. Ветвление и слияние

Ветвление, назначение меток и слияние — это понятия, свойственные практически всем системам управления версиями. Если вы плохо знакомы с этими понятиями, то в этой главе вы с ними обстоятельно познакомитесь. Если эти понятия вам уже знакомы, то мы надеемся, что вам будет интересно узнать, как эти идеи реализованы в Subversion.

Ветвление — фундаментальное понятие управления версиями. Если вы собираетесь доверить Subversion управление своей информацией, то это именно та функция, от которой вы впоследствии будете сильно зависеть. Материал данной главы предполагает, что вы уже знакомы с основными понятиями Subversion (Глава 1, Фундаментальные понятия).

Что такое ветка?

Предположим, что ваша работа заключается в сопровождении документа (например, какого-то руководства) для подразделений вашей компании. Однажды различные подразделения запросят у вас одно и то же руководство, но при этом в несколько «адаптированном» для них варианте, поскольку работа каждого подразделения имеет свою специфику.

Как быть в такой ситуации? Скорее всего, вы создадите вторую копию документа и начнёте отдельно сопровождать обе копии. Когда какое-то из подразделений попросит вас внести небольшие изменения, вы включите их либо в первую копию, либо во вторую.

Чаще всего вам придется вносить изменения в обе копии. Например, если вы обнаружите опечатку в одной копии, скорее всего, эта же опечатка будет присутствовать и в другой. Два документа, в общем-то, почти одинаковы — их различия сводятся к отдельным специфичным моментам.

В этом заключается основная идея ветки — то есть направления разработки, которое существует независимо от другого направления, но имеет с ним общую историю, если заглянуть немного в прошлое. Ветка всегда берет начало как копия чего-либо и движется от этой точки, создавая свою собственную историю (см. Рисунок 4.1, «Ветки разработки»).

Рисунок 4.1. Ветки разработки

Ветки разработки


В Subversion есть команды, которые помогают сопровождать параллельные ветки файлов и каталогов. Они позволяют создавать ветки, копируя данные и запоминая, что копии связаны друг с другом. Кроме того, эти команды помогают дублировать изменения из одной ветки в другую. Наконец, они могут сделать так, что отдельные части рабочей копии будут отражать состояние различных веток, что позволит вам «смешивать и согласовывать» различные линии разработки в своей каждодневной работе.

Использование веток

К этому моменту вы должны понимать, что в хранилище при каждой фиксации создается полностью новое дерево файлов (называемое «правка»). Если нет, то вернитесь назад и прочитайте о правках в разделе «Правки».

В этой главе мы воспользуемся тем же примером, что и в Глава 1, Фундаментальные понятия. Как вы помните, вы и ваш соразработчик Салли совместно используете хранилище, содержащее два проекта, paint и calc. Как отмечалось в Рисунок 4.2, «Начальная структура хранилища», каждый каталог проекта содержит подкаталоги с именами trunk и branches. Назначение этих каталогов вскоре станет понятно.

Рисунок 4.2. Начальная структура хранилища

Начальная структура хранилища


Как и раньше, предположим, что и Салли, и вы имеете рабочие копии проекта «calc». Точнее, каждый из вас имеет рабочую копию /calc/trunk. Все файлы, относящиеся к проекту, находятся в этом подкаталоге, а не прямо в /calc, потому что ваша команда решила размещать «главную линию» разработки в /calc/trunk.

Допустим, перед вами была поставлена задача коренной реорганизации проекта. Это займет много времени и затронет все файлы проекта. Проблема заключается в том, что вы не хотите мешать Салли, которая прямо сейчас занимается исправлением небольших ошибок. Ее работа зависит от постоянной доступности последней версии проекта (каталога /calc/trunk). Если вы начнете пошагово фиксировать свои изменения, вы конечно же смешаете Салли все карты.

Одним из вариантов является временная изоляция: вы и Салли перестаете делиться информацией на неделю или две. В это время вы начинаете перелопачивать и реорганизовывать файлы рабочей копии, но не фиксируете и не обновляете ее до завершения работы над задачей. Однако, в этом случае появляется несколько проблем. Во-первых, это не очень надежно. Большинство людей предпочитают часто сохранять свою работу в хранилище на случай, если с рабочей копией вдруг случится что-то плохое. Во-вторых, это не достаточно гибко. Если вы работаете на разных компьютерах (к примеру, если рабочая копия /calc/trunk есть у вас на двух разных машинах), вам придется вручную копировать изменения туда и обратно, либо делать всю работу на одном компьютере. С другой стороны, вам трудно делиться вносимыми изменениями с кем-то еще. А предоставление возможности знакомиться с проделанной вами работой по мере ее продвижения считается «наилучшей практикой» при разработке любого программного обеспечения. Если никто не будет видеть ваших промежуточных фиксаций, вы теряете потенциал обратной связи. Наконец, когда вы закончите свои изменения, может выясниться, что слить проделанную вами работу с остальным программным кодом компании чрезвычайно трудно. Салли (или кто-то другой) могла внести такие изменения в хранилище, которые трудно совместить с вашей рабочей копией — особенно, если вы выполните svn update впервые после нескольких недель изоляции.

Наилучшим решением будет создание в хранилище вашей собственной ветки, или направления разработки. Это позволит вам сохранять наполовину поломанную работу сколь угодно часто, не пересекаясь с другими, и кроме того, вы сможете выборочно делиться информацией с другими коллегами. Дальше вы увидите, как всё это работает.

Создание ветки

Создать ветку очень просто — при помощи команды svn copy в хранилище создается копия проекта. Subversion может копировать не только отдельные файлы, но и целые каталоги. Итак, вам нужно сделать копию каталога /calc/trunk. Где должна лежать эта новая копия? Где угодно — этот вопрос определяется правилами проекта. Допустим, что по правилам вашей команды ветки создаются в каталоге /calc/branches хранилища, и вы хотите назвать свою ветку my-calc-branch. Тогда вам следует создать новый каталог /calc/branches/my-calc-branch, который будет копией /calc/trunk.

Копию можно создать двумя различными способами. Сперва мы покажем более длинный способ, просто для того, что бы пояснить суть идеи. Для начала создадим рабочую копию корневого каталога проекта /calc:

$ svn checkout http://svn.example.com/repos/calc bigwc
A  bigwc/trunk/
A  bigwc/trunk/Makefile
A  bigwc/trunk/integer.c
A  bigwc/trunk/button.c
A  bigwc/branches/
Checked out revision 340.

Теперь, чтобы создать копию, достаточно просто передать два пути в пределах рабочей копии команде svn copy:

$ cd bigwc
$ svn copy trunk branches/my-calc-branch
$ svn status
A  +   branches/my-calc-branch

В результате команда svn copy рекурсивно копирует рабочий каталог trunk в новый рабочий каталог branches/my-calc-branch. Теперь команда svn status покажет, что новый каталог запланирован для добавления в хранилище. Обратите внимание на знак «+» после буквы А. Он означает, что запланированное для добавления представляет собой какую-то копию, а не что-то новое. При следующей фиксации Subversion создаст в хранилище каталог /calc/branches/my-calc-branch, скопировав его из /calc/trunk вместо того, чтобы повторно отправлять по сети всю информацию рабочей копии:

$ svn commit -m "Creating a private branch of /calc/trunk."
Adding         branches/my-calc-branch
Committed revision 341.

А теперь покажем простой способ создания ветки, о котором мы упоминали раньше: команда svn copy может оперировать двумя URL-адресами напрямую.

$ svn copy http://svn.example.com/repos/calc/trunk \
           http://svn.example.com/repos/calc/branches/my-calc-branch \
      -m "Creating a private branch of /calc/trunk."

Committed revision 341.

В сущности, между этими двумя методами нет разницы. Оба варианта создают в правке 341 новый каталог, и этой новый каталог является копией /calc/trunk. Это показывает Рисунок 4.3, «Хранилище, содержащее новую копию». Обратите внимание на то, что второй метод, кроме всего прочего, выполняет немедленную фиксацию. [24]Эта процедура более проста в использовании, так как нет необходимости в выгрузке в рабочую копию значительного объема данных из хранилища. По сути, в этом случае можно вовсе не иметь рабочей копии.

Рисунок 4.3. Хранилище, содержащее новую копию

Хранилище, содержащее новую копию


Работа с веткой

После создания ветки проекта можно загрузить новую рабочую копию и приступить к работе с ней:

$ svn checkout http://svn.example.com/repos/calc/branches/my-calc-branch
A  my-calc-branch/Makefile
A  my-calc-branch/integer.c
A  my-calc-branch/button.c
Checked out revision 341.

В этой рабочей копии нет ничего особенного; это просто зеркало другого каталога хранилища. Однако, если Салли обновит свою рабочую копию, она не увидит там ваших изменений. Рабочая копия Салли создана из каталога /calc/trunk. (Смотрите далее в этой главе раздел «Переключение рабочей копии»: команда svn switch является альтернативным способом создания рабочей копии ветки.)

Предположим, что за неделю были сделаны следующие фиксации:

  • Вы внесли изменения в /calc/branches/my-calc-branch/button.c, создав таким образом правку 342.

  • Вы внесли изменения в /calc/branches/my-calc-branch/integer.c, создав правку 343.

  • Салли внесла изменения в /calc/trunk/integer.c, создав правку 344.

Теперь у файла integer.c есть два независимых направления разработки, что демонстрирует Рисунок 4.4, «История ветвления для одного файла».

Рисунок 4.4. История ветвления для одного файла

История ветвления для одного файла


Если посмотреть историю изменений, сделанных в вашей копии integer.c, можно увидеть интересные вещи:

$ pwd
/home/user/my-calc-branch

$ svn log --verbose integer.c
------------------------------------------------------------------------
r343 | user | 2002-11-07 15:27:56 -0600 (Thu, 07 Nov 2002) | 2 lines
Changed paths:
   M /calc/branches/my-calc-branch/integer.c

* integer.c:  frozzled the wazjub.

------------------------------------------------------------------------
r341 | user | 2002-11-03 15:27:56 -0600 (Thu, 07 Nov 2002) | 2 lines
Changed paths:
   A /calc/branches/my-calc-branch (from /calc/trunk:340)

Creating a private branch of /calc/trunk.

------------------------------------------------------------------------
r303 | sally | 2002-10-29 21:14:35 -0600 (Tue, 29 Oct 2002) | 2 lines
Changed paths:
   M /calc/trunk/integer.c

* integer.c:  changed a docstring.

------------------------------------------------------------------------
r98 | sally | 2002-02-22 15:35:29 -0600 (Fri, 22 Feb 2002) | 2 lines
Changed paths:
   M /calc/trunk/integer.c

* integer.c:  adding this file to the project.

------------------------------------------------------------------------

Обратите внимание на то, что Subversion полностью прослеживает всю историю ветки integer.c во времени, в том числе пересекая точку создания копии. Создание ветки показано как событие в истории, потому что файл integer.c был неявно скопирован при копировании всего каталога /calc/trunk/. Теперь давайте посмотрим, какой результат выдаст такая же команда для Салли:

$ pwd
/home/sally/calc

$ svn log --verbose integer.c
------------------------------------------------------------------------
r344 | sally | 2002-11-07 15:27:56 -0600 (Thu, 07 Nov 2002) | 2 lines
Changed paths:
   M /calc/trunk/integer.c

* integer.c:  fix a bunch of spelling errors.

------------------------------------------------------------------------
r303 | sally | 2002-10-29 21:14:35 -0600 (Tue, 29 Oct 2002) | 2 lines
Changed paths:
   M /calc/trunk/integer.c

* integer.c:  changed a docstring.

------------------------------------------------------------------------
r98 | sally | 2002-02-22 15:35:29 -0600 (Fri, 22 Feb 2002) | 2 lines
Changed paths:
   M /calc/trunk/integer.c

* integer.c:  adding this file to the project.

------------------------------------------------------------------------

Салли увидит свои собственные изменения в правке 344, а ваши, сделанные в правке 343 — нет. Subversion позаботилась о том, чтобы эти две фиксации затронули разные файлы, имеющие разное расположение в хранилище. Тем не менее, Subversion будет показывать то, что два файла имеют общую историю. До создания ветки-копии в правке 341 это был один файл. Поэтому и вы, и Салли видите изменения, сделанные в правках 303 и 98.

Ключевые идеи, стоящие за ветками

Из этого раздела вы должны запомнить две вещи.

  1. В отличие от многих других систем управления версиями, в хранилище Subversion ветки существуют не в отдельном измерении, а как обычные каталоги файловой системы. Эти каталоги отличаются только тем, что несут дополнительную информацию о своей истории.

  2. Subversion не имеет такого понятия как ветка — есть только копии. Копия каталога становится «веткой» только потому, что вы рассматриваете ее таким образом. Вы можете по-разному думать о каталоге, по разному его трактовать, но для Subversion это не более чем обычный каталог, созданный в результате копирования.

Копирование изменений между ветками

Теперь вы и Салли работаете над параллельными ветками проекта: вы — над своей собственной веткой, а Салли — над главной линией разработки (каталог trunk).

В проектах со значительным числом участников, как правило, большинство работает в главной линии разработки. Когда кому-то необходимо сделать изменения, которые займут много времени и могут нарушить главную линию, стандартной практикой является создание отдельной ветки и фиксация всех изменений в ней — до тех пор, пока работа не будет полностью завершена.

Положительным моментом здесь является то, что вы и Салли не пересекаетесь друг с другом. Но есть и минус — вы можете разойтись слишком далеко друг относительно друга. Помните, что одна из проблем такой стратегии «временной изоляции» заключается в том, что к моменту, когда вы завершите работу со своей веткой, может оказаться практически невозможным объединить ее с главной линией без огромного количества конфликтов.

Вместо этого вы и Салли можете продолжать делиться изменениями по ходу работы. Вы можете решать вплоть до отдельного изменения, стоит ли им делиться — Subversion предоставляет возможность выборочного «копирования» изменений между ветками. А тогда, когда вы полностью закончите работу со своей веткой, вы можете скопировать обратно в основную ветку все изменения полностью.

Копирование отдельных изменений

В предыдущем разделе мы отметили, что и вы, и Салли, одновременно, в разных ветках вносите изменения в файл integer.c. Если посмотреть на лог-сообщение Салли для правки 344, вы увидите, что она исправила несколько орфографических ошибок. Конечно же, в вашей копии этого файла эти ошибки остались. Не исключено, что ваши будущие изменения этого файла коснутся областей, содержащих эти орфографические ошибки, и таким образом вы получите несколько потенциальных конфликтов при последующем объединении вашей ветки. Поэтому лучше получить изменения от Салли сейчас, до того, как вы начнете вплотную работать с этой частью файла.

Настал момент воспользоваться командой svn merge. Эта команда, оказывается, является очень близким родственником команды svn diff (о которой вы читали в Глава 2, Экскурсия по Subversion). Обе команды способны сравнивать любые два объекта в хранилище и показывать различия. Например, вы можете попросить svn diff показать все изменения, сделанные Салли в правке 344:

$ svn diff -r 343:344 http://svn.example.com/repos/calc/trunk

Index: integer.c
===================================================================
--- integer.c (revision 343)
+++ integer.c (revision 344)
@@ -147,7 +147,7 @@
     case 6:  sprintf(info->operating_system, "HPFS (OS/2 or NT)"); break;
     case 7:  sprintf(info->operating_system, "Macintosh"); break;
     case 8:  sprintf(info->operating_system, "Z-System"); break;
-    case 9:  sprintf(info->operating_system, "CPM"); break;
+    case 9:  sprintf(info->operating_system, "CP/M"); break;
     case 10:  sprintf(info->operating_system, "TOPS-20"); break;
     case 11:  sprintf(info->operating_system, "NTFS (Windows NT)"); break;
     case 12:  sprintf(info->operating_system, "QDOS"); break;
@@ -164,7 +164,7 @@
     low = (unsigned short) read_byte(gzfile);  /* read LSB */
     high = (unsigned short) read_byte(gzfile); /* read MSB */
     high = high << 8;  /* interpret MSB correctly */
-    total = low + high; /* add them togethe for correct total */
+    total = low + high; /* add them together for correct total */

     info->extra_header = (unsigned char *) my_malloc(total);
     fread(info->extra_header, total, 1, gzfile);
@@ -241,7 +241,7 @@
      Store the offset with ftell() ! */

   if ((info->data_offset = ftell(gzfile))== -1) {
-    printf("error: ftell() retturned -1.\n");
+    printf("error: ftell() returned -1.\n");
     exit(1);
   }

@@ -249,7 +249,7 @@
   printf("I believe start of compressed data is %u\n", info->data_offset);
   #endif

-  /* Set postion eight bytes from the end of the file. */
+  /* Set position eight bytes from the end of the file. */

   if (fseek(gzfile, -8, SEEK_END)) {
     printf("error: fseek() returned non-zero\n");

Команда svn merge ведет себя практически идентично. Но вместо вывода различий на терминал она применяет их к рабочей копии в виде локальных изменений:

$ svn merge -r 343:344 http://svn.example.com/repos/calc/trunk
U  integer.c

$ svn status
M  integer.c

Вывод команды svn merge показывает, что к вашей копии integer.c был применен патч. Теперь она содержит изменения Салли — они были «скопированы» из главной линии разработки в вашу рабочую копию, вашу собственную ветку, и теперь существуют в виде локальных изменений. С этого момента вы можете просмотреть локальные изменения и убедиться в том, что они корректны.

Возможна ситуация, когда не все будет так хорошо и integer.c окажется в состоянии конфликта. Тогда вам будет необходимо разрешить конфликт обычным путем (см. Глава 2, Экскурсия по Subversion), либо, если вы придете к мнению, что объединение было плохой идеей, просто отказаться от него, отменив локальные изменения командой svn revert.

Просмотрев результат объединения исправлений, его можно зафиксировать как обычно (svn commit). После этого изменения будут внесены в вашу ветку хранилища. В терминологии управления версиями такую процедуру копирования изменений между ветками обычно называют портированием изменений.

При фиксации локальных изменений убедитесь, что в лог-сообщении упоминается о портировании отдельных изменений из одной ветки в другую. Например:

$ svn commit -m "integer.c: ported r344 (spelling fixes) from trunk."
Sending        integer.c
Transmitting file data .
Committed revision 360.

Как вы увидите в последующих разделах, очень важно следовать этой «хорошей практике».

Небольшое предупреждение: несмотря на то, что svn diff и svn merge по сути очень похожи, во многих случаях они используют разный синтаксис. Обязательно прочтите об этом в Глава 9, Полное справочное руководство по Subversion, или спросите у svn help. Например, svn merge требует в качестве целевого объекта путь в рабочей копии, то есть место, где ей нужно применить изменения структуры файлов. Если целевой объект не указан, предполагается, что делается попытка выполнить одну из следующих операций:

  1. объединение изменений каталога с вашим текущим рабочим каталогом;

  2. объединение изменений в конкретном файле с файлом, имеющим то же имя в текущем рабочем каталоге.

Если вы объединяете каталог и не указываете целевой путь, svn merge предполагает первый из приведенных выше вариантов и пытается применить изменения к текущему каталогу. Если вы объединяете файл, и при этом файл с таким именем есть в текущем рабочем каталоге, svn merge подразумевает второй случай и пытается применить изменения к локальному файлу с таким же именем.

Если вы хотите применить изменения к чему-то другому, вам нужно это указать. Например, если вы находитесь в родительском каталоге рабочей копии, то вам нужно указать целевой каталог, получающий изменения:

$ svn merge -r 343:344 http://svn.example.com/repos/calc/trunk my-calc-branch
U   my-calc-branch/integer.c

Ключевые идеи, стоящие за слиянием

Теперь, после знакомства с примерами использования svn merge, настала пора разобраться в них поглубже. Если вы чувствуете неуверенность в том как, собственно, работает слияние, то вы в этом вы не одиноки. Многие пользователи (особенно те, для которых управление версиями в новинку) поначалу путаются в правильности записи этой команды и в том, как и когда эту функцию следует использовать. Отбросьте страх — на самом деле эта команда намного проще, чем вы думаете! Понять, как именно ведет себя svn merge, очень просто.

В ступор вводит, главным образом, название команды. Термин «слияние» как бы указывает на то, что ветки соединяются вместе, или происходит какое-то волшебное смешивание данных. На самом деле это не так. Пожалуй, этой команде лучше бы подощло название svn diff-and-apply, поскольку это всё, что в результате происходит: сравниваются два файловых дерева хранилища, а различия переносятся в рабочую копию.

Команда принимает три аргумента:

  1. Начальное дерево хранилища (как правило, называемое левой частью при сравнении),

  2. Конечное дерево хранилища (как правило называемое правой частью при сравнении),

  3. Рабочую копию, к которой отличия применяются в виде локальных изменений (как правило, называемую целью слияния).

Когда эти три аргумента указаны, производится сравнение двух деревьев, а полученные различия применяются к целевой рабочей копии в виде локальных изменений. После выполнения этой команды результат будет так же, как в случае, если бы вы вручную редактировали файлы или многократно выполняли команды svn add или svn delete. Если результат вас устраивает, его можно зафиксировать. Если результат вас не устраивает, просто отмените (svn revert) все сделанные изменения.

Синтаксис svn merge позволяет указывать эти три аргумента довольно гибко. Вот несколько примеров:

      
$ svn merge http://svn.example.com/repos/branch1@150 \
            http://svn.example.com/repos/branch2@212 \
            my-working-copy

$ svn merge -r 100:200 http://svn.example.com/repos/trunk my-working-copy

$ svn merge -r 100:200 http://svn.example.com/repos/trunk

В первом варианте все три аргумента указаны явно — каждое дерево задано в форме URL@REV и указана целевая рабочая копия. Второй вариант может использоваться для краткости записи в ситуациях, когда сравниваются две разных правки по одному и тому же URL. Последний вариант демонстрирует возможность не указывать целевую рабочую копию, при этом по умолчанию используется текущий каталог.

Как правильнее всего использовать слияние

Ручной контроль слияния

На первый взгляд объединить изменения просто, однако на практике могут возникнуть трудности. Проблема заключается в том, что при многократном объединении изменений одной ветки с другой можно непреднамеренно сделать объединение одних и тех же изменений дважды. Иногда это не вызывает проблем. При применении изменений к файлу Subversion, как правило, предупреждает о том, что файл уже содержит изменения и в этом случае не выполняет никаких действий. Однако, если уже присутствующие изменения были модифицированы, возникнет конфликт.

В идеале система управления версиями должна предотвращать повторное применение изменений к ветке. Она должна автоматически фиксировать, какие изменения уже были получены и иметь возможность перечислить их вам. Она должна использовать эту информацию для того, чтобы, насколько возможно, помочь автоматизировать слияние.

К сожалению, Subversion не такая система. Как и CVS, Subversion пока не сохраняет никакой информации об операциях слияния. При фиксации локальных изменений хранилище понятия не имеет, являются ли эти изменения результатом выполнения команды svn merge или результатом обычного ручного редактирования файлов.

Что это означает для вас как пользователя? Это означает, что до того момента, пока у Subversion не появится этой функции, вам придется контролировать слияние информации самостоятельно. Лучшим местом для этого является лог-сообщение. Как было показано в предыдущих примерах, рекомендуется, чтобы в лог-сообщении был указан конкретный номер правки (или диапазон правок), которые были слиты в вашу ветку. В этом случае вы сможете впоследствии просмотреть, какие изменения уже содержит ваша ветка, запусти команду svn log. Это позволит быть осторожнее при последующих запусках команды svn merge и избежать пересечения с уже портированными изменениями.

В следующем разделе мы на примерах рассмотрим эту методику в действии.

Предварительный просмотр результатов слияния

Поскольку результатом слияния являются локальные изменения, такая операция не является опасной. Допустив при слиянии ошибку, можно просто отменить изменения (svn revert) и попробовать еще раз.

Однако, возможна ситуация, когда рабочая копия уже содержит локальные изменения. Изменения, примененные при слиянии, будут смешаны с уже существующими, и запуск svn revert нас больше не устроит. Разделить два множества изменений будет невозможно.

В такой ситуации лучше попробовать спрогнозировать или проверить результат слияния до того, как оно произойдет. Проще всего запустить для этого svn diff с теми же аргументами, что и для svn merge. Мы уже показывали это в первом примере объединения. Другим способом предварительного просмотра может служить вызов команды слияния с опцией --dry-run:

$ svn merge --dry-run -r 343:344 http://svn.example.com/repos/calc/trunk
U  integer.c

$ svn status
#  nothing printed, working copy is still unchanged.

Опция --dry-run позволяет не применять локальные изменения к рабочей копии. Она только показывает статусы, которые имели бы файлы при реальном объединении. Это полезно для получения «сводной» информации о потенциальном слиянии в тех случаях, когда запуск svn diff выдает слишком много подробностей.

Конфликты при слиянии

Так же как и svn update, команда svn merge внедряет изменения в рабочую копию. Следовательно, она тоже может создавать конфликты. Однако конфликты, порождаемые svn merge, имеют определенные отличия, и поэтому мы их сейчас рассмотрим подробнее.

Вначале предположим, что рабочая копия не имеет локальных изменений. При обновлении (svn update) рабочей копии до конкретной правки отправляемые сервером изменения будут всегда «без проблем» внедряться в рабочую копию. Сервер создает дельту, сравнивая два дерева: виртуальный снимок рабочей копии и дерево файлов, которое вас интересует. Учитывая то, что левая часть сравнения полностью эквивалентна тому, что вы уже имеете, дельта гарантированно правильно конвертирует рабочую копию в правую часть сравнения.

Однако svn merge не дает такой гарантии, и может вести себя более непредсказуемо: пользователь может запросить сервер сравнить любые два дерева файлов, даже такие, которые не имеют отношения к рабочей копии! Из этого следует множество потенциальных человеческих ошибок. Иногда пользователи будут сравнивать два ошибочных дерева, создавая дельту, которая не сможет правильно внедриться. svn merge будет пытаться внедрить различия по максимуму, но иногда это будет невозможно. Так же как команда patch в Unix иногда жалуется на «неудачные попытки» объединения, svn merge будет жаловаться на «пропущенные цели»:

$ svn merge -r 1288:1351 http://svn.example.com/repos/branch
U  foo.c
U  bar.c
Skipped missing target: 'baz.c'
U  glub.c
C  glorb.h

$

Возможно, что в предыдущем примере файл baz.c существует в обоих сравниваемых снимках ветки и Subversion пытается применить результирующую дельту для того, чтобы изменить содержимое файла, однако в рабочей копии файл отсутствует. В любом случае сообщение «skipped» означает, что скорее всего пользователь ошибся при указании деревьев для сравнения — то есть это классическая ошибка оператора. Если это так, проще всего рекурсивно отменить все изменения, сделанные при слиянии (svn revert --recursive), сразу же после этого удалить все неверсионированные файлы и каталоги и повторно запустить svn merge с другими параметрами.

Обратите внимание на то, что в предыдущем примере в файле glorb.h возник конфликт. Откуда же он мог взяться, если ранее мы договорились, что рабочая копия не имеет локальных изменений? Опять же, пользователь мог запустить svn merge для выделения и применения к рабочей копии какой то старой дельты. В результате такая дельта может содержать изменения, которые нельзя внедрить в рабочий файл без появления проблем, даже если он не имеет локальных изменений.

Еще одно небольшое отличие между svn update и svn merge заключается в названиях файлов, создаваемых при конфликтах. В разделе «Разрешение конфликтов (при слиянии с чужими изменениями)» мы говорили о том, что при обновлении создаются файлы с названиями filename.mine, filename.rOLDREV и filename.rNEWREV. А svn merge в конфликтной ситуации создает три файла с названиями filename.working, filename.left и filename.right. Термины «left» и «right» указывают здесь на две стороны сравнения, то есть на используемые при сравнении деревья. Это разделение используемых названий поможет вам отличать конфликты, возникшие в результате обновления, от конфликтов, возникших в результате слияния.

Учитывать или игнорировать происхождение

Общаясь с разработчиками, использующими Subversion, очень часто можно услышать термин происхождение. Это слово используется для описания отношений между двумя объектами хранилища: если между ними есть связь, то говорят, что один объект происходит от другого.

Предположим, что фиксируется правка 100, в которой изменяется файл foo.c. В этом случае файл foo.c@99 является предком файла foo.c@100. С другой стороны, можно допустить, что в правке 101 вы фиксируете удаление foo.c, а затем в правке 102 добавляете новый файл с таким же именем. В таком случае может показаться, что файлы foo.c@99 и foo.c@102 имеют отношение друг к другу (у них одинаковый путь), однако на самом деле они являются полностью независимыми объектами хранилища. Они не имеют ни общей истории, ни общих «предков».

Мы обращаем на это ваше внимание, чтобы указать на важные различия между svn diff и svn merge. Первая команда игнорирует происхождение, в то время как вторая его учитывает. Например, если попросить svn diff сравнить правки 99 и 102 файла foo.c вы увидите построчное сравнение; команда diff слепо сравнивает два пути. А вот если вы попросите svn merge сравнить те же объекты, то Subversion предупредит вас о том, что они не связаны друг с другом и сначала попытается удалить старый файл, а затем добавить новый; вывод команды покажет удаление с последующим добавлением:

D  foo.c
A  foo.c

В большинстве случаев при слиянии сравниваются деревья, имеющие родственную связь и по умолчанию svn merge рассчитывает на это. Однако иногда вам будет нужно, чтобы команда merge сравнила два независимых дерева файлов. Например, вы могли импортировать два дерева, содержащие исходный код релизов программных проектов сторонних поставщиков (см. «Vendor branches»). Если попросить svn merge сравнить два эти дерева, вы увидите, что первое дерево будет полностью удалено, а затем будет полностью добавлено второе!

В подобных ситуациях нужно, чтобы команда svn merge выполняла сравнение, учитывая только пути, и не обращала внимание на отношения между файлами и каталогами. Добавьте опцию --ignore-ancestry при запуске команды слияния, после чего она будет вести себя аналогично svn diff. (И наоборот, опция --notice-ancestry заставит svn diff работать подобно команде merge.)

Типовые примеры

Ветвлением и слиянием можно пользоваться по-разному. В этом разделе описываются наиболее типичные примеры, с которыми вам придется иметь дело.

Полное объединение двух веток

Чтобы закончить с последним примером, заглянем немного вперед. Предположим, что прошло несколько дней. И в главную линию разработки, и вашу личную ветку за это время было внесено множество изменений. Допустим, что работу над своей веткой вы завершили. Новый функционал добавлен, ошибки исправлены, и теперь вы хотите объединить все изменения из своей ветки с главной линией разработки.

Как применить в этом случае svn merge? Помните о том, что эта команда сравнивает два дерева и применяет различия к рабочей копии. Следовательно, для того, чтобы было к чему применять изменения, необходимо иметь рабочую копию главной линии разработки. Будем считать, что такая, полностью обновленная копия у вас либо уже есть, либо вы ее только что создали в каталоге /calc/trunk.

Но какие именно два дерева нужно сравнивать? На первый взгляд ответ очевиден: нужно сравнить последнее дерево главной линии разработки с последним деревом вашей ветки. Однако такое предположение будет ошибочным. Это типичная ошибка большинства новичков! Поскольку svn merge работает так же как и svn diff, сравнение последней версии главной линии разработки и вашей ветки покажет изменения, сделанные не только в вашей ветке. Такое сравнение покажет слишком много изменений. Оно выведет не только то, что добавлялось в вашей ветке, но и то, что удалялось в главной линии разработки и не удалялось в вашей ветке.

Чтобы выделить только те изменения, которые были сделаны в вашей ветке, нужно сравнивать начальное и конечное состояния этой ветки. Посмотрев svn log, можно узнать, что ветка была создана в правке 341. В качестве конечного состояния ветки можно просто использовать правку HEAD. Это значит, что вам нужно сравнить правки 341 и HEAD каталога с веткой и применить различия к рабочей копии главной линии разработки.

[Подсказка]Подсказка

Для определения правки, в которой была создана ветка («базовой» правки ветки), удобно использовать параметр --stop-on-copy команды svn log. Обычно эта команда показывает все изменения, сделанные в ветке, включая те, которые были сделаны до создания ветки. Поэтому вы будете видеть и историю главной линии разработки. Параметр --stop-on-copy остановит вывод лог-сообщений, как только svn log обнаружит факт копирования или переименования целевого объекта.

$ svn log --verbose --stop-on-copy \
          http://svn.example.com/repos/calc/branches/my-calc-branch
…
------------------------------------------------------------------------
r341 | user | 2002-11-03 15:27:56 -0600 (Thu, 07 Nov 2002) | 2 lines
Changed paths:
   A /calc/branches/my-calc-branch (from /calc/trunk:340)

$

Как и ожидалось, последней строчкой эта команда выведет ту правку, в которой в результате копирования был создан каталог my-calc-branch.

Теперь мы можем завершить объединение веток:

$ cd calc/trunk
$ svn update
At revision 405.

$ svn merge -r 341:405 http://svn.example.com/repos/calc/branches/my-calc-branch
U   integer.c
U   button.c
U   Makefile

$ svn status
M   integer.c
M   button.c
M   Makefile

# ...examine the diffs, compile, test, etc...

$ svn commit -m "Merged my-calc-branch changes r341:405 into the trunk."
Sending        integer.c
Sending        button.c
Sending        Makefile
Transmitting file data ...
Committed revision 406.

Еще раз обратите внимание на то, что в лог-сообщении фиксации очень точно указан диапазон правок, которые были объединены с главной линией разработки. Никогда не забывайте этого делать, потому что это очень важная информация, которая понадобиться вам позже.

Предположим, что на следующей неделе вы решили продолжить работу над своей веткой, чтобы доработать новый функционал или исправить еще несколько ошибок. Теперь правка HEAD хранилища имеет номер 480, и вы готовы еще раз объединить свою личную копию с главной линией разработки. Однако, как уже было сказано в разделе «Как правильнее всего использовать слияние», ранее объединенные изменения не стоит объединять повторно. Объединению подлежат только «новые» изменения, появившиеся с момента последнего объединения. Сложность заключается в том, чтобы выделить эти новые изменения.

Первым шагом будет запуск svn log для главной линии разработки, в результате чего мы узнаем время последнего объединения с веткой:

$ cd calc/trunk
$ svn log
…
------------------------------------------------------------------------
r406 | user | 2004-02-08 11:17:26 -0600 (Sun, 08 Feb 2004) | 1 line

Merged my-calc-branch changes r341:405 into the trunk.
------------------------------------------------------------------------
…

Ага! Все изменения ветки, сделанные между правками 341 и 405, уже были объединены с главной линией разработки в правке 406. Поэтому сейчас нам нужно взять только изменения, выполненные после этого. Для этого мы будем сравнивать правки 406 и HEAD.

$ cd calc/trunk
$ svn update
At revision 480.

# We notice that HEAD is currently 480, so we use it to do the merge:

$ svn merge -r 406:480 http://svn.example.com/repos/calc/branches/my-calc-branch
U   integer.c
U   button.c
U   Makefile

$ svn commit -m "Merged my-calc-branch changes r406:480 into the trunk."
Sending        integer.c
Sending        button.c
Sending        Makefile
Transmitting file data ...
Committed revision 481.

Теперь главная линия разработки полностью содержит вторую волну изменений, сделанных в ветке. Теперь можно либо удалить ветку (об этом мы поговорим позже), либо продолжить работу над ней, периодически повторяя при этом процедуру объединения.

Отмена изменений

Еще одной типичной задачей для svn merge является откат ранее сделанных изменений. Предположим, работая в копии /calc/trunk, вы вдруг выясняете, что изменения файла integer.c, сделанные в правке 303, были совершенно ошибочными. Вы можете воспользоваться командой svn merge для «отмены» изменений в своей рабочей копии, после чего зафиксировать локальные изменения в хранилище. Для этого нужно всего лишь указать различия в обратном порядке:

$ svn merge -r 303:302 http://svn.example.com/repos/calc/trunk
U  integer.c

$ svn status
M  integer.c

$ svn diff
…
# verify that the change is removed
…

$ svn commit -m "Undoing change committed in r303."
Sending        integer.c
Transmitting file data .
Committed revision 350.

Правку хранилища можно рассматривать как группу изменений (некоторые системы управления версиями называют это набором изменений). Используя параметр -r, можно попросить svn merge применить к рабочей копии набор изменений или целый диапазон наборов изменений. В нашем примере с отменой изменений мы просим svn merge применить к рабочей копии набор изменений #303 в обратном направлении.

Обратите внимание, что подобный откат изменений ничем не отличается от остальных операций, выполняемых с помощью svn merge. Поэтому необходимо с помощью svn status и svn diff убедиться в том, что результат соответствует ожиданиям, а затем, используя svn commit, отправить финальную версию в хранилище. После фиксации этот конкретный набор изменений больше не будет отражен в правке HEAD.

Давайте, однако, подумаем: отменяется ли на самом деле предыдущая фиксация? Изменения продолжают существовать в правке 303. И если кто-то создаст рабочую копию проекта calc между правками 303 и 349, он ведь все равно получит ошибочные изменения?

Безусловно, это так. Говоря об «удалении» изменений, мы имеем в виду их удаление из правки HEAD. Исходные изменения по-прежнему останутся в истории хранилища. Чаще всего это можно рассматривать даже как положительный момент. В любом случае, большинство пользователей интересует только HEAD-правка проекта. Однако, возможны ситуации, когда необходимо полностью удалить последствия фиксации. (Например, если кто-то случайно зафиксировал конфиденциальный документ.) Сделать это будет непросто, так как архитектура Subversion намеренно исключает возможность потери информации. Правки представляют собой не меняющиеся деревья файлов, основанные друг на друге. Удаление правки из хранилища может вызвать эффект домино, потащив за собой все последующие правки и повредив все рабочие копии. [26]

Восстановление удаленных элементов

Отличным свойством системы управления версиями является то, что информация никогда не теряется. При удалении файла или каталога элемент исключается из правки HEAD, но продолжает существовать в более ранних правках. Новые пользователи очень часто спрашивают: «Как мне вернуть назад свой файл или каталог?»

Для начала было бы неплохо определиться, какой именно элемент мы пытаемся восстановить. Для этого полезно представить все объекты хранилища как точки в двумерной системе координат. Первой координатой будет отдельное дерево правок, в второй — путь в этом дереве. Таким образом, каждая версия файла или каталога может быть задана парой координат.

В отличие от CVS, Subversion не имеет каталога Attic[27], поэтому для определения искомой пары координат восстанавливаемого объекта нужно вызвать svn log. Лучше всего запустить svn log --verbose в каталоге, который содержал удаленный объект. Параметр --verbose покажет для каждой правки список измененных элементов — в этом случае вам останется только найти ту правку, в которой файл или каталог были удалены. Это можно сделать визуально или обработав вывод команды каким-нибудь инструментом (например, утилитой grep или просто запустив поиск в редакторе).

$ cd parent-dir
$ svn log --verbose
…
------------------------------------------------------------------------
r808 | joe | 2003-12-26 14:29:40 -0600 (Fri, 26 Dec 2003) | 3 lines
Changed paths:
   D /calc/trunk/real.c
   M /calc/trunk/integer.c

Added fast fourier transform functions to integer.c.
Removed real.c because code now in double.c.
…

В этом примере предполагается, что вы ищете удаленный файл real.c. Просмотрев логи родительского каталога, вы можете заметить, что этот файл был удален в правке 808. Следовательно, самая последняя версия этого файла была в правке, предшествующей удалению. Вывод: необходимо из правки 807 восстановить путь /calc/trunk/real.c.

Поиск — непростая задача. Теперь, когда нам известно, что именно нужно восстановить, есть две варианта действий.

Во-первых, мы можем посредством svn merge применить правку 808 «в обратном направлении». (Как отменять изменения, мы уже рассматривали, см. «Отмена изменений».) Это приведет к повторному добавлению файла real.c в форме локального изменения. Файл будет запланирован для добавления, и после фиксации будет снова присутствовать в HEAD.

Однако, в данном примере это не самое лучшее решение. Повторное применение правки 808 не только добавит файл real.c. Лог-сообщение показывает, что также будут отменены некоторые изменения в integer.c, что весьма нежелательно. Конечно, можно выполнить обратное слияние с правкой 808, а затем отменить (svn revert) локальные изменения в integer.c, но такой подход плохо масштабируется. Что, если в правке 808 изменилось 90 файлов?

При другом, более аккуратном подходе svn merge вообще не используется, а вместо этого применяется команда svn copy. Просто скопируйте объект, заданный «парой координат» (правка и путь), из хранилища в рабочую копию:

$ svn copy --revision 807 \
           http://svn.example.com/repos/calc/trunk/real.c ./real.c

$ svn status
A  +   real.c

$ svn commit -m "Resurrected real.c from revision 807, /calc/trunk/real.c."
Adding         real.c
Transmitting file data .
Committed revision 1390.

Знак "плюс" в столбце статуса показывает, что элемент не просто запланирован для добавления, а запланирован для добавления «с историей». Subversion запоминает, откуда он был скопирован. В будущем вызов svn log для этого файла будет пересекать точку восстановления файла и прослеживать всю историю, предшествующую правке 807. Другими словами, новый файл real.c на самом деле не является новым; он является прямым потомком исходного файла, который был удален.

Хотя наш пример демонстрирует только восстановление файла, отметим, что такой же подход будет работать и при восстановлении удаленных каталогов.

Типовые приемы использования веток

Управление версиями чаще всего используется при разработке программного обеспечения, поэтому здесь мы вкратце рассмотрим два наиболее часто используемых командами программистов приема ветвления/слияния. Если вы не используете Subversion для разработки программного обеспечения, можете пропустить этот раздел. Если вы — разработчик программного обеспечения, впервые использующий контроль версий, уделите этому разделу пристальное внимание, поскольку опытные разработчики считают использование данных приемов хорошим стилем. Такие приемы не являются специфичными для Subversion; они применимы к любой системе управления версиями. Однако, здесь мы взглянем на них с позиций Subversion.

Ветки релизов

Большинство программного обеспечения имеет типовой жизненный цикл: написание кода, тестирование, выпуск, повторный цикл. При таком подходе возникают две проблемы. Во-первых, разработчикам необходимо продолжать расширять функциональность в то время, как группа проверки качества будет заниматься тестированием предположительно стабильных версий программы. Во время тестирования не должна останавливаться разработка. Во-вторых, как правило, требуется поддерживать старые, уже выпущенные версии программы; если найдена ошибка в последней версии кода, то скорее всего она присутствует и в уже выпущенных версиях, поэтому пользователи захотят, чтобы эта ошибка была исправлена не дожидаясь выхода новой версии программы.

Здесь-то и может помочь контроль версий. Типичная процедура выглядит примерно так:

  • Разработчики фиксируют все новое в главную линию разработки. Каждодневные изменения фиксируются в /trunk: новая функциональность, исправление ошибок и тому подобное.

  • Главная линия разработки копируется в ветку «релиза». Когда команда разработчиков решает, что программа готова к выпуску (скажем, к релизу 1.0), тогда /trunk копируется, например, в /branches/1.0.

  • Группы продолжают работать параллельно. Одна группа начинает всестороннее тестирование ветки релиза, в то время как вторая группа продолжает работу (скажем, над версией 2.0) в /trunk. Если находятся ошибки в какой-либо из версий, исправления портируются по необходимости в одну или другую сторону. В какой-то момент этот процесс останавливается. Ветка «замораживается» для окончательной проверки перед релизом.

  • На основе ветки создается метка и выпускается релиз. Когда тестирование завершено, /branches/1.0 копируется в /tags/1.0.0 как справочный снимок. Метка запаковывается и отправляется пользователям.

  • Ветка продолжает поддерживаться. По мере продвижения работы над /trunk для версии 2.0, исправления ошибок продолжают портироваться из /trunk в /branches/1.0. Когда будет накоплено определенной количество исправлений, руководство может решить сделать релиз 1.0.1: /branches/1.0 копируется в /tags/1.0.1, метка пакуется и выпускается.

По мере развития программы эти этапы повторяются: когда работа над 2.0 будет завершена, создается новая ветка релиза 2.0, тестируется, создается метка и в последствии выпускается релиз. После нескольких лет в хранилище будет находиться определенное количество веток релизов, находящихся в режиме «сопровождения» и определенное количество меток, отражающих последние выпущенные ветки.

Функциональные ветки

Функциональная ветка является доминирующим примером в этой главе, над такой веткой вы работаете пока Салли работает над /trunk. Это временная ветка, которая создается для работы над комплексным изменением без пересечения со стабильной линией разработки /trunk. В отличие от веток релизов (которые могут поддерживаться вечно), функциональные ветки создаются, используются, внедряются обратно в главную линию разработки, после чего полностью удаляются. Они имеют ограниченный срок использования.

Опять же, правила проекта относительно определения момента, когда требуется создание функциональной ветки могут быть разными. Некоторые проекты вообще никогда не используют функциональные ветки: все фиксируется в /trunk. Преимущества такой системы в ее простоте — никому не нужно учиться делать ветки или объединения. Недостатком является то, что главная линия разработки часто не стабильна или не пригодна к использованию. В других проектах ветки используют по-другому: ни одного изменения не фиксируют в главной линии разработки напрямую. Даже для самых простых изменений создается краткосрочная ветка, внимательно анализируется и объединяется с главной линией. После чего ветка удаляется. Ценой огромных накладных расходов, такая система гарантирует исключительную стабильность и пригодность к использованию главной линии разработки в любой момент времени.

Большинство проектов использует что-то среднее. Как правило, все время контролируя, что /trunk компилируется и проходит регрессивные тесты. Функциональная ветка требуется только тогда, когда изменение требует большого количества дестабилизирующих фиксаций. Хорошим способом проверки является постановка такого вопроса: если разработчик работал несколько дней изолировано, а затем за один раз зафиксировал большое изменение (притом, что /trunk не будет дестабилизирован) будет ли сложно отследить это изменение? Если ответ на этот вопрос «да», то тогда изменение должно разрабатываться в функциональной ветке. По мере того, как разработчик последовательно фиксирует изменения в ветку, они могут легко отслеживаться другими участниками.

Напоследок, рекомендация, как по ходу работы лучше всего сохранять функциональную ветку «синхронизированной» с главной линией разработки. Как мы уже говорили, рискованно работать над веткой в течение недель или месяцев; изменения в главной линии будут продолжаться, и настанет момента, когда две линии разработки станут отличаться так сильно, что попытка объединить ветку обратно с главной линией разработки может стать ночным кошмаром.

Этой ситуации не возникнет, если регулярно объединять ветку с изменениями в главной линии. Возьмите за правило один раз в неделю объединять с веткой значимые изменения в главной линии разработки за прошедшую неделю. Делайте это аккуратно; за объединением необходим ручной контроль для того, что бы исключить проблему повторных объединений (как это описано в разделе «Ручной контроль слияния»). Необходимо внимательно записывать лог сообщение, указывая какой именно диапазон правок был объединен (как показано в разделе «Полное объединение двух веток»). Возможно это звучит устрашающе, но на самом деле это сделать очень легко.

Начиная с какого-то момента вы будете готовы объединить «синхронизированную» функциональную ветку с главной линией разработки. Для этого начните с завершающего объединения последних изменений из главной линии разработки с веткой. После чего, последняя версия ветки и главной линии будут абсолютно идентичны, за исключением ваших изменений в ветке. Теперь объединение заключается в сравнении ветки с главной линией разработки:

$ cd trunk-working-copy

$ svn update
At revision 1910.

$ svn merge http://svn.example.com/repos/calc/trunk@1910 \
            http://svn.example.com/repos/calc/branches/mybranch@1910
U  real.c
U  integer.c
A  newdirectory
A  newdirectory/newfile
…

Сравнивая правку HEAD главной линии разработки и правку HEAD ветки, определяется дельта, которая представляет собой только изменения сделанные в ветке; обе линии разработки уже содержат все изменения из главной линии.

Другим способом представления этого приема является то, что еженедельная синхронизация ветки аналогична запуску svn update в рабочей копии, в то время как окончательное объединение аналогично запуску из рабочей копии svn commit. В конце концов, что же такое рабочая копия если не миниатюрная личная ветка? Это такая ветка, которая способна хранить одно изменение в каждый момент времени.

Переключение рабочей копии

Команда svn switch трансформирует существующую рабочую копию в другую ветку. Несмотря на то, что при работе с ветками эта команда не является крайне необходимой, она значительно облегчает жизнь пользователям. В ранее приведенном примере, после создания личной ветки вы создавали новую рабочую копию созданной директории хранилища. Вместо этого, можно попросить Subversion изменить рабочую копию /calc/trunk так, что бы она отражала созданную ветку:

$ cd calc

$ svn info | grep URL
URL: http://svn.example.com/repos/calc/trunk

$ svn switch http://svn.example.com/repos/calc/branches/my-calc-branch
U   integer.c
U   button.c
U   Makefile
Updated to revision 341.

$ svn info | grep URL
URL: http://svn.example.com/repos/calc/branches/my-calc-branch

После «переключения» на ветку, рабочая копия не будет отличаться от той которая получилась бы при создании новой рабочей копии директории хранилища. Как правило, более эффективно использовать эту команду, так как обычно у ветки немного отличий. Сервер отправляет минимально необходимый для того, что бы рабочая копия отражала директорию ветки, набор изменений.

Команда svn switch принимает параметр --revision (-r), по-этому необязательно помещать рабочую копию на самую «верхушку» ветки.

Конечно, большинство проектов, по сравнению с нашим примером calc более сложны, содержат множество поддиректорий. Обычно пользователи Subversion используют специальный алгоритм для работы с ветками:

  1. Скопировать всю директорию «trunk» в директорию новой ветки.

  2. Переключить часть главной линии разработки на ветку.

Другими словами, если пользователь знает, что работа над веткой будет проходить в конкретной директории, он может, с помощью, svn switch переключить на ветку только эту поддиректорию. (А иногда на ветку переключается только один рабочий файл!) В этом случае пользователи могут продолжать обычным образом получать обновления «trunk» для большей части рабочей копии, а переключенные части будут оставаться нетронутыми (до тех пор, пока кто-то не изменит этой ветки). Эта возможность добавляет совершенно новое измерение в понятие «смешанная рабочая копия» — рабочая копия может содержать не только смесь рабочих правок но и смесь местоположений в хранилище.

Если рабочая копия содержит какое-то количество переключенных на разные местоположения в хранилище поддиректорий, она будет продолжать нормально функционировать. При обновлении, патчи соответственно будут приниматься для каждой поддиректории. При фиксации, локальные модификации будут приниматься в хранилище в виде единого, атомарного изменения.

Обратите внимание, на то, что хотя и иметь в рабочей копии смесь местоположений в хранилище является нормальным, все эти местоположения должны быть из одного хранилища. Хранилища Subversion пока не могут сообщаться друг с другом; реализация этой возможности запланирована после Subversion 1.0.[28]

Учитывая то, что svn switch в сущности является разновидностью svn update их поведение схоже; при получении новой информации из хранилища, все локальные изменения сохраняются. Это позволяет использовать разнообразные трюки.

Предположим вы внесли некоторые изменения в имеющуюся у вас рабочую копию /calc/trunk. После чего неожиданно обнаружили, что вместо этого вам необходимо внести изменения в ветку. Нет проблем! Когда вы переключите (svn switch) рабочую копию на ветку, локальные изменения сохраняться. После чего их можно проверить и зафиксировать в ветке.

Метки

Еще одним понятием, свойственным управлению версиями является метка. Метка является просто «снимком» проекта в определенный момент времени. В Subversion эта идея уже, кажется, повсюду. Каждая правка хранилища является именно этим — снимком файловой системы после каждой фиксации.

Как правило, люди предпочитают давать меткам удобочитаемые имена, наподобие release-1.0. И делать снимки небольших поддиректорий файловой системы. Проще говоря, не просто запомнить, что версия 1.0 программы соответствует поддиректории в правке 4822.

Создание простой метки

И снова приходит на помощь svn copy. Если вам нужно сделать снимок /calc/trunk в точно таком виде как в правке HEAD, сделайте копию этой директории:

$ svn copy http://svn.example.com/repos/calc/trunk \
           http://svn.example.com/repos/calc/tags/release-1.0 \
      -m "Tagging the 1.0 release of the 'calc' project."

Committed revision 351.

В этом примере предполагается, что директория /calc/tags существует. (Если нет, обратитесь к svn mkdir). После того как сделана копия, новая директория release-1.0 навсегда сохранит состояние проекта в таком виде в каком он существовал в правке HEAD на момент создания копии. Конечно, можно более точно указать какую именно правку копировать, возможна ситуация, когда кто-то другой зафиксировал изменения в проекте с которыми вы еще не успели познакомиться. Поэтому, если вы знаете, что правка 350 /calc/trunk это именно тот снимок который вам нужен, можете указать ее передав -r 350 команде svn copy.

Постойте: ведь процедура создания метки такая же как процедура использованная нами при создании ветки? Да, фактически, это так. Subversion не разделяет ветки и метки. И то и другое является обычными директориями, созданными копированием. Как и в случае с ветками, скопированная директория становиться «меткой» только потому, что человек считает ее таковой: если никто не делает фиксаций в эту директорию она будет оставаться снимком. Если в эту директорию начнут делать фиксации она превратится в ветку.

Если вы администрируете хранилище, есть два возможных подхода управления метками. Первый подход «ручной»: в соответствии с правилами проекта решите, где будут находиться метки и убедитесь в том, что все пользователи знают как рассматривать директории скопированные сюда. (То есть убедитесь, что они знают о том что в них нельзя выполнять фиксации.) Второй подход более параноидальный: вы можете воспользоваться одним из скриптов для контроля доступа, поставляемым с Subversion для того, что бы никто ничего другого кроме создания копий в области для создания меток сделать не мог. (См. Глава 6, Настройка сервера.) Однако обычно в параноидальном подходе необходимости нет. Если пользователь непреднамеренно зафиксирует изменения в директорию с меткой, вы можете просто отменить изменения, как это было рассмотрено в предыдущем разделе. Как ни как, это управление версиями.

Создание комплексной метки

Иногда вам будет необходим более сложный «снимок», чем одна единственная директория в одной правке.

Например, представим, что ваш проект гораздо больше, чем наш пример calc: допустим он содержит несколько поддиректорий и намного больше файлов. В процессе работы вам может понадобиться создать рабочую копию, содержащую конкретную функциональность и исправленные ошибки. Добиться этого вы можете выборочно возвращая файлы или директории к конкретной правке (используя svn update -r по мере необходимости) или переключая файлы или директории на отдельные ветки (применяя svn switch). По завершении рабочаяя копия будет представлять собой мешанину различных директорий и правок хранилища. После проверки вы поймете, что вам нужна именно такая комбинация.

Время создавать снимок. Копирование одного URL в другой здесь не пройдет. Здесь нужно сделать и сохранить в хранилище снимок именно такой структуры которую имеет рабочая копия. К счастью, svn copy имеет четыре способа использования (о которых вы можете прочитать в Глава 9, Полное справочное руководство по Subversion), включая возможность копировать в хранилище дерево рабочей копии:

$ ls
my-working-copy/

$ svn copy my-working-copy http://svn.example.com/repos/calc/tags/mytag

Committed revision 352.

Теперь в хранилище есть новая директория /calc/tags/mytag которая является полным отражением рабочей копии — смешанные правки, URL, и тому подобное.

Некоторые пользователи находят интересное применение этой возможности. Иногда возникают ситуации, когда в вашей рабочей копии содержится некоторый набор локальных изменений, которые вы хотели бы показать соразработчику. Вместо запуска svn diff и отправки патч-файла (который не сможет отразить изменения в структуре файлов, измененные символьные ссылки или свойства), можно воспользоваться svn copy для «загрузки» рабочей копии в отдельную область хранилища. После чего ваш соразработчик сможет либо воссоздать у себя вашу рабочую копию, либо, воспользовавшись svn merge, получить только внесенные вами изменения.

Поддержка веток

Сейчас вы уже понимаете, что Subversion очень гибкая система. Учитывая то, что ветки и метки имеют одну и ту же основу (копии директорий), а также то, что ветки и метки являются обычными элементами файловой системы, Subversion многих пугает. Она слишком гибкая. В этом разделе мы предложим несколько советов по компоновке и поддержке информации с течением времени.

Структура хранилища

Существует несколько стандартных, рекомендуемых способов организации хранилища. Как правило, создается директория trunk, в которой находится «главная линия» разработки, директория branches для хранения веток и директория tags для хранения меток. Если хранилище содержит только один проект, обычно создают три директории верхнего уровня:

/trunk
/branches
/tags

Если хранилище содержит несколько проектов, администратор, обычно создает такую структуру для каждого проекта отдельно (за более подробной информацией о «корне проекта» обратитесь в раздел «Choosing a Repository Layout»):

/paint/trunk
/paint/branches
/paint/tags
/calc/trunk
/calc/branches
/calc/tags

Конечно, вы можете не использовать такие типовые структуры. Вы можете сделать любую разновидность, которая будет удобна для вас или вашей команды. Помните о том, какой бы вы выбор не сделали, он может быть не окончательным. Хранилище можно реорганизовать в любое время. Учитывая то, что ветки и метки являются обычными директориями, команда svn move может переместить или переименовать их по вашему усмотрению. Переход от одной структуры к другой означает просто несколько последовательных передвижек на сервере; если организация хранилища вам не нравится, просто поменяйте местами директории.

Однако не забывайте о том, что несмотря на легкость перемещения директорий, нужно помнить и о других пользователях. Ваши перестановки могут дезориентировать пользователей с существующими рабочими копиями. Если у пользователя есть рабочая копия отдельной директории хранилища, то ваше использование svn move может удалить этот путь из последней правки. Когда в очередной раз пользователь запустит svn update, он будет проинформирован о том, что его рабочая копия отражает путь, который больше не существует, и пользователь будет вынужден переключиться (svn switch) на новое местоположение.

Продолжительность жизни информации

Еще одним замечательным свойством модели Subversion является то, что ветки и метки могут иметь конечную продолжительность жизни, так же как и все другие версионированные элементы. Например, предположим вы наконец закончили все работы в ваше личной ветке проекта calc. После объединения изменений с /calc/trunk, нет причин продолжать хранить эту ветку:

$ svn delete http://svn.example.com/repos/calc/branches/my-calc-branch \
             -m "Removing obsolete branch of calc project."

Committed revision 375.

Больше вашей ветки не существует. Конечно, на самом деле она не исчезла: просто ее больше нет в правке HEAD, она больше никого не отвлекает. Если воспользоваться командами svn checkout, svn switch или svn list для обращения к ранним правкам, свою старую ветку вы увидите.

Если просмотра удаленной директории не достаточно, вы всегда можете восстановить эту директорию. Восстановление информации в Subversion выполнить очень просто. Если есть директория или файл, который вы хотите вернуть обратно в HEAD, просто воспользуйтесь svn copy -r для того, что бы скопировать его из старой правки:

$ svn copy -r 374 http://svn.example.com/repos/calc/branches/my-calc-branch \
                  http://svn.example.com/repos/calc/branches/my-calc-branch

Committed revision 376.

В нашем примере ваша личная ветка имеет относительно короткую продолжительность жизни: возможно она создавалась для того, что бы исправить ошибку или реализовать новую функцию. После того, как работа завершена, завершена и ветка. При разработке программного обеспечения, тем не менее, часто имеют две «главных» ветки, существующих рядом довольно долгое время. Допустим, пришло время выпустить релиз стабильной версии проекта calc, а вы знаете, что нужна будет пара месяцев для того, что бы вытрясти из программы последние ошибки. Разработчики не должны добавлять в проект новых функции, но при этом и работа не должна останавливаться. В подобной ситуации создается «стабильная» ветка программы, которая существенно изменяться уже не будет:

$ svn copy http://svn.example.com/repos/calc/trunk \
         http://svn.example.com/repos/calc/branches/stable-1.0 \
         -m "Creating stable branch of calc project."

Committed revision 377.

После этого, разработчикам ничего не мешает продолжать добавлять в /calc/trunk новые передовые (или экспериментальные) функции, а в правилах проекта можно указать, что в /calc/branches/stable-1.0 должны фиксироваться только исправления ошибок. По мере того, как будет продвигаться работа над главной линией разработки, исправленные ошибки будут выборочно портироваться в стабильную ветку. Даже после выхода релиза стабильной ветки, она может продолжать поддерживаться долгое время — столько, сколько этот релиз будет продолжать поддерживаться для пользователей.

Vendor branches

As is especially the case when developing software, the data that you maintain under version control is often closely related to, or perhaps dependent upon, someone else's data. Generally, the needs of your project will dictate that you stay as up-to-date as possible with the data provided by that external entity without sacrificing the stability of your own project. This scenario plays itself out all the time—anywhere that the information generated by one group of people has a direct effect on that which is generated by another group.

For example, software developers might be working on an application which makes use of a third-party library. Subversion has just such a relationship with the Apache Portable Runtime library (see «The Apache Portable Runtime Library»). The Subversion source code depends on the APR library for all its portability needs. In earlier stages of Subversion's development, the project closely tracked APR's changing API, always sticking to the «bleeding edge» of the library's code churn. Now that both APR and Subversion have matured, Subversion attempts to synchronize with APR's library API only at well-tested, stable release points.

Now, if your project depends on someone else's information, there are several ways that you could attempt to synchronize that information with your own. Most painfully, you could issue oral or written instructions to all the contributors of your project, telling them to make sure that they have the specific versions of that third-party information that your project needs. If the third-party information is maintained in a Subversion repository, you could also use Subversion's externals definitions to effectively «pin down» specific versions of that information to some location in your own working copy directory (see «Внешние зависимости»).

But sometimes you want to maintain custom modifications to third-party data in your own version control system. Returning to the software development example, programmers might need to make modifications to that third-party library for their own purposes. These modifications might include new functionality or bug fixes, maintained internally only until they become part of an official release of the third-party library. Or the changes might never be relayed back to the library maintainers, existing solely as custom tweaks to make the library further suit the needs of the software developers.

Now you face an interesting situation. Your project could house its custom modifications to the third-party data in some disjointed fashion, such as using patch files or full-fledged alternate versions of files and directories. But these quickly become maintenance headaches, requiring some mechanism by which to apply your custom changes to the third-party data, and necessitating regeneration of those changes with each successive version of the third-party data that you track.

The solution to this problem is to use vendor branches. A vendor branch is a directory tree in your own version control system that contains information provided by a third-party entity, or vendor. Each version of the vendor's data that you decide to absorb into your project is called a vendor drop.

Vendor branches provide two key benefits. First, by storing the currently supported vendor drop in your own version control system, the members of your project never need to question whether they have the right version of the vendor's data. They simply receive that correct version as part of their regular working copy updates. Secondly, because the data lives in your own Subversion repository, you can store your custom changes to it in-place—you have no more need of an automated (or worse, manual) method for swapping in your customizations.

General Vendor Branch Management Procedure

Managing vendor branches generally works like this. You create a top-level directory (such as /vendor) to hold the vendor branches. Then you import the third party code into a subdirectory of that top-level directory. You then copy that subdirectory into your main development branch (for example, /trunk) at the appropriate location. You always make your local changes in the main development branch. With each new release of the code you are tracking you bring it into the vendor branch and merge the changes into /trunk, resolving whatever conflicts occur between your local changes and the upstream changes.

Perhaps an example will help to clarify this algorithm. We'll use a scenario where your development team is creating a calculator program that links against a third-party complex number arithmetic library, libcomplex. We'll begin with the initial creation of the vendor branch, and the import of the first vendor drop. We'll call our vendor branch directory libcomplex, and our code drops will go into a subdirectory of our vendor branch called current. And since svn import creates all the intermediate parent directories it needs, we can actually accomplish both of these steps with a single command.

$ svn import /path/to/libcomplex-1.0 \
             http://svn.example.com/repos/vendor/libcomplex/current \
             -m 'importing initial 1.0 vendor drop'
…

We now have the current version of the libcomplex source code in /vendor/libcomplex/current. Now, we tag that version (see «Метки») and then copy it into the main development branch. Our copy will create a new directory called libcomplex in our existing calc project directory. It is in this copied version of the vendor data that we will make our customizations.

$ svn copy http://svn.example.com/repos/vendor/libcomplex/current  \
           http://svn.example.com/repos/vendor/libcomplex/1.0      \
           -m 'tagging libcomplex-1.0'
…
$ svn copy http://svn.example.com/repos/vendor/libcomplex/1.0  \
           http://svn.example.com/repos/calc/libcomplex        \
           -m 'bringing libcomplex-1.0 into the main branch'
…

We check out our project's main branch—which now includes a copy of the first vendor drop—and we get to work customizing the libcomplex code. Before we know it, our modified version of libcomplex is now completely integrated into our calculator program. [29]

A few weeks later, the developers of libcomplex release a new version of their library—version 1.1—which contains some features and functionality that we really want. We'd like to upgrade to this new version, but without losing the customizations we made to the existing version. What we essentially would like to do is to replace our current baseline version of libcomplex 1.0 with a copy of libcomplex 1.1, and then re-apply the custom modifications we previously made to that library to the new version. But we actually approach the problem from the other direction, applying the changes made to libcomplex between versions 1.0 and 1.1 to our modified copy of it.

To perform this upgrade, we checkout a copy of our vendor branch, and replace the code in the current directory with the new libcomplex 1.1 source code. We quite literally copy new files on top of existing files, perhaps exploding the libcomplex 1.1 release tarball atop our existing files and directories. The goal here is to make our current directory contain only the libcomplex 1.1 code, and to ensure that all that code is under version control. Oh, and we want to do this with as little version control history disturbance as possible.

After replacing the 1.0 code with 1.1 code, svn status will show files with local modifications as well as, perhaps, some unversioned or missing files. If we did what we were supposed to do, the unversioned files are only those new files introduced in the 1.1 release of libcomplex—we run svn add on those to get them under version control. The missing files are files that were in 1.0 but not in 1.1, and on those paths we run svn delete. Finally, once our current working copy contains only the libcomplex 1.1 code, we commit the changes we made to get it looking that way.

Our current branch now contains the new vendor drop. We tag the new version (in the same way we previously tagged the version 1.0 vendor drop), and then merge the differences between the tag of the previous version and the new current version into our main development branch.

$ cd working-copies/calc
$ svn merge http://svn.example.com/repos/vendor/libcomplex/1.0      \
            http://svn.example.com/repos/vendor/libcomplex/current  \
            libcomplex
… # resolve all the conflicts between their changes and our changes
$ svn commit -m 'merging libcomplex-1.1 into the main branch'
…

In the trivial use case, the new version of our third-party tool would look, from a files-and-directories point of view, just like the previous version. None of the libcomplex source files would have been deleted, renamed or moved to different locations—the new version would contain only textual modifications against the previous one. In a perfect world, our modifications would apply cleanly to the new version of the library, with absolutely no complications or conflicts.

But things aren't always that simple, and in fact it is quite common for source files to get moved around between releases of software. This complicates the process of ensuring that our modifications are still valid for the new version of code, and can quickly degrade into a situation where we have to manually recreate our customizations in the new version. Once Subversion knows about the history of a given source file—including all its previous locations—the process of merging in the new version of the library is pretty simple. But we are responsible for telling Subversion how the source file layout changed from vendor drop to vendor drop.

svn_load_dirs.pl

Vendor drops that contain more than a few deletes, additions and moves complicate the process of upgrading to each successive version of the third-party data. So Subversion supplies the svn_load_dirs.pl script to assist with this process. This script automates the importing steps we mentioned in the general vendor branch management procedure to make sure that mistakes are minimized. You will still be responsible for using the merge commands to merge the new versions of the third-party data into your main development branch, but svn_load_dirs.pl can help you more quickly and easily arrive at that stage.

In short, svn_load_dirs.pl is an enhancement to svn import that has several important characteristics:

  • It can be run at any point in time to bring an existing directory in the repository to exactly match an external directory, performing all the necessary adds and deletes, and optionally performing moves, too.

  • It takes care of complicated series of operations between which Subversion requires an intermediate commit—such as before renaming a file or directory twice.

  • It will optionally tag the newly imported directory.

  • It will optionally add arbitrary properties to files and directories that match a regular expression.

svn_load_dirs.pl takes three mandatory arguments. The first argument is the URL to the base Subversion directory to work in. This argument is followed by the URL—relative to the first argument—into which the current vendor drop will be imported. Finally, the third argument is the local directory to import. Using our previous example, a typical run of svn_load_dirs.pl might look like:

$ svn_load_dirs.pl http://svn.example.com/repos/vendor/libcomplex \
                   current                                        \
                   /path/to/libcomplex-1.1
…

You can indicate that you'd like svn_load_dirs.pl to tag the new vendor drop by passing the -t command-line option and specifying a tag name. This tag is another URL relative to the first program argument.

$ svn_load_dirs.pl -t libcomplex-1.1                              \
                   http://svn.example.com/repos/vendor/libcomplex \
                   current                                        \
                   /path/to/libcomplex-1.1
…

When you run svn_load_dirs.pl, it examines the contents of your existing «current» vendor drop, and compares them with the proposed new vendor drop. In the trivial case, there will be no files that are in one version and not the other, and the script will perform the new import without incident. If, however, there are discrepancies in the file layouts between versions, svn_load_dirs.pl will prompt you for how you would like to resolve those differences. For example, you will have the opportunity to tell the script that you know that the file math.c in version 1.0 of libcomplex was renamed to arithmetic.c in libcomplex 1.1. Any discrepancies not explained by moves are treated as regular additions and deletions.

The script also accepts a separate configuration file for setting properties on files and directories matching a regular expression that are added to the repository. This configuration file is specified to svn_load_dirs.pl using the -p command-line option. Each line of the configuration file is a whitespace-delimited set of two or four values: a Perl-style regular expression to match the added path against, a control keyword (either break or cont), and then optionally a property name and value.

\.png$              break   svn:mime-type   image/png
\.jpe?g$            break   svn:mime-type   image/jpeg
\.m3u$              cont    svn:mime-type   audio/x-mpegurl
\.m3u$              break   svn:eol-style   LF
.*                  break   svn:eol-style   native

For each added path, the configured property changes whose regular expression matches the path are applied in order, unless the control specification is break (which means that no more property changes should be applied to that path). If the control specification is cont—an abbreviation for continue—then matching will continue with the next line of the configuration file.

Any whitespace in the regular expression, property name, or property value must be surrounded by either single or double quote characters. You can escape quote characters that are not used for wrapping whitespace by preceding them with a backslash (\) character. The backslash escapes only quotes when parsing the configuration file, so do not protect any other characters beyond what is necessary for the regular expression.

Подводя итоги

В этой главе было рассмотрено очень многое. Мы обсудили концепцию меток и веток, показали как Subversion реализует эти понятия используя команду svn copy. Показали, как svn merge копирует изменения из одной ветки в другую, как с помощью этой команды отменить ошибочные изменения. Мы рассмотрели использование svn switch для создания рабочих копий, собранных из разных директорий хранилища. Обсудили, как управлять организацией и временем жизни веток в хранилище.

Не забывайте о мантре Subversion: ветки и метки легковесны. Поэтому пользуйтесь ими свободно!




[24] Subversion не поддерживает возможность копирования между хранилищами. При использовании в командах svn copy или svn move URL-адресов можно копировать только элементы из одного и того же хранилища.

[25] В будущем проект Subversion планирует использовать (или изобрести) расширенный формат представления различий, который будет передавать изменения в структуре дерева файлов и свойств.

[26] Однако, разработчики Subversion в будущем планируют реализовать команду svnadmin obliterate, которая позволит полностью удалять информацию. А пока за возможным решением проблемы обратитесь к разделу «svndumpfilter».

[27] Из-за того, что CVS не версионирует деревья, она создает область Attic для каждого каталога хранилища как способ сохранения информации об удаленных файлах.

[28] Однако, можно воспользоваться svn switch с параметром --relocate если URL сервера изменился и вы не хотите бросать существующую рабочую копию. За более подробной информацией и примерами смотрите раздел, посвященный svn switch в Глава 9, Полное справочное руководство по Subversion

[29] And entirely bug-free, of course!

Глава 5. Администрирование хранилища

### TODO: Heavy (re-)construction will be happenin' here! ###

The Subversion repository is the central storehouse of versioned data for any number of projects. As such, it becomes an obvious candidate for all the love and attention an administrator can offer. While the repository is generally a low-maintenance item, it is important to understand how to properly configure and care for it so that potential problems are avoided, and actual problems are safely resolved.

In this chapter, we'll discuss how to create and configure a Subversion repository. We'll also talk about repository maintenance, including the use of the svnlook and svnadmin tools (which are provided with Subversion). We'll address some common questions and mistakes, and give some suggestions on how to arrange the data in the repository.

If you plan to access a Subversion repository only in the role of a user whose data is under version control (that is, via a Subversion client), you can skip this chapter altogether. However, if you are, or wish to become, a Subversion repository administrator, [30] you should definitely pay attention to this chapter.

Repository Basics

Before jumping into the broader topic of repository administration, let's further define what a repository is. How does it look? How does it feel? Does it take its tea hot or iced, sweetened, and with lemon? As an administrator, you'll be expected to understand the composition of a repository both from a logical perspective—dealing with how data is represented inside the repository—and from a physical nuts-and-bolts perspective—how a repository looks and acts with respect to non-Subversion tools. The following section covers some of these basic concepts at a very high level.

Understanding Transactions and Revisions

Conceptually speaking, a Subversion repository is a sequence of directory trees. Each tree is a snapshot of how the files and directories versioned in your repository looked at some point in time. These snapshots are created as a result of client operations, and are called revisions.

Every revision begins life as a transaction tree. When doing a commit, a client builds a Subversion transaction that mirrors their local changes (plus any additional changes that might have been made to the repository since the beginning of the client's commit process), and then instructs the repository to store that tree as the next snapshot in the sequence. If the commit succeeds, the transaction is effectively promoted into a new revision tree, and is assigned a new revision number. If the commit fails for some reason, the transaction is destroyed and the client is informed of the failure.

Updates work in a similar way. The client builds a temporary transaction tree that mirrors the state of the working copy. The repository then compares that transaction tree with the revision tree at the requested revision (usually the most recent, or «youngest» tree), and sends back information that informs the client about what changes are needed to transform their working copy into a replica of that revision tree. After the update completes, the temporary transaction is deleted.

The use of transaction trees is the only way to make permanent changes to a repository's versioned filesystem. However, it's important to understand that the lifetime of a transaction is completely flexible. In the case of updates, transactions are temporary trees that are immediately destroyed. In the case of commits, transactions are transformed into permanent revisions (or removed if the commit fails). In the case of an error or bug, it's possible that a transaction can be accidentally left lying around in the repository (not really affecting anything, but still taking up space).

In theory, someday whole workflow applications might revolve around more fine-grained control of transaction lifetime. It is feasible to imagine a system whereby each transaction slated to become a revision is left in stasis well after the client finishes describing its changes to repository. This would enable each new commit to be reviewed by someone else, perhaps a manager or engineering QA team, who can choose to promote the transaction into a revision, or abort it.

Unversioned Properties

Transactions and revisions in the Subversion repository can have properties attached to them. These properties are generic key-to-value mappings, and are generally used to store information about the tree to which they are attached. The names and values of these properties are stored in the repository's filesystem, along with the rest of your tree data.

Revision and transaction properties are useful for associating information with a tree that is not strictly related to the files and directories in that tree—the kind of information that isn't managed by client working copies. For example, when a new commit transaction is created in the repository, Subversion adds a property to that transaction named svn:date—a datestamp representing the time that the transaction was created. By the time the commit process is finished, and the transaction is promoted to a permanent revision, the tree has also been given a property to store the username of the revision's author (svn:author) and a property to store the log message attached to that revision (svn:log).

Revision and transaction properties are unversioned properties—as they are modified, their previous values are permanently discarded. Also, while revision trees themselves are immutable, the properties attached to those trees are not. You can add, remove, and modify revision properties at any time in the future. If you commit a new revision and later realize that you had some misinformation or spelling error in your log message, you can simply replace the value of the svn:log property with a new, corrected log message.

Repository Data Stores

As of Subversion 1.1, there are two options for storing data in a Subversion repository. One type of repository stores everything in a Berkeley DB database; the other kind stores data in ordinary flat files, using a custom format. Because Subversion developers often refer to a repository as «the (versioned) filesystem», they have adopted the habit of referring to the latter type of repository as FSFS [31] —a versioned filesystem implementation that uses the native OS filesystem to store data.

When a repository is created, an administrator must decide whether it will use Berkeley DB or FSFS. There are advantages and disadvantages to each, which we'll describe in a bit. Neither back-end is more «official» than another, and programs which access the repository are insulated from this implementation detail. Programs have no idea how a repository is storing data; they only see revision and transaction trees through the repository API.

Таблица 5.1, «Repository Data Store Comparison» gives a comparative overview of Berkeley DB and FSFS repositories. The next sections go into detail.

Таблица 5.1. Repository Data Store Comparison

FeatureBerkeley DBFSFS
Sensitivity to interruptionsvery; crashes and permission problems can leave the database «wedged», requiring journaled recovery procedures.quite insensitive.
Usable from a read-only mountnoyes
Platform-independent storagenoyes
Usable over network filesystemsnoyes
Repository sizeslightly largerslightly smaller
Scalability: number of revision treesdatabase; no problemssome older native filesystems don't scale well with thousands of entries in a single directory.
Scalability: directories with many filesslowerfaster
Speed: checking out latest codefasterslower
Speed: large commitsslower, but work is spread throughout commitfaster, but finalization delay may cause client timeouts
Group permissions handlingsensitive to user umask problems; best if accessed by only one user.works around umask problems
Code maturityin use since 2001in use since 2004


Berkeley DB

When the initial design phase of Subversion was in progress, the developers decided to use Berkeley DB for a variety of reasons, including its open-source license, transaction support, reliability, performance, API simplicity, thread-safety, support for cursors, and so on.

Berkeley DB provides real transaction support—perhaps its most powerful feature. Multiple processes accessing your Subversion repositories don't have to worry about accidentally clobbering each other's data. The isolation provided by the transaction system is such that for any given operation, the Subversion repository code sees a static view of the database—not a database that is constantly changing at the hand of some other process—and can make decisions based on that view. If the decision made happens to conflict with what another process is doing, the entire operation is rolled back as if it never happened, and Subversion gracefully retries the operation against a new, updated (and yet still static) view of the database.

Another great feature of Berkeley DB is hot backups—the ability to backup the database environment without taking it «offline». We'll discuss how to backup your repository in «Repository Backup», but the benefits of being able to make fully functional copies of your repositories without any downtime should be obvious.

Berkeley DB is also a very reliable database system. Subversion uses Berkeley DB's logging facilities, which means that the database first writes to on-disk log files a description of any modifications it is about to make, and then makes the modification itself. This is to ensure that if anything goes wrong, the database system can back up to a previous checkpoint—a location in the log files known not to be corrupt—and replay transactions until the data is restored to a usable state. See «Managing Disk Space» for more about Berkeley DB log files.

But every rose has its thorn, and so we must note some known limitations of Berkeley DB. First, Berkeley DB environments are not portable. You cannot simply copy a Subversion repository that was created on a Unix system onto a Windows system and expect it to work. While much of the Berkeley DB database format is architecture independent, there are other aspects of the environment that are not. Secondly, Subversion uses Berkeley DB in a way that will not operate on Windows 95/98 systems—if you need to house a repository on a Windows machine, stick with Windows 2000 or Windows XP. Also, you should never keep a Berkeley DB repository on a network share. While Berkeley DB promises to behave correctly on network shares that meet a particular set of specifications, almost no known shares actually meet all those specifications.

Finally, because Berkeley DB is a library linked directly into Subversion, it's more sensitive to interruptions than a typical relational database system. Most SQL systems, for example, have a dedicated server process that mediates all access to tables. If a program accessing the database crashes for some reason, the database daemon notices the lost connection and cleans up any mess left behind. And because the database daemon is the only process accessing the tables, applications don't need to worry about permission conflicts. These things are not the case with Berkeley DB, however. Subversion (and programs using Subversion libraries) access the database tables directly, which means that a program crash can leave the database in a temporarily inconsistent, inaccessible state. When this happens, an administrator needs to ask Berkeley DB to restore to a checkpoint, which is a bit of an annoyance. Other things can cause a repository to «wedge» besides crashed processes, such as programs conflicting over ownership and permissions on the database files. So while a Berkeley DB repository is quite fast and scalable, it's best used by a single server process running as one user—such as Apache's httpd or svnserve (see Глава 6, Настройка сервера)—rather than accessing it as many different users via file:/// or svn+ssh:// URLs. If using a Berkeley DB repository directly as multiple users, be sure to read «Supporting Multiple Repository Access Methods».

FSFS

In mid-2004, a second type of repository storage system came into being: one which doesn't use a database at all. An FSFS repository stores a revision tree in a single file, and so all of a repository's revisions can be found in a single subdirectory full of numbered files. Transactions are created in separate subdirectories. When complete, a single transaction file is created and moved to the revisions directory, thus guaranteeing that commits are atomic. And because a revision file is permanent and unchanging, the repository also can be backed up while «hot», just like a Berkeley DB repository.

The revision-file format represents a revision's directory structure, file contents, and deltas against files in other revision trees. Unlike a Berkeley DB database, this storage format is portable across different operating systems and isn't sensitive to CPU architecture. Because there's no journaling or shared-memory files being used, the repository can be safely accessed over a network filesystem and examined in a read-only environment. The lack of database overhead also means that the overall repository size is a bit smaller.

FSFS has different performance characteristics too. When committing a directory with a huge number of files, FSFS uses an O(N) algorithm to append entries, while Berkeley DB uses an O(N^2) algorithm to rewrite the whole directory. On the other hand, FSFS writes the latest version of a file as a delta against an earlier version, which means that checking out the latest tree is a bit slower than fetching the fulltexts stored in a Berkeley DB HEAD revision. FSFS also has a longer delay when finalizing a commit, which could in extreme cases cause clients to time out when waiting for a response.

The most important distinction, however, is FSFS's inability to be «wedged» when something goes wrong. If a process using a Berkeley DB database runs into a permissions problem or suddenly crashes, the database is left unusable until an administrator recovers it. If the same scenarios happen to a process using an FSFS repository, the repository isn't affected at all. At worst, some transaction data is left behind.

The only real argument against FSFS is its relative immaturity compared to Berkeley DB. It hasn't been used or stress-tested nearly as much, and so a lot of these assertions about speed and scalability are just that: assertions, based on good guesses. In theory, it promises a lower barrier to entry for new administrators and is less susceptible to problems. In practice, only time will tell.

Repository Creation and Configuration

Creating a Subversion repository is an incredibly simple task. The svnadmin utility, provided with Subversion, has a subcommand for doing just that. To create a new repository, just run:

$ svnadmin create /path/to/repos

This creates a new repository in the directory /path/to/repos. This new repository begins life at revision 0, which is defined to consist of nothing but the top-level root (/) filesystem directory. Initially, revision 0 also has a single revision property, svn:date, set to the time at which the repository was created.

In Subversion 1.2, a repository is created with an FSFS back-end by default (see «Repository Data Stores»). The back-end can be explicitly chosen with the --fs-type argument:

$ svnadmin create --fs-type fsfs /path/to/repos
$ svnadmin create --fs-type bdb /path/to/other/repos
[Внимание]Внимание

Do not create a Berkeley DB repository on a network share—it cannot exist on a remote filesystem such as NFS, AFS, or Windows SMB. Berkeley DB requires that the underlying filesystem implement strict POSIX locking semantics, and more importantly, the ability to map files directly into process memory. Almost no network filesystems provide these features. If you attempt to use Berkeley DB on a network share, the results are unpredictable—you may see mysterious errors right away, or it may be months before you discover that your repository database is subtly corrupted.

If you need multiple computers to access the repository, you create an FSFS repository on the network share, not a Berkeley DB repository. Or better yet, set up a real server process (such as Apache or svnserve), store the repository on a local filesystem which the server can access, and make the repository available over a network. Глава 6, Настройка сервера covers this process in detail.

You may have noticed that the path argument to svnadmin was just a regular filesystem path and not a URL like the svn client program uses when referring to repositories. Both svnadmin and svnlook are considered server-side utilities—they are used on the machine where the repository resides to examine or modify aspects of the repository, and are in fact unable to perform tasks across a network. A common mistake made by Subversion newcomers is trying to pass URLs (even «local» file: ones) to these two programs.

So, after you've run the svnadmin create command, you have a shiny new Subversion repository in its own directory. Let's take a peek at what is actually created inside that subdirectory.

$ ls repos
conf/  dav/  db/  format  hooks/  locks/  README.txt

With the exception of the README.txt and format files, the repository directory is a collection of subdirectories. As in other areas of the Subversion design, modularity is given high regard, and hierarchical organization is preferred to cluttered chaos. Here is a brief description of all of the items you see in your new repository directory:

conf

A directory containing repository configuration files.

dav

A directory provided to Apache and mod_dav_svn for their private housekeeping data.

db

Where all of your versioned data resides. This directory is either a Berkeley DB environment (full of DB tables and other things), or is an FSFS environment containing revision files.

format

A file whose contents are a single integer value that dictates the version number of the repository layout.

hooks

A directory full of hook script templates (and hook scripts themselves, once you've installed some).

locks

A directory for Subversion's repository locking data, used for tracking accessors to the repository.

README.txt

A file which merely informs its readers that they are looking at a Subversion repository.

In general, you shouldn't tamper with your repository «by hand». The svnadmin tool should be sufficient for any changes necessary to your repository, or you can look to third-party tools (such as Berkeley DB's tool suite) for tweaking relevant subsections of the repository. Some exceptions exist, though, and we'll cover those here.

Hook Scripts

A hook is a program triggered by some repository event, such as the creation of a new revision or the modification of an unversioned property. Each hook is handed enough information to tell what that event is, what target(s) it's operating on, and the username of the person who triggered the event. Depending on the hook's output or return status, the hook program may continue the action, stop it, or suspend it in some way.

The hooks subdirectory is, by default, filled with templates for various repository hooks.

$ ls repos/hooks/
post-commit.tmpl          post-unlock.tmpl          pre-revprop-change.tmpl
post-lock.tmpl            pre-commit.tmpl           pre-unlock.tmpl
post-revprop-change.tmpl  pre-lock.tmpl             start-commit.tmpl

There is one template for each hook that the Subversion repository implements, and by examining the contents of those template scripts, you can see what triggers each such script to run and what data is passed to that script. Also present in many of these templates are examples of how one might use that script, in conjunction with other Subversion-supplied programs, to perform common useful tasks. To actually install a working hook, you need only place some executable program or script into the repos/hooks directory which can be executed as the name (like start-commit or post-commit) of the hook.

On Unix platforms, this means supplying a script or program (which could be a shell script, a Python program, a compiled C binary, or any number of other things) named exactly like the name of the hook. Of course, the template files are present for more than just informational purposes—the easiest way to install a hook on Unix platforms is to simply copy the appropriate template file to a new file that lacks the .tmpl extension, customize the hook's contents, and ensure that the script is executable. Windows, however, uses file extensions to determine whether or not a program is executable, so you would need to supply a program whose basename is the name of the hook, and whose extension is one of the special extensions recognized by Windows for executable programs, such as .exe or .com for programs, and .bat for batch files.

[Подсказка]Подсказка

For security reasons, the Subversion repository executes hook scripts with an empty environment—that is, no environment variables are set at all, not even $PATH or %PATH%. Because of this, a lot of administrators are baffled when their hook script runs fine by hand, but doesn't work when run by Subversion. Be sure to explicitly set environment variables in your hook and/or use absolute paths to programs.

There are nine hooks implemented by the Subversion repository:

start-commit

This is run before the commit transaction is even created. It is typically used to decide if the user has commit privileges at all. The repository passes two arguments to this program: the path to the repository, and username which is attempting the commit. If the program returns a non-zero exit value, the commit is stopped before the transaction is even created. If the hook program writes data to stderr, it will be marshalled back to the client.

pre-commit

This is run when the transaction is complete, but before it is committed. Typically, this hook is used to protect against commits that are disallowed due to content or location (for example, your site might require that all commits to a certain branch include a ticket number from the bug tracker, or that the incoming log message is non-empty). The repository passes two arguments to this program: the path to the repository, and the name of the transaction being committed. If the program returns a non-zero exit value, the commit is aborted and the transaction is removed. If the hook program writes data to stderr, it will be marshalled back to the client.

The Subversion distribution includes some access control scripts (located in the tools/hook-scripts directory of the Subversion source tree) that can be called from pre-commit to implement fine-grained write-access control. Another option is to use the mod_authz_svn Apache httpd module, which provides both read and write access control on individual directories (see «Per-Directory Access Control»). In a future version of Subversion, we plan to implement access control lists (ACLs) directly in the filesystem.

post-commit

This is run after the transaction is committed, and a new revision is created. Most people use this hook to send out descriptive emails about the commit or to make a backup of the repository. The repository passes two arguments to this program: the path to the repository, and the new revision number that was created. The exit code of the program is ignored.

The Subversion distribution includes mailer.py and commit-email.pl scripts (located in the tools/hook-scripts/ directory of the Subversion source tree) that can be used to send email with (and/or append to a log file) a description of a given commit. This mail contains a list of the paths that were changed, the log message attached to the commit, the author and date of the commit, as well as a GNU diff-style display of the changes made to the various versioned files as part of the commit.

Another useful tool provided by Subversion is the hot-backup.py script (located in the tools/backup/ directory of the Subversion source tree). This script performs hot backups of your Subversion repository (a feature supported by the Berkeley DB database back-end), and can be used to make a per-commit snapshot of your repository for archival or emergency recovery purposes.

pre-revprop-change

Because Subversion's revision properties are not versioned, making modifications to such a property (for example, the svn:log commit message property) will overwrite the previous value of that property forever. Since data can be potentially lost here, Subversion supplies this hook (and its counterpart, post-revprop-change) so that repository administrators can keep records of changes to these items using some external means if they so desire. As a precaution against losing unversioned property data, Subversion clients will not be allowed to remotely modify revision properties at all unless this hook is implemented for your repository.

This hook runs just before such a modification is made to the repository. The repository passes four arguments to this hook: the path to the repository, the revision on which the to-be-modified property exists, the authenticated username of the person making the change, and the name of the property itself.

post-revprop-change

As mentioned earlier, this hook is the counterpart of the pre-revprop-change hook. In fact, for the sake of paranoia this script will not run unless the pre-revprop-change hook exists. When both of these hooks are present, the post-revprop-change hook runs just after a revision property has been changed, and is typically used to send an email containing the new value of the changed property. The repository passes four arguments to this hook: the path to the repository, the revision on which the property exists, the authenticated username of the person making the change, and the name of the property itself.

The Subversion distribution includes a propchange-email.pl script (located in the tools/hook-scripts/ directory of the Subversion source tree) that can be used to send email with (and/or append to a log file) the details of a revision property change. This mail contains the revision and name of the changed property, the user who made the change, and the new property value.

pre-lock

This hook runs whenever someone attempts to lock a file. It can be used to prevent locks altogether, or to create a more complex policy specifying exactly which users are allowed to lock particular paths. If the hook notices a pre-existing lock, then it can also decide whether a user is allowed to «steal» the existing lock. The repository passes three arguments to the hook: the path to the repository, the path being locked, and the user attempting to perform the lock. If the program returns a non-zero exit value, the lock action is aborted and anything printed to stderr is marshalled back to the client.

post-lock

This hook runs after a path is locked. The locked path is passed to the hook's stdin, and the hook also receives two arguments: the path to the repository, and the user who performed the lock. The hook is then free to send email notification or record the event in any way it chooses. Because the lock already happened, the output of the hook is ignored.

pre-unlock

This hook runs whenever someone attempts to remove a lock on a file. It can be used to create policies that specify which users are allowed to unlock particular paths. It's particularly important for determining policies about lock breakage. If user A locks a file, is user B allowed to break the lock? What if the lock is more than a week old? These sorts of things can be decided and enforced by the hook. The repository passes three arguments to the hook: the path to the repository, the path being unlocked, and the user attempting to remove the lock. If the program returns a non-zero exit value, the unlock action is aborted and anything printed to stderr is marshalled back to the client.

post-unlock

This hook runs after a path is unlocked. The unlocked path is passed to the hook's stdin, and the hook also receives two arguments: the path to the repository, and the user who removed the lock. The hook is then free to send email notification or record the event in any way it chooses. Because the lock removal already happened, the output of the hook is ignored.

[Внимание]Внимание

Do not attempt to modify the transaction using hook scripts. A common example of this would be to automatically set properties such as svn:eol-style or svn:mime-type during the commit. While this might seem like a good idea, it causes problems. The main problem is that the client does not know about the change made by the hook script, and there is no way to inform the client that it is out-of-date. This inconsistency can lead to surprising and unexpected behavior.

Instead of attempting to modify the transaction, it is much better to check the transaction in the pre-commit hook and reject the commit if it does not meet the desired requirements.

Subversion will attempt to execute hooks as the same user who owns the process which is accessing the Subversion repository. In most cases, the repository is being accessed via Apache HTTP server and mod_dav_svn, so this user is the same user that Apache runs as. The hooks themselves will need to be configured with OS-level permissions that allow that user to execute them. Also, this means that any file or programs (including the Subversion repository itself) accessed directly or indirectly by the hook will be accessed as the same user. In other words, be alert to potential permission-related problems that could prevent the hook from performing the tasks you've written it to perform.

Berkeley DB Configuration

A Berkeley DB environment is an encapsulation of one or more databases, log files, region files and configuration files. The Berkeley DB environment has its own set of default configuration values for things like the number of database locks allowed to be taken out at any given time, or the maximum size of the journaling log files, etc. Subversion's filesystem code additionally chooses default values for some of the Berkeley DB configuration options. However, sometimes your particular repository, with its unique collection of data and access patterns, might require a different set of configuration option values.

The folks at Sleepycat (the producers of Berkeley DB) understand that different databases have different requirements, and so they have provided a mechanism for overriding at runtime many of the configuration values for the Berkeley DB environment. Berkeley checks for the presence of a file named DB_CONFIG in each environment directory, and parses the options found in that file for use with that particular Berkeley environment.

The Berkeley configuration file for your repository is located in the db environment directory, at repos/db/DB_CONFIG. Subversion itself creates this file when it creates the rest of the repository. The file initially contains some default options, as well as pointers to the Berkeley DB online documentation so you can read about what those options do. Of course, you are free to add any of the supported Berkeley DB options to your DB_CONFIG file. Just be aware that while Subversion never attempts to read or interpret the contents of the file, and makes no use of the option settings in it, you'll want to avoid any configuration changes that may cause Berkeley DB to behave in a fashion that is unexpected by the rest of the Subversion code. Also, changes made to DB_CONFIG won't take effect until you recover the database environment (using svnadmin recover).

Repository Maintenance

Maintaining a Subversion repository can be a daunting task, mostly due to the complexities inherent in systems which have a database backend. Doing the task well is all about knowing the tools—what they are, when to use them, and how to use them. This section will introduce you to the repository administration tools provided by Subversion, and how to wield them to accomplish tasks such as repository migrations, upgrades, backups and cleanups.

An Administrator's Toolkit

Subversion provides a handful of utilities useful for creating, inspecting, modifying and repairing your repository. Let's look more closely at each of those tools. Afterward, we'll briefly examine some of the utilities included in the Berkeley DB distribution that provide functionality specific to your repository's database backend not otherwise provided by Subversion's own tools.

svnlook

svnlook is a tool provided by Subversion for examining the various revisions and transactions in a repository. No part of this program attempts to change the repository—it's a «read-only» tool. svnlook is typically used by the repository hooks for reporting the changes that are about to be committed (in the case of the pre-commit hook) or that were just committed (in the case of the post-commit hook) to the repository. A repository administrator may use this tool for diagnostic purposes.

svnlook has a straightforward syntax:

$ svnlook help
general usage: svnlook SUBCOMMAND REPOS_PATH [ARGS & OPTIONS ...]
Note: any subcommand which takes the '--revision' and '--transaction'
      options will, if invoked without one of those options, act on
      the repository's youngest revision.
Type "svnlook help <subcommand>" for help on a specific subcommand.
…

Nearly every one of svnlook's subcommands can operate on either a revision or a transaction tree, printing information about the tree itself, or how it differs from the previous revision of the repository. You use the --revision and --transaction options to specify which revision or transaction, respectively, to examine. Note that while revision numbers appear as natural numbers, transaction names are alphanumeric strings. Keep in mind that the filesystem only allows browsing of uncommitted transactions (transactions that have not resulted in a new revision). Most repositories will have no such transactions, because transactions are usually either committed (which disqualifies them from viewing) or aborted and removed.

In the absence of both the --revision and --transaction options, svnlook will examine the youngest (or «HEAD») revision in the repository. So the following two commands do exactly the same thing when 19 is the youngest revision in the repository located at /path/to/repos:

$ svnlook info /path/to/repos
$ svnlook info /path/to/repos --revision 19

The only exception to these rules about subcommands is the svnlook youngest subcommand, which takes no options, and simply prints out the HEAD revision number.

$ svnlook youngest /path/to/repos
19

Output from svnlook is designed to be both human- and machine-parsable. Take as an example the output of the info subcommand:

$ svnlook info /path/to/repos
sally
2002-11-04 09:29:13 -0600 (Mon, 04 Nov 2002)
27
Added the usual
Greek tree.

The output of the info subcommand is defined as:

  1. The author, followed by a newline.

  2. The date, followed by a newline.

  3. The number of characters in the log message, followed by a newline.

  4. The log message itself, followed by a newline.

This output is human-readable, meaning items like the datestamp are displayed using a textual representation instead of something more obscure (such as the number of nanoseconds since the Tasty Freeze guy drove by). But this output is also machine-parsable—because the log message can contain multiple lines and be unbounded in length, svnlook provides the length of that message before the message itself. This allows scripts and other wrappers around this command to make intelligent decisions about the log message, such as how much memory to allocate for the message, or at least how many bytes to skip in the event that this output is not the last bit of data in the stream.

Another common use of svnlook is to actually view the contents of a revision or transaction tree. The svnlook tree command displays the directories and files in the requested tree. If you supply the --show-ids option, it will also show the filesystem node revision IDs for each of those paths (which is generally of more use to developers than to users).

$ svnlook tree /path/to/repos --show-ids
/ <0.0.1>
 A/ <2.0.1>
  B/ <4.0.1>
   lambda <5.0.1>
   E/ <6.0.1>
    alpha <7.0.1>
    beta <8.0.1>
   F/ <9.0.1>
  mu <3.0.1>
  C/ <a.0.1>
  D/ <b.0.1>
   gamma <c.0.1>
   G/ <d.0.1>
    pi <e.0.1>
    rho <f.0.1>
    tau <g.0.1>
   H/ <h.0.1>
    chi <i.0.1>
    omega <k.0.1>
    psi <j.0.1>
 iota <1.0.1>

Once you've seen the layout of directories and files in your tree, you can use commands like svnlook cat, svnlook propget, and svnlook proplist to dig into the details of those files and directories.

svnlook can perform a variety of other queries, displaying subsets of bits of information we've mentioned previously, reporting which paths were modified in a given revision or transaction, showing textual and property differences made to files and directories, and so on. The following is a brief description of the current list of subcommands accepted by svnlook, and the output of those subcommands:

author

Print the tree's author.

cat

Print the contents of a file in the tree.

changed

List all files and directories that changed in the tree.

date

Print the tree's datestamp.

diff

Print unified diffs of changed files.

dirs-changed

List the directories in the tree that were themselves changed, or whose file children were changed.

history

Display interesting points in the history of a versioned path (places where modifications or copies occurred).

info

Print the tree's author, datestamp, log message character count, and log message.

lock

If a path is locked, describe the lock attributes.

log

Print the tree's log message.

propget

Print the value of a property on a path in the tree.

proplist

Print the names and values of properties set on paths in the tree.

tree

Print the tree listing, optionally revealing the filesystem node revision IDs associated with each path.

uuid

Print the repository's UUID— Universal Unique IDentifier.

youngest

Print the youngest revision number.

svnadmin

The svnadmin program is the repository administrator's best friend. Besides providing the ability to create Subversion repositories, this program allows you to perform several maintenance operations on those repositories. The syntax of svnadmin is similar to that of svnlook:

$ svnadmin help
general usage: svnadmin SUBCOMMAND REPOS_PATH  [ARGS & OPTIONS ...]
Type "svnadmin help <subcommand>" for help on a specific subcommand.

Available subcommands:
   create
   deltify
   dump
   help (?, h)
…

We've already mentioned svnadmin's create subcommand (see «Repository Creation and Configuration»). Most of the others we will cover in more detail later in this chapter. For now, let's just take a quick glance at what each of the available subcommands offers.

create

Create a new Subversion repository.

deltify

Run over a specified revision range, performing predecessor deltification on the paths changed in those revisions. If no revisions are specified, this command will simply deltify the HEAD revision.

dump

Dump the contents of the repository, bounded by a given set of revisions, using a portable dump format.

hotcopy

Make a hot copy of a repository. You can run this command at any time and make a safe copy of the repository, regardless if other processes are using the repository.

list-dblogs

(Berkeley DB repositories only.) List the paths of Berkeley DB log files associated with the repository. This list includes all log files—those still in use by Subversion, as well as those no longer in use.

list-unused-dblogs

(Berkeley DB repositories only.) List the paths of Berkeley DB log files associated with, but no longer used by, the repository. You may safely remove these log files from the repository layout, possibly archiving them for use in the event that you ever need to perform a catastrophic recovery of the repository.

load

Load a set of revisions into a repository from a stream of data that uses the same portable dump format generated by the dump subcommand.

lslocks

List and describe any locks that exist in the repository.

lstxns

List the names of uncommitted Subversion transactions that currently exist in the repository.

recover

Perform recovery steps on a repository that is in need of such, generally after a fatal error has occurred that prevented a process from cleanly shutting down its communication with the repository.

rmlocks

Unconditionally remove locks from listed paths.

rmtxns

Cleanly remove Subversion transactions from the repository (conveniently fed by output from the lstxns subcommand).

setlog

Replace the current value of the svn:log (commit log message) property on a given revision in the repository with a new value.

verify

Verify the contents of the repository. This includes, among other things, checksum comparisons of the versioned data stored in the repository.

svndumpfilter

Since Subversion stores everything in an opaque database system, attempting manual tweaks is unwise, if not quite difficult. And once data has been stored in your repository, Subversion generally doesn't provide an easy way to remove that data. [32] But inevitably, there will be times when you would like to manipulate the history of your repository. You might need to strip out all instances of a file that was accidentally added to the repository (and shouldn't be there for whatever reason). Or, perhaps you have multiple projects sharing a single repository, and you decide to split them up into their own repositories. To accomplish tasks like this, administrators need a more manageable and malleable representation of the data in their repositories—the Subversion repository dump format.

The Subversion repository dump format is a human-readable representation of the changes that you've made to your versioned data over time. You use the svnadmin dump command to generate the dump data, and svnadmin load to populate a new repository with it (see «Migrating a Repository»). The great thing about the human-readability aspect of the dump format is that, if you aren't careless about it, you can manually inspect and modify it. Of course, the downside is that if you have two years' worth of repository activity encapsulated in what is likely to be a very large dump file, it could take you a long, long time to manually inspect and modify it.

While it won't be the most commonly used tool at the administrator's disposal, svndumpfilter provides a very particular brand of useful functionality—the ability to quickly and easily modify that dump data by acting as a path-based filter. Simply give it either a list of paths you wish to keep, or a list of paths you wish to not keep, then pipe your repository dump data through this filter. The result will be a modified stream of dump data that contains only the versioned paths you (explicitly or implicitly) requested.

The syntax of svndumpfilter is as follows:

$ svndumpfilter help
general usage: svndumpfilter SUBCOMMAND [ARGS & OPTIONS ...]
Type "svndumpfilter help <subcommand>" for help on a specific subcommand.

Available subcommands:
   exclude
   include
   help (?, h)

There are only two interesting subcommands. They allow you to make the choice between explicit or implicit inclusion of paths in the stream:

exclude

Filter out a set of paths from the dump data stream.

include

Allow only the requested set of paths to pass through the dump data stream.

Let's look a realistic example of how you might use this program. We discuss elsewhere (see «Choosing a Repository Layout») the process of deciding how to choose a layout for the data in your repositories—using one repository per project or combining them, arranging stuff within your repository, and so on. But sometimes after new revisions start flying in, you rethink your layout and would like to make some changes. A common change is the decision to move multiple projects which are sharing a single repository into separate repositories for each project.

Our imaginary repository contains three projects: calc, calendar, and spreadsheet. They have been living side-by-side in a layout like this:

/
   calc/
      trunk/
      branches/
      tags/
   calendar/
      trunk/
      branches/
      tags/
   spreadsheet/
      trunk/
      branches/
      tags/

To get these three projects into their own repositories, we first dump the whole repository:

$ svnadmin dump /path/to/repos > repos-dumpfile
* Dumped revision 0.
* Dumped revision 1.
* Dumped revision 2.
* Dumped revision 3.
…
$

Next, run that dump file through the filter, each time including only one of our top-level directories, and resulting in three new dump files:

$ svndumpfilter include calc < repos-dumpfile > calc-dumpfile
…
$ svndumpfilter include calendar < repos-dumpfile > cal-dumpfile
…
$ svndumpfilter include spreadsheet < repos-dumpfile > ss-dumpfile
…
$

At this point, you have to make a decision. Each of your dump files will create a valid repository, but will preserve the paths exactly as they were in the original repository. This means that even though you would have a repository solely for your calc project, that repository would still have a top-level directory named calc. If you want your trunk, tags, and branches directories to live in the root of your repository, you might wish to edit your dump files, tweaking the Node-path and Node-copyfrom-path headers to no longer have that first calc/ path component. Also, you'll want to remove the section of dump data that creates the calc directory. It will look something like:

Node-path: calc
Node-action: add
Node-kind: dir
Content-length: 0

[Внимание]Внимание

If you do plan on manually editing the dump file to remove a top-level directory, make sure that your editor is not set to automatically convert end-lines to the native format (e.g. \r\n to \n) as the content will then not agree with the metadata and this will render the dump file useless.

All that remains now is to create your three new repositories, and load each dump file into the right repository:

$ svnadmin create calc; svnadmin load calc < calc-dumpfile
<<< Started new transaction, based on original revision 1
     * adding path : Makefile ... done.
     * adding path : button.c ... done.
…
$ svnadmin create calendar; svnadmin load calendar < cal-dumpfile
<<< Started new transaction, based on original revision 1
     * adding path : Makefile ... done.
     * adding path : cal.c ... done.
…
$ svnadmin create spreadsheet; svnadmin load spreadsheet < ss-dumpfile
<<< Started new transaction, based on original revision 1
     * adding path : Makefile ... done.
     * adding path : ss.c ... done.
…
$

Both of svndumpfilter's subcommands accept options for deciding how to deal with «empty» revisions. If a given revision contained only changes to paths that were filtered out, that now-empty revision could be considered uninteresting or even unwanted. So to give the user control over what to do with those revisions, svndumpfilter provides the following command-line options:

--drop-empty-revs

Do not generate empty revisions at all—just omit them.

--renumber-revs

If empty revisions are dropped (using the --drop-empty-revs option), change the revision numbers of the remaining revisions so that there are no gaps in the numeric sequence.

--preserve-revprops

If empty revisions are not dropped, preserve the revision properties (log message, author, date, custom properties, etc.) for those empty revisions. Otherwise, empty revisions will only contain the original datestamp, and a generated log message that indicates that this revision was emptied by svndumpfilter.

While svndumpfilter can be very useful, and a huge timesaver, there are unfortunately a couple of gotchas. First, this utility is overly sensitive to path semantics. Pay attention to whether paths in your dump file are specified with or without leading slashes. You'll want to look at the Node-path and Node-copyfrom-path headers.

…
Node-path: spreadsheet/Makefile
…

If the paths have leading slashes, you should include leading slashes in the paths you pass to svndumpfilter include and svndumpfilter exclude (and if they don't, you shouldn't). Further, if your dump file has an inconsistent usage of leading slashes for some reason, [33] you should probably normalize those paths so they all have, or lack, leading slashes.

Also, copied paths can give you some trouble. Subversion supports copy operations in the repository, where a new path is created by copying some already existing path. It is possible that at some point in the lifetime of your repository, you might have copied a file or directory from some location that svndumpfilter is excluding, to a location that it is including. In order to make the dump data self-sufficient, svndumpfilter needs to still show the addition of the new path—including the contents of any files created by the copy—and not represent that addition as a copy from a source that won't exist in your filtered dump data stream. But because the Subversion repository dump format only shows what was changed in each revision, the contents of the copy source might not be readily available. If you suspect that you have any copies of this sort in your repository, you might want to rethink your set of included/excluded paths.

Berkeley DB Utilities

If you're using a Berkeley DB repository, then all of your versioned filesystem's structure and data live in a set of database tables within the db subdirectory of your repository. This subdirectory is a regular Berkeley DB environment directory, and can therefore be used in conjunction with any of the Berkeley database tools (you can see the documentation for these tools at Sleepycat's website, http://www.sleepycat.com/).

For day-to-day Subversion use, these tools are unnecessary. Most of the functionality typically needed for Subversion repositories has been duplicated in the svnadmin tool. For example, svnadmin list-unused-dblogs and svnadmin list-dblogs perform a subset of what is provided by the Berkeley db_archive command, and svnadmin recover reflects the common use cases of the db_recover utility.

There are still a few Berkeley DB utilities that you might find useful. The db_dump and db_load programs write and read, respectively, a custom file format which describes the keys and values in a Berkeley DB database. Since Berkeley databases are not portable across machine architectures, this format is a useful way to transfer those databases from machine to machine, irrespective of architecture or operating system. Also, the db_stat utility can provide useful information about the status of your Berkeley DB environment, including detailed statistics about the locking and storage subsystems.

Repository Cleanup

Your Subversion repository will generally require very little attention once it is configured to your liking. However, there are times when some manual assistance from an administrator might be in order. The svnadmin utility provides some helpful functionality to assist you in performing such tasks as:

  • modifying commit log messages,

  • removing dead transactions,

  • recovering «wedged» repositories, and

  • migrating repository contents to a different repository.

Perhaps the most commonly used of svnadmin's subcommands is setlog. When a transaction is committed to the repository and promoted to a revision, the descriptive log message associated with that new revision (and provided by the user) is stored as an unversioned property attached to the revision itself. In other words, the repository remembers only the latest value of the property, and discards previous ones.

Sometimes a user will have an error in her log message (a misspelling or some misinformation, perhaps). If the repository is configured (using the pre-revprop-change and post-revprop-change hooks; see «Hook Scripts») to accept changes to this log message after the commit is finished, then the user can «fix» her log message remotely using the svn program's propset command (see Глава 9, Полное справочное руководство по Subversion). However, because of the potential to lose information forever, Subversion repositories are not, by default, configured to allow changes to unversioned properties—except by an administrator.

If a log message needs to be changed by an administrator, this can be done using svnadmin setlog. This command changes the log message (the svn:log property) on a given revision of a repository, reading the new value from a provided file.

$ echo "Here is the new, correct log message" > newlog.txt
$ svnadmin setlog myrepos newlog.txt -r 388

The svnadmin setlog command alone is still bound by the same protections against modifying unversioned properties as a remote client is—the pre- and post-revprop-change hooks are still triggered, and therefore must be setup to accept changes of this nature. But an administrator can get around these protections by passing the --bypass-hooks option to the svnadmin setlog command.

[Внимание]Внимание

Remember, though, that by bypassing the hooks, you are likely avoiding such things as email notifications of property changes, backup systems which track unversioned property changes, and so on. In other words, be very careful about what you are changing, and how you change it.

Another common use of svnadmin is to query the repository for outstanding—possibly dead—Subversion transactions. In the event that a commit should fail, the transaction is usually cleaned up. That is, the transaction itself is removed from the repository, and any data associated with (and only with) that transaction is removed as well. Occasionally, though, a failure occurs in such a way that the cleanup of the transaction never happens. This could happen for several reasons: perhaps the client operation was inelegantly terminated by the user, or a network failure might have occurred in the middle of an operation, etc. Regardless of the reason, dead transactions can happen. They don't do any real harm, other than consuming a small bit of disk space. A fastidious administrator may nonetheless want to remove them.

You can use svnadmin's lstxns command to list the names of the currently outstanding transactions.

$ svnadmin lstxns myrepos
19
3a1
a45
$

Each item in the resultant output can then be used with svnlook (and its --transaction option) to determine who created the transaction, when it was created, what types of changes were made in the transaction—in other words, whether or not the transaction is a safe candidate for removal! If so, the transaction's name can be passed to svnadmin rmtxns, which will perform the cleanup of the transaction. In fact, the rmtxns subcommand can take its input directly from the output of lstxns!

$ svnadmin rmtxns myrepos `svnadmin lstxns myrepos`
$

If you use these two subcommands like this, you should consider making your repository temporarily inaccessible to clients. That way, no one can begin a legitimate transaction before you start your cleanup. The following is a little bit of shell-scripting that can quickly generate information about each outstanding transaction in your repository:

Пример 5.1. txn-info.sh (Reporting Outstanding Transactions)

#!/bin/sh

### Generate informational output for all outstanding transactions in
### a Subversion repository.

REPOS="${1}"
if [ "x$REPOS" = x ] ; then
  echo "usage: $0 REPOS_PATH"
  exit
fi

for TXN in `svnadmin lstxns ${REPOS}`; do
  echo "---[ Transaction ${TXN} ]-------------------------------------------"
  svnlook info "${REPOS}" --transaction "${TXN}"
done


You can run the previous script using /path/to/txn-info.sh /path/to/repos. The output is basically a concatenation of several chunks of svnlook info output (see «svnlook»), and will look something like:

$ txn-info.sh myrepos
---[ Transaction 19 ]-------------------------------------------
sally
2001-09-04 11:57:19 -0500 (Tue, 04 Sep 2001)
0
---[ Transaction 3a1 ]-------------------------------------------
harry
2001-09-10 16:50:30 -0500 (Mon, 10 Sep 2001)
39
Trying to commit over a faulty network.
---[ Transaction a45 ]-------------------------------------------
sally
2001-09-12 11:09:28 -0500 (Wed, 12 Sep 2001)
0
$

A long-abandoned transaction usually represents some sort of failed or interrupted commit. A transaction's datestamp can provide interesting information—for example, how likely is it that an operation begun nine months ago is still active?

In short, transaction cleanup decisions need not be made unwisely. Various sources of information—including Apache's error and access logs, the logs of successful Subversion commits, and so on—can be employed in the decision-making process. Finally, an administrator can often simply communicate with a seemingly dead transaction's owner (via email, for example) to verify that the transaction is, in fact, in a zombie state.

Managing Disk Space

While the cost of storage has dropped incredibly in the past few years, disk usage is still a valid concern for administrators seeking to version large amounts of data. Every additional byte consumed by the live repository is a byte that needs to be backed up offsite, perhaps multiple times as part of rotating backup schedules. If using a Berkeley DB repository, the primary storage mechanism is a complex database system, it is useful to know what pieces of data need to remain on the live site, which need to be backed up, and which can be safely removed. This section is specific to Berkeley DB; FSFS repositories have no extra data to be cleaned up or reclaimed.

Until recently, the largest offender of disk space usage with respect to Subversion repositories was the log files to which Berkeley DB performs its pre-writes before modifying the actual database files. These files capture all the actions taken along the route of changing the database from one state to another—while the database files reflect at any given time some state, the log files contain all the many changes along the way between states. As such, they can start to accumulate quite rapidly.

Fortunately, beginning with the 4.2 release of Berkeley DB, the database environment has the ability to remove its own unused log files without any external procedures. Any repositories created using an svnadmin which is compiled against Berkeley DB version 4.2 or greater will be configured for this automatic log file removal. If you don't want this feature enabled, simply pass the --bdb-log-keep option to the svnadmin create command. If you forget to do this, or change your mind at a later time, simple edit the DB_CONFIG file found in your repository's db directory, comment out the line which contains the set_flags DB_LOG_AUTOREMOVE directive, and then run svnadmin recover on your repository to force the configuration changes to take effect. See «Berkeley DB Configuration» for more information about database configuration.

Without some sort of automatic log file removal in place, log files will accumulate as you use your repository. This is actually somewhat of a feature of the database system—you should be able to recreate your entire database using nothing but the log files, so these files can be useful for catastrophic database recovery. But typically, you'll want to archive the log files that are no longer in use by Berkeley DB, and then remove them from disk to conserve space. Use the svnadmin list-unused-dblogs command to list the unused log files:

$ svnadmin list-unused-dblogs /path/to/repos
/path/to/repos/log.0000000031
/path/to/repos/log.0000000032
/path/to/repos/log.0000000033

$ svnadmin list-unused-dblogs /path/to/repos | xargs rm
## disk space reclaimed!

To keep the size of the repository as small as possible, Subversion uses deltification (or, «deltified storage») within the repository itself. Deltification involves encoding the representation of a chunk of data as a collection of differences against some other chunk of data. If the two pieces of data are very similar, this deltification results in storage savings for the deltified chunk—rather than taking up space equal to the size of the original data, it only takes up enough space to say, «I look just like this other piece of data over here, except for the following couple of changes». Specifically, each time a new version of a file is committed to the repository, Subversion encodes the previous version (actually, several previous versions) as a delta against the new version. The result is that most of the repository data that tends to be sizable—namely, the contents of versioned files—is stored at a much smaller size than the original «fulltext» representation of that data.

[Замечание]Замечание

Because all of the Subversion repository data that is subject to deltification is stored in a single Berkeley DB database file, reducing the size of the stored values will not necessarily reduce the size of the database file itself. Berkeley DB will, however, keep internal records of unused areas of the database file, and use those areas first before growing the size of the database file. So while deltification doesn't produce immediate space savings, it can drastically slow future growth of the database.

Repository Recovery

As mentioned in «Berkeley DB», a Berkeley DB repository can sometimes be left in frozen state if not closed properly. When this happens, an administrator needs to rewind the database back into a consistent state.

In order to protect the data in your repository, Berkeley DB uses a locking mechanism. This mechanism ensures that portions of the database are not simultaneously modified by multiple database accessors, and that each process sees the data in the correct state when that data is being read from the database. When a process needs to change something in the database, it first checks for the existence of a lock on the target data. If the data is not locked, the process locks the data, makes the change it wants to make, and then unlocks the data. Other processes are forced to wait until that lock is removed before they are permitted to continue accessing that section of the database. (This has nothing to do with the locks that you, as a user, can apply to versioned files within the repository; see Three meanings of «lock» for more information.)

In the course of using your Subversion repository, fatal errors (such as running out of disk space or available memory) or interruptions can prevent a process from having the chance to remove the locks it has placed in the database. The result is that the back-end database system gets «wedged». When this happens, any attempts to access the repository hang indefinitely (since each new accessor is waiting for a lock to go away—which isn't going to happen).

First, if this happens to your repository, don't panic. The Berkeley DB filesystem takes advantage of database transactions and checkpoints and pre-write journaling to ensure that only the most catastrophic of events [34] can permanently destroy a database environment. A sufficiently paranoid repository administrator will be making off-site backups of the repository data in some fashion, but don't call your system administrator to restore a backup tape just yet.

Secondly, use the following recipe to attempt to «unwedge» your repository:

  1. Make sure that there are no processes accessing (or attempting to access) the repository. For networked repositories, this means shutting down the Apache HTTP Server, too.

  2. Become the user who owns and manages the repository. This is important, as recovering a repository while running as the wrong user can tweak the permissions of the repository's files in such a way that your repository will still be inaccessible even after it is «unwedged».

  3. Run the command svnadmin recover /path/to/repos. You should see output like this:

    Repository lock acquired.
    Please wait; recovering the repository may take some time...
    
    Recovery completed.
    The latest repos revision is 19.
    

    This command may take many minutes to complete.

  4. Restart the Subversion server.

This procedure fixes almost every case of repository lock-up. Make sure that you run this command as the user that owns and manages the database, not just as root. Part of the recovery process might involve recreating from scratch various database files (shared memory regions, for example). Recovering as root will create those files such that they are owned by root, which means that even after you restore connectivity to your repository, regular users will be unable to access it.

If the previous procedure, for some reason, does not successfully unwedge your repository, you should do two things. First, move your broken repository out of the way and restore your latest backup of it. Then, send an email to the Subversion user list (at ) describing your problem in detail. Data integrity is an extremely high priority to the Subversion developers.

Migrating a Repository

A Subversion filesystem has its data spread throughout various database tables in a fashion generally understood by (and of interest to) only the Subversion developers themselves. However, circumstances may arise that call for all, or some subset, of that data to be collected into a single, portable, flat file format. Subversion provides such a mechanism, implemented in a pair of svnadmin subcommands: dump and load.

The most common reason to dump and load a Subversion repository is due to changes in Subversion itself. As Subversion matures, there are times when certain changes made to the back-end database schema cause Subversion to be incompatible with previous versions of the repository. Other reasons for dumping and loading might be to migrate a Berkeley DB repository to a new OS or CPU architecture, or to switch between Berkeley DB and FSFS back-ends. The recommended course of action is relatively simple:

  1. Using your current version of svnadmin, dump your repositories to dump files.

  2. Upgrade to the new version of Subversion.

  3. Move your old repositories out of the way, and create new empty ones in their place using your new svnadmin.

  4. Again using your new svnadmin, load your dump files into their respective, just-created repositories.

  5. Be sure to copy any customizations from your old repositories to the new ones, including DB_CONFIG files and hook scripts. You'll want to pay attention to the release notes for the new release of Subversion to see if any changes since your last upgrade affect those hooks or configuration options.

  6. If the migration process made your repository accessible at a different URL (e.g. moved to a different computer, or is being accessed via a different schema), then you'll probably want to tell your users to run svn switch --relocate on their existing working copies. See svn switch.

svnadmin dump will output a range of repository revisions that are formatted using Subversion's custom filesystem dump format. The dump format is printed to the standard output stream, while informative messages are printed to the standard error stream. This allows you to redirect the output stream to a file while watching the status output in your terminal window. For example:

$ svnlook youngest myrepos
26
$ svnadmin dump myrepos > dumpfile
* Dumped revision 0.
* Dumped revision 1.
* Dumped revision 2.
…
* Dumped revision 25.
* Dumped revision 26.

At the end of the process, you will have a single file (dumpfile in the previous example) that contains all the data stored in your repository in the requested range of revisions. Note that svnadmin dump is reading revision trees from the repository just like any other «reader» process would (svn checkout, for example). So it's safe to run this command at any time.

The other subcommand in the pair, svnadmin load, parses the standard input stream as a Subversion repository dump file, and effectively replays those dumped revisions into the target repository for that operation. It also gives informative feedback, this time using the standard output stream:

$ svnadmin load newrepos < dumpfile
<<< Started new txn, based on original revision 1
     * adding path : A ... done.
     * adding path : A/B ... done.
     …
------- Committed new rev 1 (loaded from original rev 1) >>>

<<< Started new txn, based on original revision 2
     * editing path : A/mu ... done.
     * editing path : A/D/G/rho ... done.

------- Committed new rev 2 (loaded from original rev 2) >>>

…

<<< Started new txn, based on original revision 25
     * editing path : A/D/gamma ... done.

------- Committed new rev 25 (loaded from original rev 25) >>>

<<< Started new txn, based on original revision 26
     * adding path : A/Z/zeta ... done.
     * editing path : A/mu ... done.

------- Committed new rev 26 (loaded from original rev 26) >>>

The result of a load is new revisions added to a repository—the same thing you get by making commits against that repository from a regular Subversion client. And just as in a commit, you can use hook scripts to perform actions before and after each of the commits made during a load process. By passing the --use-pre-commit-hook and --use-post-commit-hook options to svnadmin load, you can instruct Subversion to execute the pre-commit and post-commit hook scripts, respectively, for each loaded revision. You might use these, for example, to ensure that loaded revisions pass through the same validation steps that regular commits pass through. Of course, you should use these options with care—if your post-commit hook sends emails to a mailing list for each new commit, you might not want to spew hundreds or thousands of commit emails in rapid succession at that list for each of the loaded revisions! You can read more about the use of hook scripts in «Hook Scripts».

Note that because svnadmin uses standard input and output streams for the repository dump and load process, people who are feeling especially saucy can try things like this (perhaps even using different versions of svnadmin on each side of the pipe):

$ svnadmin create newrepos
$ svnadmin dump myrepos | svnadmin load newrepos

By default, the dump file will be quite large—much larger than the repository itself. That's because every version of every file is expressed as a full text in the dump file. This is the fastest and simplest behavior, and nice if you're piping the dump data directly into some other process (such as a compression program, filtering program, or into a loading process). But if you're creating a dump file for longer-term storage, you'll likely want to save disk space by using the --deltas switch. With this option, successive revisions of files will be output as compressed, binary differences—just as file revisions are stored in a repository. This option is slower, but results in a dump file much closer in size to the original repository.

We mentioned previously that svnadmin dump outputs a range of revisions. Use the --revision option to specify a single revision to dump, or a range of revisions. If you omit this option, all the existing repository revisions will be dumped.

$ svnadmin dump myrepos --revision 23 > rev-23.dumpfile
$ svnadmin dump myrepos --revision 100:200 > revs-100-200.dumpfile

As Subversion dumps each new revision, it outputs only enough information to allow a future loader to re-create that revision based on the previous one. In other words, for any given revision in the dump file, only the items that were changed in that revision will appear in the dump. The only exception to this rule is the first revision that is dumped with the current svnadmin dump command.

By default, Subversion will not express the first dumped revision as merely differences to be applied to the previous revision. For one thing, there is no previous revision in the dump file! And secondly, Subversion cannot know the state of the repository into which the dump data will be loaded (if it ever, in fact, occurs). To ensure that the output of each execution of svnadmin dump is self-sufficient, the first dumped revision is by default a full representation of every directory, file, and property in that revision of the repository.

However, you can change this default behavior. If you add the --incremental option when you dump your repository, svnadmin will compare the first dumped revision against the previous revision in the repository, the same way it treats every other revision that gets dumped. It will then output the first revision exactly as it does the rest of the revisions in the dump range—mentioning only the changes that occurred in that revision. The benefit of this is that you can create several small dump files that can be loaded in succession, instead of one large one, like so:

$ svnadmin dump myrepos --revision 0:1000 > dumpfile1
$ svnadmin dump myrepos --revision 1001:2000 --incremental > dumpfile2
$ svnadmin dump myrepos --revision 2001:3000 --incremental > dumpfile3

These dump files could be loaded into a new repository with the following command sequence:

$ svnadmin load newrepos < dumpfile1
$ svnadmin load newrepos < dumpfile2
$ svnadmin load newrepos < dumpfile3

Another neat trick you can perform with this --incremental option involves appending to an existing dump file a new range of dumped revisions. For example, you might have a post-commit hook that simply appends the repository dump of the single revision that triggered the hook. Or you might have a script that runs nightly to append dump file data for all the revisions that were added to the repository since the last time the script ran. Used like this, svnadmin's dump and load commands can be a valuable means by which to backup changes to your repository over time in case of a system crash or some other catastrophic event.

The dump format can also be used to merge the contents of several different repositories into a single repository. By using the --parent-dir option of svnadmin load, you can specify a new virtual root directory for the load process. That means if you have dump files for three repositories, say calc-dumpfile, cal-dumpfile, and ss-dumpfile, you can first create a new repository to hold them all:

$ svnadmin create /path/to/projects
$

Then, make new directories in the repository which will encapsulate the contents of each of the three previous repositories:

$ svn mkdir -m "Initial project roots" \
      file:///path/to/projects/calc \
      file:///path/to/projects/calendar \
      file:///path/to/projects/spreadsheet
Committed revision 1.
$

Lastly, load the individual dump files into their respective locations in the new repository:

$ svnadmin load /path/to/projects --parent-dir calc < calc-dumpfile
…
$ svnadmin load /path/to/projects --parent-dir calendar < cal-dumpfile
…
$ svnadmin load /path/to/projects --parent-dir spreadsheet < ss-dumpfile
…
$

We'll mention one final way to use the Subversion repository dump format—conversion from a different storage mechanism or version control system altogether. Because the dump file format is, for the most part, human-readable, [35] it should be relatively easy to describe generic sets of changes—each of which should be treated as a new revision—using this file format. In fact, the cvs2svn utility (see «Converting a Repository from CVS to Subversion») uses the dump format to represent the contents of a CVS repository so that those contents can be copied into a Subversion repository.

Repository Backup

Despite numerous advances in technology since the birth of the modern computer, one thing unfortunately rings true with crystalline clarity—sometimes, things go very, very awry. Power outages, network connectivity dropouts, corrupt RAM and crashed hard drives are but a taste of the evil that Fate is poised to unleash on even the most conscientious administrator. And so we arrive at a very important topic—how to make backup copies of your repository data.

There are generally two types of backup methods available for Subversion repository administrators—incremental and full. We discussed in an earlier section of this chapter how to use svnadmin dump --incremental to perform an incremental backup (see «Migrating a Repository»). Essentially, the idea is to only backup at a given time the changes to the repository since the last time you made a backup.

A full backup of the repository is quite literally a duplication of the entire repository directory (which includes either Berkeley database or FSFS environment). Now, unless you temporarily disable all other access to your repository, simply doing a recursive directory copy runs the risk of generating a faulty backup, since someone might be currently writing to the database.

In the case of Berkeley DB, Sleepycat documents describe a certain order in which database files can be copied that will guarantee a valid backup copy. And a similar ordering exists for FSFS data. Better still, you don't have to implement these algorithms yourself, because the Subversion development team has already done so. The hot-backup.py script is found in the tools/backup/ directory of the Subversion source distribution. Given a repository path and a backup location, hot-backup.py—which is really just a more intelligent wrapper around the svnadmin hotcopy command—will perform the necessary steps for backing up your live repository—without requiring that you bar public repository access at all—and then will clean out the dead Berkeley log files from your live repository.

Even if you also have an incremental backup, you might want to run this program on a regular basis. For example, you might consider adding hot-backup.py to a program scheduler (such as cron on Unix systems). Or, if you prefer fine-grained backup solutions, you could have your post-commit hook script call hot-backup.py (see «Hook Scripts»), which will then cause a new backup of your repository to occur with every new revision created. Simply add the following to the hooks/post-commit script in your live repository directory:

(cd /path/to/hook/scripts; ./hot-backup.py ${REPOS} /path/to/backups &)

The resulting backup is a fully functional Subversion repository, able to be dropped in as a replacement for your live repository should something go horribly wrong.

There are benefits to both types of backup methods. The easiest is by far the full backup, which will always result in a perfect working replica of your repository. This again means that should something bad happen to your live repository, you can restore from the backup with a simple recursive directory copy. Unfortunately, if you are maintaining multiple backups of your repository, these full copies will each eat up just as much disk space as your live repository.

Incremental backups using the repository dump format are excellent to have on hand if the database schema changes between successive versions of Subversion itself. Since a complete repository dump and load are generally required to upgrade your repository to the new schema, it's very convenient to already have half of that process (the dump part) finished. Unfortunately, the creation of—and restoration from—incremental backups takes longer, as each commit is effectively replayed into either the dump file or the repository.

In either backup scenario, repository administrators need to be aware of how modifications to unversioned revision properties affect their backups. Since these changes do not themselves generate new revisions, they will not trigger post-commit hooks, and may not even trigger the pre-revprop-change and post-revprop-change hooks. [36] And since you can change revision properties without respect to chronological order—you can change any revision's properties at any time—an incremental backup of the latest few revisions might not catch a property modification to a revision that was included as part of a previous backup.

Generally speaking, only the truly paranoid would need to backup their entire repository, say, every time a commit occurred. However, assuming that a given repository has some other redundancy mechanism in place with relatively fine granularity (like per-commit emails), a hot backup of the database might be something that a repository administrator would want to include as part of a system-wide nightly backup. For most repositories, archived commit emails alone provide sufficient redundancy as restoration sources, at least for the most recent few commits. But it's your data—protect it as much as you'd like.

Often, the best approach to repository backups is a diversified one. You can leverage combinations of full and incremental backups, plus archives of commit emails. The Subversion developers, for example, back up the Subversion source code repository after every new revision is created, and keep an archive of all the commit and property change notification emails. Your solution might be similar, but should be catered to your needs and that delicate balance of convenience with paranoia. And while all of this might not save your hardware from the iron fist of Fate, [37] it should certainly help you recover from those trying times.

Adding Projects

Once your repository is created and configured, all that remains is to begin using it. If you have a collection of existing data that is ready to be placed under version control, you will more than likely want to use the svn client program's import subcommand to accomplish that. Before doing this, though, you should carefully consider your long-term plans for the repository. In this section, we will offer some advice on how to plan the layout of your repository, and how to get your data arranged in that layout.

Choosing a Repository Layout

While Subversion allows you to move around versioned files and directories without any loss of information, doing so can still disrupt the workflow of those who access the repository often and come to expect things to be at certain locations. Try to peer into the future a bit; plan ahead before placing your data under version control. By «laying out» the contents of your repositories in an effective manner the first time, you can prevent a load of future headaches.

There are a few things to consider when setting up Subversion repositories. Let's assume that as repository administrator, you will be responsible for supporting the version control system for several projects. The first decision is whether to use a single repository for multiple projects, or to give each project its own repository, or some compromise of these two.

There are benefits to using a single repository for multiple projects, most obviously the lack of duplicated maintenance. A single repository means that there is one set of hook scripts, one thing to routinely backup, one thing to dump and load if Subversion releases an incompatible new version, and so on. Also, you can move data between projects easily, and without losing any historical versioning information.

The downside of using a single repository is that different projects may have different commit mailing lists or different authentication and authorization requirements. Also, remember that Subversion uses repository-global revision numbers. Some folks don't like the fact that even though no changes have been made to their project lately, the youngest revision number for the repository keeps climbing because other projects are actively adding new revisions.

A middle-ground approach can be taken, too. For example, projects can be grouped by how well they relate to each other. You might have a few repositories with a handful of projects in each repository. That way, projects that are likely to want to share data can do so easily, and as new revisions are added to the repository, at least the developers know that those new revisions are at least remotely related to everyone who uses that repository.

After deciding how to organize your projects with respect to repositories, you'll probably want to think about directory hierarchies in the repositories themselves. Because Subversion uses regular directory copies for branching and tagging (see Глава 4, Ветвление и слияние), the Subversion community recommends that you choose a repository location for each project root—the «top-most» directory which contains data related to that project—and then create three subdirectories beneath that root: trunk, meaning the directory under which the main project development occurs; branches, which is a directory in which to create various named branches of the main development line; tags, which is a directory of branches that are created, and perhaps destroyed, but never changed. [38]

For example, your repository might look like:

/
   calc/
      trunk/
      tags/
      branches/
   calendar/
      trunk/
      tags/
      branches/
   spreadsheet/
      trunk/
      tags/
      branches/
   …

Note that it doesn't matter where in your repository each project root is. If you have only one project per repository, the logical place to put each project root is at the root of that project's respective repository. If you have multiple projects, you might want to arrange them in groups inside the repository, perhaps putting projects with similar goals or shared code in the same subdirectory, or maybe just grouping them alphabetically. Such an arrangement might look like:

/
   utils/
      calc/
         trunk/
         tags/
         branches/
      calendar/
         trunk/
         tags/
         branches/
      …
   office/
      spreadsheet/
         trunk/
         tags/
         branches/
      …

Lay out your repository in whatever way you see fit. Subversion does not expect or enforce a layout schema—in its eyes, a directory is a directory is a directory. Ultimately, you should choose the repository arrangement that meets the needs of the people who work on the projects that live there.

Creating the Layout, and Importing Initial Data

After deciding how to arrange the projects in your repository, you'll probably want to actually populate the repository with that layout and with initial project data. There are a couple of ways to do this in Subversion. You could use the svn mkdir command (see Глава 9, Полное справочное руководство по Subversion) to create each directory in your skeletal repository layout, one-by-one. A quicker way to accomplish the same task is to use the svn import command (see «svn import»). By first creating the layout in a temporary location on your drive, you can import the whole layout tree into the repository in a single commit:

$ mkdir tmpdir
$ cd tmpdir
$ mkdir projectA
$ mkdir projectA/trunk
$ mkdir projectA/branches
$ mkdir projectA/tags
$ mkdir projectB
$ mkdir projectB/trunk
$ mkdir projectB/branches
$ mkdir projectB/tags
…
$ svn import . file:///path/to/repos --message "Initial repository layout"
Adding         projectA
Adding         projectA/trunk
Adding         projectA/branches
Adding         projectA/tags
Adding         projectB
Adding         projectB/trunk
Adding         projectB/branches
Adding         projectB/tags
…
Committed revision 1.
$ cd ..
$ rm -rf tmpdir
$

You can verify the results of the import by running the svn list command:

$ svn list --verbose file:///path/to/repos
      1 harry               May 08 21:48 projectA/
      1 harry               May 08 21:48 projectB/
…
$

Once you have your skeletal layout in place, you can begin importing actual project data into your repository, if any such data exists yet. Once again, there are several ways to do this. You could use the svn import command. You could checkout a working copy from your new repository, move and arrange project data inside the working copy, and use the svn add and svn commit commands. But once we start talking about such things, we're no longer discussing repository administration. If you aren't already familiar with the svn client program, see Глава 2, Экскурсия по Subversion.

Summary

By now you should have a basic understanding of how to create, configure, and maintain Subversion repositories. We've introduced you to the various tools that will assist you with this task. Throughout the chapter, we've noted common administration pitfalls, and suggestions for avoiding them.

All that remains is for you to decide what exciting data to store in your repository, and finally, how to make it available over a network. The next chapter is all about networking.




[30] This may sound really prestigious and lofty, but we're just talking about anyone who is interested in that mysterious realm beyond the working copy where everyone's data hangs out.

[31] Pronounced «fuzz-fuzz», if Jack Repenning has anything to say about it.

[32] That, by the way, is a feature, not a bug.

[33] While svnadmin dump has a consistent leading slash policy—to not include them—other programs which generate dump data might not be so consistent.

[34] E.g.: hard drive + huge electromagnet = disaster.

[35] The Subversion repository dump format resembles an RFC-822 format, the same type of format used for most email.

[36] svnadmin setlog can be called in a way that bypasses the hook interface altogether.

[37] You know—the collective term for all of her «fickle fingers».

[38] The trunk, tags, and branches trio are sometimes referred to as «the TTB directories».

Глава 6. Настройка сервера

Одновременный доступ к хранилищу Subversion клиентами, запущенными на том же компьютере, где расположено и хранилище, возможен при использовании метода file:///. Но, обычно, сервер Subversion устанавливается на отдельный компьютер, к которому имеют доступ клиенты с компьютеров всего офиса — или, возможно, всего мира.

Этот раздел расскажет, как предоставить доступ к хранилищу Subversion удаленным клиентам. Мы опишем доступные на сегодняшний день механизмы серверов Subversion, а так же обсудим вопросы конфигурации и использования каждого из них. После прочтения этого раздела вы сможете решить, какой тип сервера подходит вам, как его установить и настроить на вашем компьютере.

Обзор

Subversion был разработан с использованием абстрактного сетевого уровня. Это означает, что на программном уровне для доступа к хранилищу может быть использован любой тип сервера, а «клиентский API для доступа к хранилищу» дает программистам возможность создавать плагины, которые будут взаимодействовать с соответствующим сетевым протоколом. Теоретически, Subversion может использовать неограниченное количество сетевых реализаций. Практически же, на данный момент есть только два сервера.

Apache — наиболее популярный web-сервер; при использовании модуля mod_dav_svn Apache получает возможность доступа к хранилищу, а так же делает его доступным для клиентов, используя протокол WebDAV/DeltaV, который является расширением HTTP. В другом углу ринга — svnserve — небольшой, самостоятельный сервер, использующий для связи с клиентами собственный протокол. В Таблица 6.1, «Сравнение серверов» дано сравнение этих двух серверов.

Таблица 6.1. Сравнение серверов

ВозможностьApache + mod_dav_svnsvnserve
Настройки установления личностистандартное установление личности средствами HTTP(S), сертификаты X.509, LDAP, NTLM, а также другие механизмы, доступные для использования в ApacheCRAM-MD5 или SSH
Настройки пользовательских учетных записейвнутренний файл 'users'внутренний файл 'users' или использование существующих системных (SSH) учетных записей
Настройки прав доступадоступ на чтение/запись устанавливается сразу на всё хранилище, или настраивается по-каталоговодоступ на чтение/запись устанавливается сразу на всё хранилище, или настраивается по-каталогово
Шифрованиечерез SSL (опционально)через SSH-туннель (опционально)
Ведение журналаполноценный журнал Apache с записями о каждом HTTP запросе, с возможностью «высокоуровневого» учета любых операций клиентанет журнала
Интероперабельностьчастично, используя другие WevDAV-клиентытолько для svn клиентов
Просмотр через вебограниченная встроенная поддержка, или использование программ сторонних разработчиков, таких, как ViewVSтолько при помощи программ сторонних разработчиков, таких, как ViewVS
Скоростьболее низкаяболее высокая
Начальная установканесколько сложнаядостаточно простая


Http-сервер Apache

Как это работает:

Установите и настройте сервер Apache 2.0, затем активируйте модуль сервера subversion. Клиенты будут обращаться к серверу через HTTP или HTTPS, используя протокол WebDAV.

Преимущества данного варианта:
  • Subversion может использовать любой из механизмов аутентификации, интегрированный в Apache.

  • Нет нужды создавать учётные записи на сервере.

  • Ведение логов средствами Apache.

  • Возможность шифровать трафик с помощью SSL.

  • Если компьютер или сеть защищены брандмауэром, порты HTTP(S) обычно открыты.

  • Встроенный просмотр хранилища через веб-обозреватель.

  • Хранилище может быть смонтировано как сетевой диск. (Смотрите «Autoversioning».)

Недостатки данного варианта:
  • Скорость заметно ниже, чем при использовании svnserve.

  • Первичная настройка более комплексная.

Сервер svnserve

Как он работает:

"Лёгкий" процесс, который может работать как самостоятельно, так и "по вызову" inetd. Аутентификация происходит по алгоритму CRAM-MD5. Используется свой протокол.

Преимущества данного варианта:
  • Быстрая и лёгкая установка.

  • Сетевой протокол более продвинутый и работает ощутимо быстрее, чем WebDAV.

  • Нет необходимости создавать на сервере дополнительные учётные записи.

  • Пароль не передаётся по сети.

Недостатки данного варианта:
  • Протокол не поддерживает шифрование.

  • Доступен только один метод аутентификации.

  • Пароль хранится на сервере открытым текстом.

  • Логи не ведутся, даже лог ошибок.

svnserve через SSH

Как он работает:

Клиент подключается к серверу с помощью SSH, используя системную учётную запись. При этом на сервере запускается временный процесс svnserve. Он работает с хранилищем, обменивается данными с клиентом через SSH-туннель, после чего, при закрытии SSH-сессии, завершается. (При этом методе в системе не будет постоянно запущенных процессов svnserve).

Преимущества данного варианта:
  • Используемый stateful-протокол значительно быстрее, чем WebDAV.

  • Удобство использования существующих учётных записей и пользовательской инфраструктуры.

  • Весь сетевой траффик шифруется.

Недостатки данного варианта:
  • Выбор одного метода идентификации

  • Журнал не ведется вообще, даже записи об ошибках.

  • Требует от пользователей принадлежности к одной группе или использования общего ключа ssh.

  • Может привести к проблемам с правами.

Выбор лучшей конфигурации сервера

Итак, какой сервер лучше использовать? Какой из них лучше?

Конечно, на этот вопрос нет точного ответа. Каждая команда имеет свои потребности, и каждый сервер предоставляет свой набор возможностей. Сам проект Subversion не предпочитает какой-то один сервер и не представляет один из них как более «официальный».

Для небольшой команды, которая хочет начать использовать сервер Subversion, авторы этой книги рекомендуют простую установку svnserve; он прост в настройке и требует минимальных усилий на поддержку. Помните, что вы всегда можете перейти на более комплексное решение, когда ваши потребности вырастут.

Вот несколько общих рекомендаций, основанных на многолетнем опыте поддержки пользователей:

  • If you're trying to set up the simplest possible server for your group, then a vanilla svnserve installation is the easiest, fastest route. Note, however, that your repository data will be transmitted in the clear over the network. If your deployment is entirely within your company's LAN or VPN, this isn't an issue. If the repository is exposed to the wide-open internet, then you might want to make sure the repository's contents aren't sensitive (e.g. it contains only open-source code.)

  • If you need to integrate with existing identity systems (LDAP, Active Directory, NTLM, X.509, etc.), then an Apache-based server is your only real option. Similarly, if you absolutely need server-side logs of either server errors or client activities, then an Apache-based server is required.

  • If you've decided to use either Apache or stock svnserve, create a single svn user on your system, and run either Apache or svnserve as that user. Be sure to make the repository directory wholly owned by the svn user as well. These keeps the repository data nicely siloed and protected by operating system filesystem permissions, changeable by only the Subverion server process itself.

  • If you have an existing infrastructure heavily based on SSH accounts, and if your users already have system accounts on your server machine, then it makes sense to deploy an svnserve-over-ssh solution. Otherwise, we don't recommend this option to the general public. It's generally considered safer to have your users access the repository via (imaginary) accounts managed by svnserve or Apache, rather than by full-blown system accounts. If your deep desire for encrypted communication still draws you to this option, we recommend using Apache with SSL instead.

  • Do not be seduced by the simple idea of having all of your users access a repository directly via file:/// URLs. Even if the repository is readily available to everyone via network share, this is a bad idea. It removes any layers of protection between the users and the repository: users can accidentally (or intentionally) corrupt the repository database, it becomes hard to take the repository 'offline' for inspection or upgrade, and it can lead to a mess of file-permissions problems (see «Supporting Multiple Repository Access Methods».) Note that this is also one of the reasons we warn against accessing repositories via svn+ssh:// URLs — from a security standpoint, it's effectively the same as local users accessing via file:///, and can entail all the same problems if the administrator isn't careful.)

Сетевая модель

Этот раздел является обсуждением того, как клиент и сервер Subversion взаимодействуют друг с другом, вне зависимости от используемого вами сетевого решения. После прочтения вы будете понимать, как работает сервер, а также знать различные способы конфигурации клиента.

Запросы и отклики

Основная часть работы клиента Subversion относится к управлению рабочими копиями. Однако, когда возникает необходимость получить информацию из хранилища, он посылает запрос серверу, а сервер посылает соответствующий ответ. Подробности сетевого протокола невидимы пользователю; клиент пытается установить связь с URL, и, в зависимости от схемы URL, использует соответствующий протокол связи с сервером (смотрите URL хранилища). Пользователи могут использовать команду svn --version для получения информации о том, с какими схемами URL и протоколами клиент умеет работать.

Когда сервер получает запрос от клиента, он требует, чтобы клиент идентифицировал себя. Он отсылает запрос об установлении личности клиента, на что клиент реагирует предоставлением идентификационной информации серверу. После окончания процедуры установления личности сервер отсылает клиенту информацию, которую тот запрашивал. Заметьте, что эта система отличается от таких, как в CVS, где клиент вначале отсылает идентификационную информацию, а потом уже посылает запрос. В Subversion сервер сам получает идентификационную информацию, запрашивая её у клиента тогда, когда ему нужно. Такой способ делает определенные операции более изящными. К примеру, в случае, когда конфигурация сервера открывает доступ для чтения всем без ограничений, и клиент выполняет команду svn checkout, сервер не будет запрашивать идентификационную информацию для установления личности.

Когда клиентский запрос пишет в хранилище новые данные (например svn commit), создается новое дерево правок. Если клиентский запрос успешно прошел процедуру установления личности, имя пользователя сохраняется как значение свойства svn:author новой правки (смотрите «Unversioned Properties»). Если клиент не был опознан (другими словами, сервер ни разу не послал запрос об установлении личности), то свойство svn:author остается пустым. [39]

Кэширование клиентской идентификационной информации

Многие серверы сконфигурированы таким образом, что они требуют установить личность при каждом запросе. Это может сильно раздражать пользователей, требуя от них ввода пароля еще и еще раз.

К счастью, клиент Subversion спасает пользователя от этого: он имеет встроенную систему кэширования идентификационной информации на диск. По умолчанию, каждый раз, когда клиент успешно проходит процедуру установления личности на сервере, он сохраняет идентификационную информацию в области конфигурации — в ~/.subversion/auth/ на UNIX-системах и в %APPDATA%/Subversion/auth/ в Windows. (Подробно про область конфигурации смотрите «Параметры времени выполнения»). При успешном определении личности идентификационная информация сохраняется на диск с ключом, состоящим из имени хоста, порта и области установления личности.

Когда клиент получает запрос об установлении личности, он в первую очередь ищет соответствующую идентификационную информацию в дисковом кеше пользователя; если ее нет в кеше или она не проходит процедуру опознания, клиент просит пользователя ввести необходимую информацию.

Люди, помешанные на безопасности, могут подумать: « Сохранять пароли на диск? Это ужасно! Вы никогда не должны так делать.» Пожалуйста, успокойтесь, это не так опасно, как кажется.

  • Каталог auth/ защищен системой прав доступа, которая позволяет чтение данных из каталога только его владельцу, и больше никому в мире. Права доступа на уровне операционной системы защищены паролем.

  • На операционных системах Windows 2000 и старше Subversion использует стандартные средства шифрования Windows при сохранении пароля на диск. Поскольку ключ шифрования управляется Windows и привязывается к учетной записи пользователя, то только владелец учетной записи может расшифровать сохраненный пароль. (Обратите внимание: если администратор сменит пароль для учетной записи пользователя все сохраненные на диск пароли станут недействительными. Клиент Subversion будет вести себя так, словно их не существует, запрашивая пароль, когда он потребуется.)

  • Для тех параноиков, которые готовы жертвовать всеми удобствами, предусмотрена возможность отключения механизма кеширования.

Чтобы отключить кеширование для текущей команды, используйте ключ --no-auth-cache.

$ svn commit -F log_msg.txt --no-auth-cache
Authentication realm: <svn://host.example.com:3690> example realm
Username:  joe
Password for 'joe':

Adding         newfile
Transmitting file data .
Committed revision 2324.

# password was not cached, so a second commit still prompts us

$ svn delete newfile
$ svn commit -F new_msg.txt
Authentication realm: <svn://host.example.com:3690> example realm
Username:  joe
…

Однако, если вы хотите навсегда отключить механизм кеширования идентификационной информации, вам надо отредактировать файл config (находится в каталоге auth/). Просто установите параметр store-auth-creds в no. Всё! Кешироание идентификационной информации на диск отключено!

[auth]
store-auth-creds = no

Иногда требуется удалить идентификационную информацию из кеша. Для этого необходимо вручную удалить соответствующий файл из каталога auth/. Идентификационная информация хранится в отдельных файлах; если вы просмотрите эти файлы, вы увидите список ключей и их значений. Ключ svn:realmstring описывает конкретную realm сервера, с которой связан данный файл.

$ ls ~/.subversion/auth/svn.simple/
5671adf2865e267db74f09ba6f872c28
3893ed123b39500bca8a0b382839198e
5c3c22968347b390f349ff340196ed39

$ cat ~/.subversion/auth/svn.simple/5671adf2865e267db74f09ba6f872c28

K 8
username
V 3
joe
K 8
password
V 4
blah
K 15
svn:realmstring
V 45
<https://svn.domain.com:443> Joe's repository
END

Вы нашли требуемый файл? Теперь просто удалите его.

И последнее о некоторых особенностях идентификации клиента, а именно небольшое разъяснение ключей --username и --password. Многие подкоманды клиента используют эти ключи, однако следует понимать, что использование этих ключей не подразумевает автоматическую отсылку идентификационной информации на сервер. Как объяснялось раньше, сервер получает идентификационную информацию от клиента только тогда, когда считает, что это необходимо; клиент не может передать её серверу по своей инициативе. Когда имя пользователя и пароль передаются в ключах, они будут отосланы серверу только в том случае, если сервер запросит их. [40] Обычно эти ключи используются в следующих случаях:

  • пользователь не хочет использовать текущую учетную запись, или

  • скрипт хочет пройти опознание личности, не используя сохранённые идентификационные данные.

Вот итоговое описание, как клиент Subversion ведет себя когда он получает запрос на авторизацию:

  1. Проверяет указал ли пользователь любую авторизационную информацию как параметры командной строки, через --username и/или --password. Если нет или если эти параметры не прошли авторизацию, тогда

  2. Просматривает область сервера в разделе auth/ на предмет были ли закешированы данные пользователя. Если нет, или если закешированные данные пользователя не прошли авторизацию, тогда

  3. Обращается с запросом к пользователю.

Если клиент успешно идентифицирован через любой из методов, перечисленных выше, он будет пытаться закешировать данные пользователя на диск (за исключением случав, когда пользователь запретил это поведение, как описывалось ранее).

Собственный сервер svnserve

Программа svnserve легкий сервер, способный общаться с клиентами через TCP/IP, используя собственный простой протокол. Клиенты обращаются к серверу, svnserve используя URL, который начинается с svn:// или svn+ssh://. В этом разделе рсказывается о различных способах запуска svnserve, о том как клиенты аутентифицируются на сервере и о настройке соответствующих правил доступа к хранилищу.

Запуск Сервера

Существует несколько различных способов запустить программу svnserve. При запуске без параметров, ничего кроме справочного сообщения вы не увидите. Если вы планируете запускать процесс через inetd, необходимо указывать параметр -i (--inetd):

$ svnserve -i
( success ( 1 2 ( ANONYMOUS ) ( edit-pipeline ) ) )

При запуске с параметром --inetd, svnserve будет пытаться общаться с клиентом Subversion через stdin и stdout используя собственный протокол. Это стандартное поведение для программ, запускаемых через inetd. IANA зарезервировал порт 3690 для протокола Subversion, поэтому на unix-подобных системах вы можете добавить в /etc/services строки подобные этим (возможно, они там уже есть):

svn           3690/tcp   # Subversion
svn           3690/udp   # Subversion

Если система использует классический Unix-подобный демон inetd, в /etc/inetd.conf можно добавить такую строку:

svn stream tcp nowait svnowner /usr/bin/svnserve svnserve -i

Убедитесь, что пользователь «svnowner» имеет необходимые права для доступа к хранилищу. После этого, когда от клиента к серверу на порт 3690 придет запрос на соединение, inetd запустит процесс svnserve для обслуживания этого запроса.

На Windows системах, существуют средства от сторонних производителей, которые запускают svnserve как сервис. Список этих инструментов можно посмотреть на веб-сайте Subversion.

Второй параметр запускает svnserve как автономный процесс—«демон». Для этого используется параметр -d:

$ svnserve -d
$               # svnserve is now running, listening on port 3690

Если svnserve запускается в режиме демона, можно использовать опции --listen-port= и --listen-host=, чтобы назначить нужное значение порта и имени хоста, к которому «привязан» svnserve.

Существует еще один, третий способ запуска svnserve, с параметром -t — это так называемый «туннельный режим». Этот режим предполагает, что программы удаленного доступа такие как RSH или SSH уже успешно аутентифицировали пользователя и запускают частный процесс svnserve от имени этого пользователя. Программа svnserve работает в обычном режиме (работая через stdin и stdout) и предполагает, что трафик автоматически перенаправится по некоторому тунелю к клиенту. Когда svnserve запущен подобным туннельным агентом убедитесь в том что аутентифицированый пользователь имеет полный доступ на чтение и запись к файлам базы данных хранилища. По сути, это соответствует обращению к хранилищу локального пользователя через URL вида file:///.

После запуска svnserve все хранилища на вашей системе будут доступны через сеть. Клиент должен указывать абсолютный путь в URL хранилища. Например, если хранилище расположено в /usr/local/repositories/project1, обращаться к нему клиент сможет по адресу svn://host.example.com/usr/local/repositories/project1. Чтобы увеличить безопасность, можно передать svnserve параметр -r, который разрешит обращаться только к тем хранилищам, которые расположены ниже указанного пути:

$ svnserve -d -r /usr/local/repositories
…

Применение параметра -r эффективно изменяет местоположение рассматриваемое программой как корень файловой системы. Клиенты используют URL, из которого удален этот путь, в результате чего URL получается более коротким (и менее разоблачительным):

$ svn checkout svn://host.example.com/project1
…

Встроенная аутентификация и авторизация

Когда клиент подключается к svnserve, происходит следующее:

  • Клиент указывает требуемое хранилище.

  • Сервер обрабатывает файл conf/svnserve.conf хранилища, и начинает выполнять правила аутентификации и авторизации, указанные в нем.

  • В зависимости от ситуации и правил авторизации,

    • клиенту может быть разрешено делать анонимные обращения, без запроса на идентификацию, ИЛИ

    • клиенту может быть сделан запрос на идентификацию в любой момент, ИЛИ

    • при работе в «туннельном режиме», клиент объявит себя уже идентифицированным.

Во время написания данного материала сервер знал только об вызове авторизации через CRAM-MD5 [41]. В сущности, сервер отправляет некоторые данные клиенту. Клиент, используя хэш алгоритма MD5, создает отпечаток (fingerprint) из совмещенных вместе этих данных и своего пароля, после чего отправляет этот отпечаток серверу как ответ. Сервер производит подобные вычисления со своей версией пользовательского пароля и проверяет идентичность результатов. Таким образом пароль никогда не передается в открытую по сети.

Также возможно, что клиент уже был идентифицирован через внешнего туннельного агента, такого как SSH. В таком случае, сервер просто проверяет запустившего его пользователя и в дальнейшем использует идентифицированное имя пользователя. Более подробно об этом смотри в «SSH идентификация и авторизация».

Как вы уже догадались, файл хранилища svnserve.conf — центральный механизм контроля правил идентификации и авторизации. Этот файл имеет такой же формат, как и другие конфигурационные файлы (см. «Параметры времени выполнения»): имена секций помечены квадратными скобками (([ и ]), комментарии начинаются с #, а каждая секция содержит определенные переменные, которые могут быть использованы для конфигурирования (переменная = значение). Давайте посмотрим на этот файл и изучим как им пользоваться.

Создание файла пользователей и область хранилища

Сейчас, секция [general] вsvnserve.conf имеет все необходимые вам переменные. Начнем с определения файла, содержащего имена пользователей и пароли, а также с области хранилища:

[general]
password-db = userfile
realm = example realm

realm — это определяемое вами имя. Оно сообщает клиентам, к какой «области идентификации» они подсоединяются; клиенту Subversion она выводится в приглашении к аутентификации, и используется как ключ (вместе с именем сервера и портом) для кэширования клиентской идентификационной информации на диск (см. «Кэширование клиентской идентификационной информации»). Переменная password-db указывает на отдельный файл, который содержит список пользователей и пароли в таком же простом формате. Например:

[users]
harry = foopassword
sally = barpassword

Значение password-db может быть абсолютным или относительным путем к файлу пользователей. Для большинства администраторов, его легче держать в conf/ области хранилища, рядом с svnserve.conf. С другой стороны, возможно, вы захотите разделять один и тот же файл пользователей для двух или более хранилищ, в этом случае этот файл стоит поместить в более доступное место. Хранилища разделяющие файл пользователей, должны быть также сконфигурированы с одинаковыми областями, так как список пользователей по существу определяет область аутентификации. Где бы в итоге файл не находился, убедитесь, что у него выставлены соответствующие права на чтение/запись. Если вы знаете от имени какого пользователя(-ей) будет запускаться svnserve, то ограничьте доступ на чтение только тем пользователем, которым это нужно.

Установка контроля доступа

Есть еще две дополнительных переменные в svnserve.conf: они определяют, что будут допущены делать не идентифицированные (анонимные) и идентифицированные пользователи. Переменные anon-access и auth-access могут иметь значения: none, read, или write. Установка значения в none запрещает доступ любого рода; read — доступ к хранилищу только на чтение, а write — позволяет полный доступ к хранилищу на чтение/запись. Например:

[general]
password-db = userfile
realm = example realm

# anonymous users can only read the repository
anon-access = read

# authenticated users can both read and write
auth-access = write

Значения установленные в примере — фактически значения по умолчанию, они будут установлены если вы не захотите определить их. Если вы хотите быть более консервативным, то можете заблокировать полностью анонимный доступ:

[general]
password-db = userfile
realm = example realm

# anonymous users aren't allowed
anon-access = none

# authenticated users can both read and write
auth-access = write

Сервер понимает не только такие «поверхностные» ограничения доступа к хранилищу, но также и более детальные, связанные с конкретными файлами и каталогами в хранилище. Чтобы использовать эту возможность, вам необходимо создать файл, содержащий эти специальные правила и указать к нему путь с помощью переменной authz-db:

[general]
password-db = userfile
realm = example realm

# Specific access rules for specific locations
authz-db = authzfile

Формат файла authzfile детально описан в «Path-Based Authorization». Заметьте, что переменная authz-db и пара anon-access, auth-access допускают совместное использование; если все переменные определены одновременно, то для получения доступа должны быть удовлетворены все правила.

SSH идентификация и авторизация

Встроенная в svnserve идентификация может быть более удобной, так как избегает необходимости создавать реальные системные учетные записи. С другой стороны, некоторые администраторы уже имеют хорошо настроенные SSH оболочки в своих системах. В этой ситуации все пользователи проектов уже имеют системные учетные записи и способность к «SSH into» на серверную машину.

Проще всего использовать SSH в связке с svnserve. Клиенты просто используют для коннекта схему svn+ssh://:

$ whoami
harry

$ svn list svn+ssh://host.example.com/repos/project
harry@host.example.com's password:  *****

foo
bar
baz
…

В этом примере клиент Subversion вовлекает локальный процесс ssh, соединяется с host.example.com, идентифицируется как пользователь harry, затем порождает личный процесс svnserve на удаленной машине запускаемый от имени пользователя harry. Команда svnserve была вовлечена в режим тунелирования (-t) и ее сетевой протокол был «тунелирован» через зашифрованное соединение через тунельного-агента ssh. svnserve знает что он запущен пользователем harry, и если клиент выполняет фиксацию, идентификационное имя пользователя будет использовано как имя автора новой ревизии.

Важная вещь для понимания здесь, это то что клиент Subversion не соединяется с запущенным демоном svnserve. Этот метод доступа не требует демона, ни делает уведомления даже если он присутствует. Он использует в целом способность ssh запускать временный процесс svnserve, которые завершается когда сетевое соединение закроется.

Когда для доступа к хранилищу используется URL вида svn+ssh://, помните что это программа ssh запрашивает идентификацию, а не клиентская программа svn. Это означает что нет автоматического кеширования паролей (см. «Кэширование клиентской идентификационной информации»). Клиенты Subversion часто делают несколько соединений к хранилищу, хотя пользователи обычно не знают об этом из-за возможности кеширования паролей. Однако когда используют URL вида svn+ssh:// URLs, пользователи могут быть раздражены ssh из-за повторяющихся запросов пароля для каждого исходящего соединения. Решение этой проблемы заключается в использовании отдельного инструмента для кеширования паролей SSH, подобных ssh-agent на Unix-подобных системах, или pageant в Windows.

Когда выполняется через тунелирование, идентификация первоначально управляется правами операционной системы на файлы базы данных хранилища; это очень похоже на то как если бы Harry получала доступ к хранилищу напрямую через URL file:///. Если несколько пользователей системы получают доступ к хранилищу напрямую, вы можете захотеть поместить их в общую группу, и вы должны будете быть очень осторожным при разрешении (umasks). (Прочитайте «Supporting Multiple Repository Access Methods».) Но в каждом случае тунелирования файл svnserve.conf может продолжать использоваться для блокирования доступа, простой установкой auth-access = read или auth-access = none. [42]

Вы не должны думать что рассказ о SSH тунелирование будет закончен здесь. Subversion позволяет вам создавать заказное поведение тунеля в файле config (смотри «Параметры времени выполнения»). Например, предположим что вы хотите использовать RSH вместо SSH. В разделе [tunnels] файла [tunnels] просто укажите подобно этому:

[tunnels]
rsh = rsh

И сейчас вы можете использовать новое определение туннеля используя схему URL которая соответствует имени вашей новой переменной: svn+rsh://host/path. Затем используя новую схему URL, клиент Subversion будет выполнять команду rsh host svnserve -t за кулисами. Если вы включите имя пользователя в URL (например, svn+rsh://username@host/path) клиент также будет включать его в эту команду (rsh username@host svnserve -t). Но вы может определить новую схему туннелирования которая будет более умная чем эта:

[tunnels]
joessh = $JOESSH /opt/alternate/ssh -p 29934

Этот пример демонстрирует связанные вещи. С начала он показывает как можно сделать чтобы клиент Subversion запускал очень специфическую программу тунелирования (она расположена в /opt/alternate/ssh) с некоторым параметром. В данном случае, доступ к svn+joessh:// будет вовлекать особую программу SSH с аргументами -p 29934 — полезно если вы хотите соединить программу тунелирования на нестандартный порт.

Затем он показывает как определить пользовательскую переменную окружения, которая может перекрыть имя программы тунелирования. Установка переменной окружения SVN_SSH это удобный путь для перекрытия агента тунелирования SSH по умолчанию. Но если вы нуждаетесь в нескольких различных перекрытиях, для разных серверов, каждый возможно взаимодействует с разными портами или передача различных наборов параметров в SSH, вы можете использовать механизм показанный в этом примере. Сейчас, если вы установите переменную окружения JOESSH, ее значение будет перекрывать содержимое переменной тунелирования —$JOESSH будет выполняться вместо /opt/alternate/ssh -p 29934.

Трюки конфигурирования SSH

Возможно не только управлять как клиент выполняет ssh, но также управлять поведением sshd на машине вашего сервера. В этом разделе, мы покажем как управлять тем, какие именно команды svnserve вызываются sshd, а также о том, как несколько пользователей могут использовать одну системную учетную запись.

Начальная настройка

Для начала, перейдите в домашнюю папку учетной записи которую вы используете для запуска svnserve. Убедитесь что учетная запись имеет установленную пару ключей SSH (публичную/приватную), и что пользователь может зайти через идентификацию с использованием публичного ключа. Парольная идентификация не работает, так как все следующие SSH трюки вращаются вокруг использования файла SSH authorized_keys.

Если он не существует, создайте файл authorized_keys (на Unix, обычно ~/.ssh/authorized_keys). Каждая строка этого файла описывает публичный ключ, который разрешен для соединения. Строки обычно в следующей форме:

  ssh-dsa AAAABtce9euch… user@example.com

Первое поле описывает тип ключа, второе поле uu-кодированный (uuencoded) ключ и третье поле это комментарий. Однако, менее известный факт что всей строке может предшествовать поле command:

  command="program" ssh-dsa AAAABtce9euch… user@example.com

Когда поле command установлено, демон SSH будет выполнять указанную программу, вместо обычной svnserve -t моля что клиент знает об этом. Это открывает двери для многих трюков на стороне сервера. В следующем примерах мы сокращаем строки в файле так :

  command="program" TYPE KEY COMMENT

Controlling the invoked command

Так как мы можем указать выполняемую на сервере команду, проще назвать специфическую программу svnserve и передать дополнительные параметры:

  command="/path/to/svnserve -t -r /virtual/root" TYPE KEY COMMENT

В этом примере, /path/to/svnserve может быть пользовательским скриптом, оберткой вокруг svnserve которая устанавливает umask (смотри «Supporting Multiple Repository Access Methods»). Также показано как привязать svnserve к виртуальному корневому каталогу, который часто делается когда запускается svnserve как процесс-демон. Это может быть сделано либо ограничением доступа к части системы, или просто заставляя пользователя указывать абсолютный путь в svn+ssh:// URL.

Так же возможно иметь нескольких пользовательских разделяемых ресурсов под одной учетной записью. Вместо создания различных учетных записей для каждого пользователя, сгенерируйте пару публичный/частный ключ для каждого человека. Затем поместите каждый публичный ключ в файл authorized_users, по одному ключу в строке, и используйте параметр --tunnel-user:

  command="svnserve -t --tunnel-user=harry" TYPE1 KEY1 harry@example.com
  command="svnserve -t --tunnel-user=sally" TYPE2 KEY2 sally@example.com

Этот пример позволяет обоим, Гарии и Салли подключаться к одной учетной записи через идентификацию через публичный ключ. Каждый из них имеет собственную команду, которая будет выполняться, параметр --tunnel-user говорит svnserve -t какой из названных аргументов идентифицирует пользователя. Без --tunnel-user они будут появляться не смотря на все фиксации которые сделаны из одной разделяемой учетной записи.

В заключение предостережение: предоставление доступа пользователям к серверу через публичные ключи в разделяемой учетной записи может оставлять доступным другие формы доступа через SSH, даже если вы установили значение command в authorized_keys. Например, пользователи могут получить доступ через SSH, или иметь возможность выполнять X11 или общий форвардинг портов через ваш сервер. Для предоставления пользователям как можно меньше привилегий, можно указать несколько ограничивающих опций сразу же после command:

  command="svnserve -t --tunnel-user=harry",no-port-forwarding,\
           no-agent-forwarding,no-X11-forwarding,no-pty \
           TYPE1 KEY1 harry@example.com

httpd, the Apache HTTP server

The Apache HTTP Server is a «heavy duty» network server that Subversion can leverage. Via a custom module, httpd makes Subversion repositories available to clients via the WebDAV/DeltaV protocol, which is an extension to HTTP 1.1 (see http://www.webdav.org/ for more information). This protocol takes the ubiquitous HTTP protocol that is the core of the World Wide Web, and adds writing—specifically, versioned writing—capabilities. The result is a standardized, robust system that is conveniently packaged as part of the Apache 2.0 software, is supported by numerous operating systems and third-party products, and doesn't require network administrators to open up yet another custom port. [43] While an Apache-Subversion server has more features than svnserve, it's also a bit more difficult to set up. With flexibility often comes more complexity.

Much of the following discussion includes references to Apache configuration directives. While some examples are given of the use of these directives, describing them in full is outside the scope of this chapter. The Apache team maintains excellent documentation, publicly available on their website at http://httpd.apache.org. For example, a general reference for the configuration directives is located at http://httpd.apache.org/docs-2.0/mod/directives.html.

Also, as you make changes to your Apache setup, it is likely that somewhere along the way a mistake will be made. If you are not already familiar with Apache's logging subsystem, you should become aware of it. In your httpd.conf file are directives that specify the on-disk locations of the access and error logs generated by Apache (the CustomLog and ErrorLog directives, respectively). Subversion's mod_dav_svn uses Apache's error logging interface as well. You can always browse the contents of those files for information that might reveal the source of a problem that is not clearly noticeable otherwise.

Prerequisites

To network your repository over HTTP, you basically need four components, available in two packages. You'll need Apache httpd 2.0, the mod_dav DAV module that comes with it, Subversion, and the mod_dav_svn filesystem provider module distributed with Subversion. Once you have all of those components, the process of networking your repository is as simple as:

  • getting httpd 2.0 up and running with the mod_dav module,

  • installing the mod_dav_svn plugin to mod_dav, which uses Subversion's libraries to access the repository, and

  • configuring your httpd.conf file to export (or expose) the repository.

You can accomplish the first two items either by compiling httpd and Subversion from source code, or by installing pre-built binary packages of them on your system. For the most up-to-date information on how to compile Subversion for use with the Apache HTTP Server, as well as how to compile and configure Apache itself for this purpose, see the INSTALL file in the top level of the Subversion source code tree.

Basic Apache Configuration

Once you have all the necessary components installed on your system, all that remains is the configuration of Apache via its httpd.conf file. Instruct Apache to load the mod_dav_svn module using the LoadModule directive. This directive must precede any other Subversion-related configuration items. If your Apache was installed using the default layout, your mod_dav_svn module should have been installed in the modules subdirectory of the Apache install location (often /usr/local/apache2). The LoadModule directive has a simple syntax, mapping a named module to the location of a shared library on disk:

LoadModule dav_svn_module     modules/mod_dav_svn.so

Note that if mod_dav was compiled as a shared object (instead of statically linked directly to the httpd binary), you'll need a similar LoadModule statement for it, too. Be sure that it comes before the mod_dav_svn line:

LoadModule dav_module         modules/mod_dav.so
LoadModule dav_svn_module     modules/mod_dav_svn.so

At a later location in your configuration file, you now need to tell Apache where you keep your Subversion repository (or repositories). The Location directive has an XML-like notation, starting with an opening tag, and ending with a closing tag, with various other configuration directives in the middle. The purpose of the Location directive is to instruct Apache to do something special when handling requests that are directed at a given URL or one of its children. In the case of Subversion, you want Apache to simply hand off support for URLs that point at versioned resources to the DAV layer. You can instruct Apache to delegate the handling of all URLs whose path portions (the part of the URL that follows the server's name and the optional port number) begin with /repos/ to a DAV provider whose repository is located at /absolute/path/to/repository using the following httpd.conf syntax:

<Location /repos>
  DAV svn
  SVNPath /absolute/path/to/repository
</Location>

If you plan to support multiple Subversion repositories that will reside in the same parent directory on your local disk, you can use an alternative directive, the SVNParentPath directive, to indicate that common parent directory. For example, if you know you will be creating multiple Subversion repositories in a directory /usr/local/svn that would be accessed via URLs like http://my.server.com/svn/repos1, http://my.server.com/svn/repos2, and so on, you could use the httpd.conf configuration syntax in the following example:

<Location /svn>
  DAV svn

  # any "/svn/foo" URL will map to a repository /usr/local/svn/foo
  SVNParentPath /usr/local/svn
</Location>

Using the previous syntax, Apache will delegate the handling of all URLs whose path portions begin with /svn/ to the Subversion DAV provider, which will then assume that any items in the directory specified by the SVNParentPath directive are actually Subversion repositories. This is a particularly convenient syntax in that, unlike the use of the SVNPath directive, you don't have to restart Apache in order to create and network new repositories.

Be sure that when you define your new Location, it doesn't overlap with other exported Locations. For example, if your main DocumentRoot is exported to /www, do not export a Subversion repository in <Location /www/repos>. If a request comes in for the URI /www/repos/foo.c, Apache won't know whether to look for a file repos/foo.c in the DocumentRoot, or whether to delegate mod_dav_svn to return foo.c from the Subversion repository.

At this stage, you should strongly consider the question of permissions. If you've been running Apache for some time now as your regular web server, you probably already have a collection of content—web pages, scripts and such. These items have already been configured with a set of permissions that allows them to work with Apache, or more appropriately, that allows Apache to work with those files. Apache, when used as a Subversion server, will also need the correct permissions to read and write to your Subversion repository.

You will need to determine a permission system setup that satisfies Subversion's requirements without messing up any previously existing web page or script installations. This might mean changing the permissions on your Subversion repository to match those in use by other things that Apache serves for you, or it could mean using the User and Group directives in httpd.conf to specify that Apache should run as the user and group that owns your Subversion repository. There is no single correct way to set up your permissions, and each administrator will have different reasons for doing things a certain way. Just be aware that permission-related problems are perhaps the most common oversight when configuring a Subversion repository for use with Apache.

Authentication Options

At this point, if you configured httpd.conf to contain something like

<Location /svn>
  DAV svn
  SVNParentPath /usr/local/svn
</Location>

…then your repository is «anonymously» accessible to the world. Until you configure some authentication and authorization policies, the Subversion repositories you make available via the Location directive will be generally accessible to everyone. In other words,

  • anyone can use their Subversion client to checkout a working copy of a repository URL (or any of its subdirectories),

  • anyone can interactively browse the repository's latest revision simply by pointing their web browser to the repository URL, and

  • anyone can commit to the repository.

Basic HTTP Authentication

The easiest way to authenticate a client is via the HTTP Basic authentication mechanism, which simply uses a username and password to verify that a user is who she says she is. Apache provides an htpasswd utility for managing the list of acceptable usernames and passwords, those to whom you wish to grant special access to your Subversion repository. Let's grant commit access to Sally and Harry. First, we need to add them to the password file.

$ ### First time: use -c to create the file
$ ### Use -m to use MD5 encryption of the password, which is more secure
$ htpasswd -cm /etc/svn-auth-file harry
New password: *****
Re-type new password: *****
Adding password for user harry
$ htpasswd -m /etc/svn-auth-file sally
New password: *******
Re-type new password: *******
Adding password for user sally
$

Next, you need to add some more httpd.conf directives inside your Location block to tell Apache what to do with your new password file. The AuthType directive specifies the type of authentication system to use. In this case, we want to specify the Basic authentication system. AuthName is an arbitrary name that you give for the authentication domain. Most browsers will display this name in the pop-up dialog box when the browser is querying the user for his name and password. Finally, use the AuthUserFile directive to specify the location of the password file you created using htpasswd.

After adding these three directives, your <Location> block should look something like this:

<Location /svn>
  DAV svn
  SVNParentPath /usr/local/svn
  AuthType Basic
  AuthName "Subversion repository"
  AuthUserFile /etc/svn-auth-file
</Location>

This <Location> block is not yet complete, and will not do anything useful. It's merely telling Apache that whenever authorization is required, Apache should harvest a username and password from the Subversion client. What's missing here, however, are directives that tell Apache which sorts of client requests require authorization. Wherever authorization is required, Apache will demand authentication as well. The simplest thing to do is protect all requests. Adding Require valid-user tells Apache that all requests require an authenticated user:

<Location /svn>
  DAV svn
  SVNParentPath /usr/local/svn
  AuthType Basic
  AuthName "Subversion repository"
  AuthUserFile /etc/svn-auth-file
  Require valid-user
</Location>

Be sure to read the next section («Authorization Options») for more detail on the Require directive and other ways to set authorization policies.

One word of warning: HTTP Basic Auth passwords pass in very nearly plain-text over the network, and thus are extremely insecure. If you're worried about password snooping, it may be best to use some sort of SSL encryption, so that clients authenticate via https:// instead of http://; at a bare minimum, you can configure Apache to use a self-signed server certificate. [44] Consult Apache's documentation (and OpenSSL documentation) about how to do that.

SSL Certificate Management

Businesses that need to expose their repositories for access outside the company firewall should be conscious of the possibility that unauthorized parties could be «sniffing» their network traffic. SSL makes that kind of unwanted attention less likely to result in sensitive data leaks.

If a Subversion client is compiled to use OpenSSL, then it gains the ability to speak to an Apache server via https:// URLs. The Neon library used by the Subversion client is not only able to verify server certificates, but can also supply client certificates when challenged. When the client and server have exchanged SSL certificates and successfully authenticated one another, all further communication is encrypted via a session key.

It's beyond the scope of this book to describe how to generate client and server certificates, and how to configure Apache to use them. Many other books, including Apache's own documentation, describe this task. But what can be covered here is how to manage server and client certificates from an ordinary Subversion client.

When speaking to Apache via https://, a Subversion client can receive two different types of information:

  • a server certificate

  • a demand for a client certificate

If the client receives a server certificate, it needs to verify that it trusts the certificate: is the server really who it claims to be? The OpenSSL library does this by examining the signer of the server certificate, or certifying authority (CA). If OpenSSL is unable to automatically trust the CA, or if some other problem occurs (such as an expired certificate or hostname mismatch), the Subversion command-line client will ask you whether you want to trust the server certificate anyway:

$ svn list https://host.example.com/repos/project

Error validating server certificate for 'https://host.example.com:443':
 - The certificate is not issued by a trusted authority. Use the
   fingerprint to validate the certificate manually!
Certificate information:
 - Hostname: host.example.com
 - Valid: from Jan 30 19:23:56 2004 GMT until Jan 30 19:23:56 2006 GMT
 - Issuer: CA, example.com, Sometown, California, US
 - Fingerprint: 7d:e1:a9:34:33:39:ba:6a:e9:a5:c4:22:98:7b:76:5c:92:a0:9c:7b

(R)eject, accept (t)emporarily or accept (p)ermanently?

This dialogue should look familiar; it's essentially the same question you've probably seen coming from your web browser (which is just another HTTP client like Subversion!). If you choose the (p)ermanent option, the server certificate will be cached in your private run-time auth/ area in just the same way your username and password are cached (see «Кэширование клиентской идентификационной информации»). If cached, Subversion will automatically remember to trust this certificate in future negotiations.

Your run-time servers file also gives you the ability to make your Subversion client automatically trust specific CAs, either globally or on a per-host basis. Simply set the ssl-authority-files variable to a semicolon-separated list of PEM-encoded CA certificates:

[global]
ssl-authority-files = /path/to/CAcert1.pem;/path/to/CAcert2.pem

Many OpenSSL installations also have a pre-defined set of «default» CAs that are nearly universally trusted. To make the Subversion client automatically trust these standard authorities, set the ssl-trust-default-ca variable to true.

When talking to Apache, a Subversion client might also receive a challenge for a client certificate. Apache is asking the client to identify itself: is the client really who it says it is? If all goes correctly, the Subversion client sends back a private certificate signed by a CA that Apache trusts. A client certificate is usually stored on disk in encrypted format, protected by a local password. When Subversion receives this challenge, it will ask you for both a path to the certificate and the password which protects it:

$ svn list https://host.example.com/repos/project

Authentication realm: https://host.example.com:443
Client certificate filename: /path/to/my/cert.p12
Passphrase for '/path/to/my/cert.p12':  ********
…

Notice that the client certificate is a «p12» file. To use a client certificate with Subversion, it must be in PKCS#12 format, which is a portable standard. Most web browsers are already able to import and export certificates in that format. Another option is to use the OpenSSL command-line tools to convert existing certificates into PKCS#12.

Again, the runtime servers file allows you to automate this challenge on a per-host basis. Either or both pieces of information can be described in runtime variables:

[groups]
examplehost = host.example.com

[examplehost]
ssl-client-cert-file = /path/to/my/cert.p12
ssl-client-cert-password = somepassword

Once you've set the ssl-client-cert-file and ssl-client-cert-password variables, the Subversion client can automatically respond to a client certificate challenge without prompting you. [45]

Authorization Options

At this point, you've configured authentication, but not authorization. Apache is able to challenge clients and confirm identities, but it has not been told how to allow or restrict access to the clients bearing those identities. This section describes two strategies for controlling access to your repositories.

Blanket Access Control

The simplest form of access control is to authorize certain users for either read-only access to a repository, or read/write access to a repository.

You can restrict access on all repository operations by adding the Require valid-user directive to your <Location> block. Using our previous example, this would mean that only clients that claimed to be either harry or sally, and provided the correct password for their respective username, would be allowed to do anything with the Subversion repository:

<Location /svn>
  DAV svn
  SVNParentPath /usr/local/svn

  # how to authenticate a user
  AuthType Basic
  AuthName "Subversion repository"
  AuthUserFile /path/to/users/file

  # only authenticated users may access the repository
  Require valid-user
</Location>

Sometimes you don't need to run such a tight ship. For example, Subversion's own source code repository at http://svn.collab.net/repos/svn allows anyone in the world to perform read-only repository tasks (like checking out working copies and browsing the repository with a web browser), but restricts all write operations to authenticated users. To do this type of selective restriction, you can use the Limit and LimitExcept configuration directives. Like the Location directive, these blocks have starting and ending tags, and you would nest them inside your <Location> block.

The parameters present on the Limit and LimitExcept directives are HTTP request types that are affected by that block. For example, if you wanted to disallow all access to your repository except the currently supported read-only operations, you would use the LimitExcept directive, passing the GET, PROPFIND, OPTIONS, and REPORT request type parameters. Then the previously mentioned Require valid-user directive would be placed inside the <LimitExcept> block instead of just inside the <Location> block.

<Location /svn>
  DAV svn
  SVNParentPath /usr/local/svn

  # how to authenticate a user
  AuthType Basic
  AuthName "Subversion repository"
  AuthUserFile /path/to/users/file

  # For any operations other than these, require an authenticated user.
  <LimitExcept GET PROPFIND OPTIONS REPORT>
    Require valid-user
  </LimitExcept>
</Location>

These are only a few simple examples. For more in-depth information about Apache access control and the Require directive, take a look at the Security section of the Apache documentation's tutorials collection at http://httpd.apache.org/docs-2.0/misc/tutorials.html.

Per-Directory Access Control

It's possible to set up finer-grained permissions using a second Apache httpd module, mod_authz_svn. This module grabs the various opaque URLs passing from client to server, asks mod_dav_svn to decode them, and then possibly vetoes requests based on access policies defined in a configuration file.

If you've built Subversion from source code, mod_authz_svn is automatically built and installed alongside mod_dav_svn. Many binary distributions install it automatically as well. To verify that it's installed correctly, make sure it comes right after mod_dav_svn's LoadModule directive in httpd.conf:

LoadModule dav_module         modules/mod_dav.so
LoadModule dav_svn_module     modules/mod_dav_svn.so
LoadModule authz_svn_module   modules/mod_authz_svn.so

To activate this module, you need to configure your Location block to use the AuthzSVNAccessFile directive, which specifies a file containing the permissions policy for paths within your repositories. (In a moment, we'll discuss the format of that file.)

Apache is flexible, so you have the option to configure your block in one of three general patterns. To begin, choose one of these basic configuration patterns. (The examples below are very simple; look at Apache's own documentation for much more detail on Apache authentication and authorization options.)

The simplest block is to allow open access to everyone. In this scenario, Apache never sends authentication challenges, so all users are treated as «anonymous».

Пример 6.1. A sample configuration for anonymous access.

<Location /repos>
  DAV svn
  SVNParentPath /usr/local/svn

  # our access control policy
  AuthzSVNAccessFile /path/to/access/file
</Location>
          


On the opposite end of the paranoia scale, you can configure your block to demand authentication from everyone. All clients must supply credentials to identify themselves. Your block unconditionally requires authentication via the Require valid-user directive, and defines a means to authenticate.

Пример 6.2. A sample configuration for authenticated access.

<Location /repos>
  DAV svn
  SVNParentPath /usr/local/svn

  # our access control policy
  AuthzSVNAccessFile /path/to/access/file

  # only authenticated users may access the repository
  Require valid-user

  # how to authenticate a user
  AuthType Basic
  AuthName "Subversion repository"
  AuthUserFile /path/to/users/file
</Location>
          


A third very popular pattern is to allow a combination of authenticated and anonymous access. For example, many administrators want to allow anonymous users to read certain repository directories, but want only authenticated users to read (or write) more sensitive areas. In this setup, all users start out accessing the repository anonymously. If your access control policy demands a real username at any point, Apache will demand authentication from the client. To do this, you use both the Satisfy Any and Require valid-user directives together.

Пример 6.3. A sample configuration for mixed authenticated/anonymous access.

<Location /repos>
  DAV svn
  SVNParentPath /usr/local/svn

  # our access control policy
  AuthzSVNAccessFile /path/to/access/file

  # try anonymous access first, resort to real
  # authentication if necessary.
  Satisfy Any
  Require valid-user

  # how to authenticate a user
  AuthType Basic
  AuthName "Subversion repository"
  AuthUserFile /path/to/users/file
</Location>
          


Once you've settled on one of these three basic httpd.conf templates, you need to create your file containing access rules for particular paths within the repository. This is described in «Path-Based Authorization».

Disabling Path-based Checks

The mod_dav_svn module goes through a lot of work to make sure that data you've marked «unreadable» doesn't get accidentally leaked. This means that it needs to closely monitor all of the paths and file-contents returned by commands like svn checkout or svn update commands. If these commands encounter a path that isn't readable according to some authorization policy, then the path is typically omitted altogether. In the case of history or rename tracing—e.g. running a command like svn cat -r OLD foo.c on a file that was renamed long ago—the rename tracking will simply halt if one of the object's former names is determined to be read-restricted.

All of this path-checking can sometimes be quite expensive, especially in the case of svn log. When retrieving a list of revisions, the server looks at every changed path in each revision and checks it for readability. If an unreadable path is discovered, then it's omitted from the list of the revision's changed paths (normally seen with the --verbose option), and the whole log message is suppressed. Needless to say, this can be time-consuming on revisions that affect a large number of files. This is the cost of security: even if you haven't configured a module like mod_authz_svn at all, the mod_dav_svn module is still asking Apache httpd to run authorization checks on every path. The mod_dav_svn module has no idea what authorization modules have been installed, so all it can do is ask Apache to invoke whatever might be present.

On the other hand, there's also an escape-hatch of sorts, one which allows you to trade security features for speed. If you're not enforcing any sort of per-directory authorization (i.e. not using mod_authz_svn or similar module), then you can disable all of this path-checking. In your httpd.conf file, use the SVNPathAuthz directive:

Пример 6.4. Disabling path checks altogether

<Location /repos>
  DAV svn
  SVNParentPath /usr/local/svn

  SVNPathAuthz off
</Location>
          


The SVNPathAuthz directive is «on» by default. When set «off», all path-based authorization checking is disabled; mod_dav_svn stops invoking authorization checks on every path it discovers.

Extra Goodies

We've covered most of the authentication and authorization options for Apache and mod_dav_svn. But there are a few other nice features that Apache provides.

Repository Browsing

One of the most useful benefits of an Apache/WebDAV configuration for your Subversion repository is that the youngest revisions of your versioned files and directories are immediately available for viewing via a regular web browser. Since Subversion uses URLs to identify versioned resources, those URLs used for HTTP-based repository access can be typed directly into a Web browser. Your browser will issue a GET request for that URL, and based on whether that URL represents a versioned directory or file, mod_dav_svn will respond with a directory listing or with file contents.

Since the URLs do not contain any information about which version of the resource you wish to see, mod_dav_svn will always answer with the youngest version. This functionality has the wonderful side-effect that you can pass around Subversion URLs to your peers as references to documents, and those URLs will always point at the latest manifestation of that document. Of course, you can even use the URLs as hyperlinks from other web sites, too.

You generally will get more use out of URLs to versioned files—after all, that's where the interesting content tends to lie. But you might have occasion to browse a Subversion directory listing, where you'll quickly note that the generated HTML used to display that listing is very basic, and certainly not intended to be aesthetically pleasing (or even interesting). To enable customization of these directory displays, Subversion provides an XML index feature. A single SVNIndexXSLT directive in your repository's Location block of httpd.conf will instruct mod_dav_svn to generate XML output when displaying a directory listing, and to reference the XSLT stylesheet of your choice:

<Location /svn>
  DAV svn
  SVNParentPath /usr/local/svn
  SVNIndexXSLT "/svnindex.xsl"
  …
</Location>

Using the SVNIndexXSLT directive and a creative XSLT stylesheet, you can make your directory listings match the color schemes and imagery used in other parts of your website. Or, if you'd prefer, you can use the sample stylesheets provided in the Subversion source distribution's tools/xslt/ directory. Keep in mind that the path provided to the SVNIndexXSLT directory is actually a URL path—browsers need to be able to read your stylesheets in order to make use of them!

Other Features

Several of the features already provided by Apache in its role as a robust Web server can be leveraged for increased functionality or security in Subversion as well. Subversion communicates with Apache using Neon, which is a generic HTTP/WebDAV library with support for such mechanisms as SSL (the Secure Socket Layer, discussed earlier) and Deflate compression (the same algorithm used by the gzip and PKZIP programs to «shrink» files into smaller chunks of data). You need only to compile support for the features you desire into Subversion and Apache, and properly configure the programs to use those features.

Deflate compression places a small burden on the client and server to compress and decompress network transmissions as a way to minimize the size of the actual transmission. In cases where network bandwidth is in short supply, this kind of compression can greatly increase the speed at which communications between server and client can be sent. In extreme cases, this minimized network transmission could be the difference between an operation timing out or completing successfully.

Less interesting, but equally useful, are other features of the Apache and Subversion relationship, such as the ability to specify a custom port (instead of the default HTTP port 80) or a virtual domain name by which the Subversion repository should be accessed, or the ability to access the repository through a proxy. These things are all supported by Neon, so Subversion gets that support for free.

Finally, because mod_dav_svn is speaking a semi-complete dialect of WebDAV/DeltaV, it's possible to access the repository via third-party DAV clients. Most modern operating systems (Win32, OS X, and Linux) have the built-in ability to mount a DAV server as a standard network «share». This is a complicated topic; for details, read Приложение C, WebDAV и автоматическое управление версиями.

Path-Based Authorization

Both Apache and svnserve are capable of granting (or denying) permissions to users. Typically this is done over the entire repository: a user can read the repository (or not), and she can write to the repository (or not). It's also possible, however, to define finer-grained access rules. One set of users may have permssion to write to a certain directory in the repository, but not others; another directory might not even be readable by all but a few special people.

Both servers use a common file format to describe these path-based access rules. In the case of Apache, one needs to load the mod_authz_svn module and then add the AuthzSVNAccessFile directive (within the httpd.conf file) pointing to your own rules-file. (For a full explanation, see «Per-Directory Access Control».) If you're using svnserve, then you need to make the authz-db variable (within svnserve.conf) point to your rules-file.

Once your server knows where to find your rules-file, it's time to define the rules.

The syntax of the file is the same familiar one used by svnserve.conf and the runtime configuration files. Lines that start with a hash (#) are ignored. In its simplest form, each section names a repository and path within it, and the authenticated usernames are the option names within each section. The value of each option describes the user's level of access to the repository path: either r (read-only) or rw (read-write). If the user is not mentioned at all, no access is allowed.

To be more specific: the value of the section-names are either of the form [repos-name:path] or the form [path]. If you're using the SVNParentPath directive, then it's important to specify the repository names in your sections. If you omit them, then a section like [/some/dir] will match the path /some/dir in every repository. If you're using the SVNPath directive, however, then it's fine to only define paths in your sections—after all, there's only one repository.

[calc:/branches/calc/bug-142]
harry = rw
sally = r

In this first example, the user harry has full read and write access on the /branches/calc/bug-142 directory in the calc repository, but the user sally has read-only access. Any other users are blocked from accessing this directory.

Of course, permissions are inherited from parent to child directory. That means that we can specify a subdirectory with a different access policy for Sally:

[calc:/branches/calc/bug-142]
harry = rw
sally = r

# give sally write access only to the 'testing' subdir
[calc:/branches/calc/bug-142/testing]
sally = rw

Now Sally can write to the testing subdirectory of the branch, but can still only read other parts. Harry, meanwhile, continues to have complete read-write access to the whole branch.

It's also possible to explicitly deny permission to someone via inheritance rules, by setting the username variable to nothing:

[calc:/branches/calc/bug-142]
harry = rw
sally = r

[calc:/branches/calc/bug-142/secret]
harry =

In this example, Harry has read-write access to the entire bug-142 tree, but has absolutely no access at all to the secret subdirectory within it.

The thing to remember is that the most specific path always matches first. The mod_authz_svn module tries to match the path itself, and then the parent of the path, then the parent of that, and so on. The net effect is that mentioning a specific path in the accessfile will always override any permissions inherited from parent directories.

By default, nobody has any access to the repository at all. That means that if you're starting with an empty file, you'll probably want to give at least read permission to all users at the root of the repository. You can do this by using the asterisk variable (*), which means «all users»:

[/]
* = r

This is a common setup; notice that there's no repository name mentioned in the section name. This makes all repositories world readable to all users, whether you're using SVNPath or SVNParentPath. Once all users have read-access to the repositories, you can give explicit rw permission to certain users on specific subdirectories within specific repositories.

The asterisk variable (*) is also worth special mention here: it's the only pattern which matches an anonymous user. If you've configured your Location block to allow a mixture of anonymous and authenticated access, all users start out accessing Apache anonymously. mod_authz_svn looks for a * value defined for the path being accessed; if it can't find one, then Apache demands real authentication from the client.

The access file also allows you to define whole groups of users, much like the Unix /etc/group file:

[groups]
calc-developers = harry, sally, joe
paint-developers = frank, sally, jane
everyone = harry, sally, joe, frank, sally, jane

Groups can be granted access control just like users. Distinguish them with an «at» (@) prefix:

[calc:/projects/calc]
@calc-developers = rw

[paint:/projects/paint]
@paint-developers = rw
jane = r

Groups can also be defined to contain other groups:

[groups]
calc-developers = harry, sally, joe
paint-developers = frank, sally, jane
everyone = @calc-developers, @paint-developers

…and that's pretty much all there is to it.

Supporting Multiple Repository Access Methods

You've seen how a repository can be accessed in many different ways. But is it possible—or safe—for your repository to be accessed by multiple methods simultaneously? The answer is yes, provided you use a bit of foresight.

At any given time, these processes may require read and write access to your repository:

  • regular system users using a Subversion client (as themselves) to access the repository directly via file:/// URLs;

  • regular system users connecting to SSH-spawned private svnserve processes (running as themselves) which access the repository;

  • an svnserve process—either a daemon or one launched by inetd—running as a particular fixed user;

  • an Apache httpd process, running as a particular fixed user.

The most common problem administrators run into is repository ownership and permissions. Does every process (or user) in the previous list have the rights to read and write the Berkeley DB files? Assuming you have a Unix-like operating system, a straightforward approach might be to place every potential repository user into a new svn group, and make the repository wholly owned by that group. But even that's not enough, because a process may write to the database files using an unfriendly umask—one that prevents access by other users.

So the next step beyond setting up a common group for repository users is to force every repository-accessing process to use a sane umask. For users accessing the repository directly, you can make the svn program into a wrapper script that first sets umask 002 and then runs the real svn client program. You can write a similar wrapper script for the svnserve program, and add a umask 002 command to Apache's own startup script, apachectl. For example:

$ cat /usr/bin/svn

#!/bin/sh

umask 002
/usr/bin/svn-real "$@"

Another common problem is often encountered on Unix-like systems. As a repository is used, Berkeley DB occasionally creates new log files to journal its actions. Even if the repository is wholly owned by the svn group, these newly created files won't necessarily be owned by that same group, which then creates more permissions problems for your users. A good workaround is to set the group SUID bit on the repository's db directory. This causes all newly-created log files to have the same group owner as the parent directory.

Once you've jumped through these hoops, your repository should be accessible by all the necessary processes. It may seem a bit messy and complicated, but the problems of having multiple users sharing write-access to common files are classic ones that are not often elegantly solved.

Fortunately, most repository administrators will never need to have such a complex configuration. Users who wish to access repositories that live on the same machine are not limited to using file:// access URLs—they can typically contact the Apache HTTP server or svnserve using localhost for the server name in their http:// or svn:// URLs. And to maintain multiple server processes for your Subversion repositories is likely to be more of a headache than necessary. We recommend you choose the server that best meets your needs and stick with it!




[39] Эта проблема описана в FAQ, она является результатом плохой конфигурации сервера.

[40] И опять-таки, частой ошибкой является неправильная конфигурация сервера, при которой сервер никогда не посылает запрос об установлении личности. Когда пользователи используют ключи --username и --password, они могут быть неприятно удивлены, увидев, что ключи не используются, что новые правки зафиксированы анонимными пользователями.

[41] Смотри RFC 2195.

[42] Note that using any sort of svnserve-enforced access control at all is a bit pointless; the user already has direct access to the repository database.

[43] They really hate doing that.

[44] While self-signed server certificates are still vulnerable to a «man in the middle» attack, such an attack is still much more difficult for a casual observer to pull off, compared to sniffing unprotected passwords.

[45] More security-conscious folk might not want to store the client certificate password in the runtime servers file.

[46] Back then, it was called «ViewCVS».

[47] A common theme in this book!

Глава 7. Профессиональная настройка Subversion

### TODO: Chapter opening ###

### TODO: Gut the runtime config stuff like I did the property stuff, making larger topical sections to which the runtime config stuff generally refers. Like already exists for external diff/diff3, add, for example, a section on external editors. ###

Параметры времени выполнения

Subversion имеет множество контролируемых пользователем опциональных параметров поведения. Возможно пользователь хотел бы применять некоторые из этих параметров во всех операциях Subversion. Поэтому для того, что бы не заставлять пользователей помнить ключи командной строки используемые для указания этих параметров и не указывать их при всех выполняемых операциях, Subversion использует конфигурационные файлы, выделенные в область конфигурации Subversion.

Область конфигурации Subversion имеет двухуровневую иерархию имен параметров и их значений. Как правило, она сводится к отдельной директории, содержащей конфигурационные файлы (первый уровень) являющиеся простыми текстовыми файлами в стандартном INI формате (с «разделами», обеспечивающими второй уровень). Эти файлы содержат директивы используемые клиентом для определения поведения клиента предпочитаемого пользователем, и могут быть легко отредактированы используя ваш любимый редактор (например, Emacs или vi).

Структура области конфигурации

Во время первого запуска клиент для командной строки svn создает отдельную для каждого пользователя область конфигурации. На Unix-подобных системах эта директория называется .subversion и находиться в домашней директории пользователя. На Win32 системах Subversion создает папку с именем Subversion в области Application Data директории с профилем пользователя (которая, кстати говоря, обычно является скрытой директорией). Однако на этой платформе точное местоположение отличается от системы к системе и указывается в реестре Windows. [48] При обращении к пользовательской области конфигурации мы будем использовать ее Unix-название.

В дополнение к пользовательской области конфигурации, Subversion использует общесистемную область конфигурации. Это дает возможность системным администраторам устанавливать параметры по умолчанию для всех пользователей отдельно взятой машины. Помните, что системная область конфигурации не устанавливает безоговорочные правила — параметры, заданные пользовательской конфигурацией переопределяют системные параметры, а аргументы командной строки, передаваемые программе svn, имеют последнее слово. На Unix-подобных платформах ожидаемым местоположением системной области конфигурации является директория /etc/subversion; на Windows машинах ищется директория Subversion внутри общесистемной области Application Data (также определяемой реестром). В отличие от пользовательской, системную область конфигурации svn не создает.

На сегодняшний момент пользовательская область конфигурации содержит три файла — два файла конфигурации (config и servers) и README.txt, который содержит описание INI формата. После их создания, эти файлы содержат значения по умолчанию для всех, поддерживаемых Subversion параметров, обычно закомментированных и объединенных с текстовым описанием значений ключей, влияющих на поведение Subversion. Для того, что бы изменить отдельный параметр все, что нужно, просто загрузить соответствующий файл в текстовый редактор и изменить значение нужного параметра. Если в какой-то момент вы захотите восстановить параметры по умолчанию, необходимо просто удалить (или переименовать) директорию с конфигурацией, после чего выполнить какую-то безобидную команду svn, например, svn --version. В результате будет создана новая директория с конфигурацией и содержимым по умолчанию.

Кроме того, пользовательская область конфигурации содержит кеш идентификационной информации. Директория auth объединяет набор поддиректорий, содержащих кешированну информацию, используемую в различных, поддерживаемых Subversion методах авторизации. Эта директория создается так, что бы только сам пользователь имел право просматривать ее содержимое.

Конфигурация и реестр Windows

В дополнение к обычным INI-настройкам, Subversion-клиент, работающий на платформе Windows, может использовать для хранения настроек Windows-реестр. Имена параметров и их значения точно такие же, как и в INI-файлах. Иерархия «файлов» сохраняется, только немного меняется способ адресации — файлы и разделы просто заменяются уровнями в дереве ключей реестра.

За общесистемными настройками Subversion обращается к ключу HKEY_LOCAL_MACHINE\Software\Tigris.org\Subversion Например, параметр global-ignores, находящийся в разделе miscellany файла config будет находиться в HKEY_LOCAL_MACHINE\Software\Tigris.org\Subversion\Config\Miscellany\global-ignores. Пользовательские настройки хранятся в ключе HKEY_CURRENT_USER\Software\Tigris.org\Subversion.

Параметры конфигурации, указанные в реестре обрабатываются до эквивалентных параметров в файлах конфигурации, поэтому они заменяются значениями, найденными, в файлах конфигурации. Другими словами, на Windows-системе приоритеты расположены в следующем порядке:

  1. Параметры командной строки

  2. Пользовательские INI-файлы

  3. Параметры в реестре

  4. Системные INI-файлы

  5. Общесистемные параметры в реестре

Кроме того, реестр Windows не поддерживает механизма «комментирования». Тем не менее, Subversion игнорирует параметры, у которых имена начинаются с символа «решетка» (#). Это позволяет закомментировать параметр, не удаляя ключ из реестра, что значительно упрощает процесс восстановления этого параметра.

Клиент для командной строки svn никогда ничего не записывает и не создает первоначальные «умолчательные» параметры в реестре Windows. Нужные вам ключи вы можете создать используя программу REGEDIT. Либо, можно создать .reg-файл и двойным щелчком на этом файле в Explorer добавить информацию в реестр.

Пример 7.1. Пример указания параметров в (.reg) файле реестра.

REGEDIT4

[HKEY_LOCAL_MACHINE\Software\Tigris.org\Subversion\Servers\groups]

[HKEY_LOCAL_MACHINE\Software\Tigris.org\Subversion\Servers\global]
"#http-proxy-host"=""
"#http-proxy-port"=""
"#http-proxy-username"=""
"#http-proxy-password"=""
"#http-proxy-exceptions"=""
"#http-timeout"="0"
"#http-compression"="yes"
"#neon-debug-mask"=""
"#ssl-authority-files"=""
"#ssl-trust-default-ca"=""
"#ssl-client-cert-file"=""
"#ssl-client-cert-password"=""

[HKEY_CURRENT_USER\Software\Tigris.org\Subversion\Config\auth]
"#store-auth-creds"="no"

[HKEY_CURRENT_USER\Software\Tigris.org\Subversion\Config\helpers]
"#editor-cmd"="notepad"
"#diff-cmd"=""
"#diff3-cmd"=""
"#diff3-has-program-arg"=""

[HKEY_CURRENT_USER\Software\Tigris.org\Subversion\Config\miscellany]
"#global-ignores"="*.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store"
"#log-encoding"=""
"#use-commit-times"=""
"#template-root"=""
"#enable-auto-props"=""

[HKEY_CURRENT_USER\Software\Tigris.org\Subversion\Config\tunnels]

[HKEY_CURRENT_USER\Software\Tigris.org\Subversion\Config\auto-props]


В предыдущем примере показано содержимое .reg-файла, содержащего часто используемые параметры и их значения по умолчанию. Обратите внимание, что приведены как общесистемные (сетевые настройки, относящиеся к прокси-серверу) и пользовательские параметры (программы-редакторы и сохранение паролей, среди прочего). Так же обратите внимание, что все параметры закомментированы. Необходимо будет просто удалить символ «решетка» (#) и установить нужное значение.

Параметры конфигурации

В этом разделе рассматриваются поддерживаемые Subversion параметры времени выполнения.

Servers

В файле servers находятся настройки, относящиеся к работе Subversion через сеть. Он содержит два специальных раздела — groups и global. Раздел groups представляет собой просто перекрестную таблицу. Ключи этого раздела являются именами последующих разделов файла; значения ключей представляют собой обобщения — текстовые блоки, которые могут содержать подстановочные символы — сравниваемые с именами машин, к которым Subversion направляет запросы.

[groups]
beanie-babies = *.red-bean.com
collabnet = svn.collab.net

[beanie-babies]
…

[collabnet]
…

При работе через сеть, Subversion ищет совпадения между именем сервера, с которым устанавливается связь и именем группы в разделе groups. Если найдено совпадение, Subversion обращается к файлу servers, к разделу с именем, совпадающим с именем группы. Из этого раздела берутся необходимые сетевые настройки.

Раздел global содержит настройки, используемые для всех серверов, не подпадающих ни под одно обобщение раздела groups. Здесь указываются те-же, что и для остальных серверных разделов файла параметры (конечно, за исключением специального раздела groups), используемые параметры приведены ниже:

http-proxy-host

Указывает имя компьютера-посредника, через который Subversion должна отправлять HTTP-запросы. По умолчанию, этот параметр имеет пустое значение, которое говорит Subversion о том, что она должна направлять HTTP-запросы не через компьютер-посредник, а связываться с целевой машиной напрямую.

http-proxy-port

Указывает номер используемого порта на промежуточном компьютере. По умолчанию имеет пустое значение.

http-proxy-username

Указывает имя пользователя, передаваемого компьютеру-посреднику. По умолчанию имеет пустое значение.

http-proxy-password

Указывает пароль, передаваемый компьютеру-посреднику. По умолчанию имеет пустое значение.

http-timeout

Указывает, в секундах, промежуток времени ожидания ответа сервера. Если при низкоскоростном сетевом соединении у вас возникает проблема превышения времени ожидания, следует увеличить это значение. Значение по умолчанию 0 означает для низлежащей HTTP библиотеки, Neon, использовать свое собственное значение времени ожидания.

http-compression

Указывает, должна или нет Subversion использовать сжатие сетевых запросов, выполняющихся к DAV-серверам. Значением по умолчанию является yes (однако выполняться сжатие будет только если такая возможность поддерживается сетевым слоем). Установите этот параметр в no, для отключения сжатия, например при отладке сетевых транзакций.

neon-debug-mask

Целочисленная маска, которая используется низлежащей HTTP-библиотекой, Neon, для определения типа выводимой отладочной информации. По умолчанию установлено значение 0, скрывающие весь отладочный вывод. Подробнее о том как Subversion использует Neon читайте в разделе Глава 8, Информация для разработчиков.

ssl-authority-files

Разделенный точкой с запятой перечень путей к файлам, содержащим сертификаты авторизации (или CAs), используемые Subversion-клиентом при обращении к хранилищу через HTTPS.

ssl-trust-default-ca

Установите значение этой переменной в yes, если хотите чтобы Subversion автоматически доверяла набору поставляемых вместе с OpenSSL сертификатов (CAs).

ssl-client-cert-file

Если хост (или хосты) требуют SSL сертификат клиента, у вас будет запрошен путь к вашему сертификату. Установите значение этой переменной и Subversion сможет автоматически находить ваш сертификат, без запроса. Нет стандартного места для хранения сертификата на диске; Subversion будет использовать тот, который располагается по указанному вами пути.

ssl-client-cert-password

Если ваш клиентский SSL сертификат защищен паролем, при обращении к нему Subversion запросит у вас пароль. Если это вам надоедает (и вас не пугает хранить пароль в файле servers), можно присвоить значению этой переменной пароль сертификата. После этого пароль больше запрашиваться не будет.

Config

Остальные доступные параметры времени выполнения Subversion, не относящиеся к сетевой работе, находятся в файле config. В данный момент существует всего несколько параметров, но они тоже сгруппированы в разделы, в расчете на их увеличение в будущем.

Раздел auth содержит параметры, относящиеся к аутентификации и авторизации в хранилище. Он содержит:

store-passwords

Устанавливает, используется или не используется кеширование паролей, введенных пользователем в ответ на запрос при аутентификации на сервере. Значением по умолчанию является да. Для запрета кеширования паролей на диск установите этот параметр в нет. Для отдельного запуска svn этот параметр можно переопределить, используя параметр командной строки --no-auth-cache (для тех команд, которые его поддерживают). За более подробной информацией обратитесь к разделу «Кэширование клиентской идентификационной информации».

store-auth-creds

Этот параметр такой же как и store-passwords, за исключением того, что он разрешает или запрещает дисковое кеширование всей информации для аутентификации: имен пользователей, паролей, серверных сертификатов и всей другой кешируемой информации.

Раздел helpers определяет, какие внешние приложения, при выполнении своих задач, будет использовать Subversion. Доступные параметры:

editor-cmd

Определяет программу, которую будет использовать Subversion для ввода лог сообщений, в тех случаях, когда svn commit используется без параметров --message (-m) или --file (-F). Эта же программа используется с командой svn propedit — вызывается временный файл, содержащий текущее значение редактируемого пользователем свойства и редактирование выполняется прямо в программе-редакторе (см. «Свойства»). По умолчанию значение этого свойства не установлено. Порядок определения используемого редактора следующий:

  1. Command-line option --editor-cmd

  2. Environment variable SVN_EDITOR

  3. Configuration option editor-cmd

  4. Environment variable VISUAL

  5. Environment variable EDITOR

  6. Possibly, a default value built in to Subversion (not present in the official builds)

The value of any of these options or variables is (unlike diff-cmd) the beginning of a command line to be executed by the shell. Subversion appends a space and the pathname of the temporary file to be edited. The editor should modify the temporary file and return a zero exit code to indicate success.

diff-cmd

Здесь указывается абсолютный путь к программе определения отличий, используемой, Subversion для «diff»-вывода (такого как при использовании команды svn diff). По умолчанию для определения отличий Subversion использует внутреннюю библиотеку — установка этого параметра заставит ее использовать внешнюю программу. Подробнее об использовании таких программ читайте в разделе «Using External Differencing Tools».

diff3-cmd

Здесь указывается абсолютный путь к программе трехстороннего сравнения. Subversion использует эту программу при объединении изменений, сделанных пользователем, с теми, которые были получены из хранилища. По умолчанию для определения отличий Subversion использует внутреннюю библиотеку — установка этого параметра заставит ее использовать внешнюю программу. Подробнее об использовании таких программ читайте в разделе «Using External Differencing Tools».

diff3-has-program-arg

Этот флаг должен быть установлен в true если программа, указанная в параметре diff3-cmd использует параметр командной строки --diff-program.

Раздел tunnels позволяет определить новые схемы туннелирования при использовании svnserve и клиентских подключений через svn://. За более подробной информацией обращайтесь в раздел «SSH идентификация и авторизация».

Все что не попало в другие разделы собирается в разделе miscellany[49]. В этом разделе можно найти:

global-ignores

Про выполнении команды svn status, Subversion перечисляет не версионированные файлы и директории вместе с версионированными, отмечая их символом ? (см. «svn status»). Просмотр не интересных, не версионированных элементов при просмотре может раздражать — например объектные файлы, полученные в результате компиляции программы. Параметр global-ignores является перечислением разделннных пробелом обобщений, представляющих имена файлов и директорий которые Subversion не должна показывать, если они не версионированны. Значением, присвоенным по умолчанию, является *.o *.lo *.la #*# .*.rej *.rej .*~ *~ .#* .DS_Store.

Также как и svn status, команды svn add и svn import при просмотре директорий тоже игнорируют файлы, подходящие к этому списку. Можно переопределить этот параметр, используя флаг командной строки --no-ignore. Более подробнее о контроле игнорирования см. «Пропуск неверсионированных элементов».

enable-auto-props

Определяет автоматическую установку свойств для вновь добавляемых или импортированных файлов. Значением по умолчанию является no, поэтому для разрешения авто-свойств установите yes. Раздел auto-props этого файла определяет, какие свойства и для каких файлов должны устанавливаться.

log-encoding

Эта переменная задает набор символов кодировки для лог-сообщений фиксаций. Это перманентная форма параметра --encoding (см. «Параметры командной строкиsvn»). Хранилище Subversion хранит лог-сообщения в UTF8, и предполагает, что ваше лог-сообщение написано используя родную локаль операционной ситемы. Кодировку необходимо указывать, если используется любая другая кодировка.

use-commit-times

Как правило, файлы рабочей копии имеют отметки времени, отражающие время последнего обращения к ним какого-либо процесса, был ли это ваш редактор, или подкоманды svn. Это должно быть близко людям, разрабатывающим программное обеспечение, потому, что как правило, системы сборки определяют по метке времени какие файлы требуют перекомпиляции.

С другой стороны, иногда бывает выгодно, что бы рабочие файлы имели метки времени отражающие время их последнего изменения в хранилище. Команда svn export всегда устанавливает «метку времени последней фиксации» для создаваемого ею дерева файлов. При установке значения этой переменной в yes команды svn checkout, svn update, svn switch и svn revert для используемых ими файлов, так же будут устанавливать метку времени последней фиксации.

Раздел auto-props определяет возможность Subversion-клиента автоматически устанавливать свойства файлов, когда они добавлялись или импортировались. Он содержит любое количество пар ключ-значение, в формате PATTERN = PROPNAME=PROPVALUE, где PATTERN является файловым шаблоном, соответствующих набору имен файлов, а остальная часть строки является свойством и его значением. Множественные совпадения для одного файла приведут к множественной установке свойств для этого файла; однако не гарантируется, что порядок установки авто-свойств будет таким же в каком они указаны в файле конфигурации, поэтому нельзя будет одним правилом «перекрыть» другое. Несколько примеров использования авто-свойств можно найти в файле config. Наконец, если хотите использовать авто-свойства, не забудьте в разделе miscellany установить enable-auto-props в yes.

Localization

Localization is the act of making programs behave in a region-specific way. When a program formats numbers or dates in a way specific to your part of the world, or prints messages (or accepts input) in your native language, the program is said to be localized. This section describes steps Subversion has made towards localization.

Understanding locales

Most modern operating systems have a notion of the «current locale»—that is, the region or country whose localization conventions are honored. These conventions—typically chosen by some runtime configuration mechanism on the computer—affect the way in which programs present data to the user, as well as the way in which they accept user input.

On Unix-like systems, you can check the values of the locale-related runtime configuration options by running the locale command:

$ locale
LANG=
LC_COLLATE="C"
LC_CTYPE="C"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL="C"

The output is a list of locale-related environment variables and their current values. In this example, the variables are all set to the default C locale, but users can set these variables to specific country/language code combinations. For example, if one were to set the LC_TIME variable to fr_CA, then programs would know to present time and date information formatted according a French-speaking Canadian's expectations. And if one were to set the LC_MESSAGES variable to zh_TW, then programs would know to present human-readable messages in Traditional Chinese. Setting the LC_ALL variable has the effect of changing every locale variable to the same value. The value of LANG is used as a default value for any locale variable that is unset. To see the list of available locales on a Unix system, run the command locale -a.

On Windows, locale configuration is done via the «Regional and Language Options» control panel item. There you can view and select the values of individual settings from the available locales, and even customize (at a sickening level of detail) several of the display formatting conventions.

Subversion's use of locales

The Subversion client, svn, honors the current locale configuration in two ways. First, it notices the value of the LC_MESSAGES variable and attempts to print all messages in the specified language. For example:

$ export LC_MESSAGES=de_DE
$ svn help cat
cat: Gibt den Inhalt der angegebenen Dateien oder URLs aus.
Aufruf: cat ZIEL[@REV]...
…

This behavior works identically on both Unix and Windows systems. Note, though, that while your operating system might have support for a certain locale, the Subversion client still may not be able to speak the particular language. In order to produce localized messages, human volunteers must provide translations for each language. The translations are written using the GNU gettext package, which results in translation modules that end with the .mo filename extension. For example, the German translation file is named de.mo. These translation files are installed somewhere on your system. On Unix, they typically live in /usr/share/locale/, while on Windows they're often found in the \share\locale\ folder in Subversion's installation area. Once installed, a module is named after the program it provides translations for. For example, the de.mo file may ultimately end up installed as /usr/share/locale/de/LC_MESSAGES/subversion.mo. By browsing the installed .mo files, you can see which languages the Subversion client is able to speak.

The second way in which the locale is honored involves how svn interprets your input. The repository stores all paths, filenames, and log messages in Unicode, encoded as UTF-8. In that sense, the repository is internationalized—that is, the repository is ready to accept input in any human language. This means, however, that the Subversion client is responsible for sending only UTF-8 filenames and log messages into the repository. In order to do this, it must convert the data from the native locale into UTF-8.

For example, suppose you create a file named caffè.txt, and then when committing the file, you write the log message as «Adesso il caffè è più forte». Both the filename and log message contain non-ASCII characters, but because your locale is set to it_IT, the Subversion client knows to interpret them as Italian. It uses an Italian character set to convert the data to UTF-8 before sending them off to the repository.

Note that while the repository demands UTF-8 filenames and log messages, it does not pay attention to file contents. Subversion treats file contents as opaque strings of bytes, and neither client nor server makes an attempt to understand the character set or encoding of the contents.

Using External Differencing Tools

The presence of --diff-cmd and --diff3-cmd options, and similarly named runtime configuration parameters (see «Config»), can lead to a false notion of how easy it is to use external differencing (or «diff») and merge tools with Subversion. While Subversion can use most of popular such tools available, the effort invested in setting this up often turns out to be non-trivial.

The interface between Subversion and external diff and merge tools harkens back to a time when Subversion's only contextual differencing capabilities were built around invocations of the GNU diffutils toolchain, specifically the diff and diff3 utilities. To get the kind of behavior Subversion needed, it called these utilities with more than a handful of options and parameters, most of which were quite specific to the utilities. Some time later, Subversion grew its own internal differencing library, and as a failover mechanism, [50] the --diff-cmd and --diff3-cmd options were added to the Subversion command-line client so users could more easily indicate that they preferred to use the GNU diff and diff3 utilities instead of the newfangled internal diff library. If those options were used, Subversion would simply ignore the internal diff library, and fall back to running those external programs, lengthy argument lists and all. And that's where things remain today.

It didn't take long for folks to realize that having such easy configuration mechanisms for specifying that Subversion should use the external GNU diff and diff3 utilities located at a particular place on the system could be applied toward the use of other diff and merge tools, too. After all, Subversion didn't actually verify that the things it was being told to run were members of the GNU diffutils toolchain. But the only configurable aspect of using those external tools is their location on the system—not the option set, parameter order, etc. Subversion continues throwing all those GNU utility options at your external diff tool regardless of whether or not that program can understand those options. And that's where things get unintuitive for most users.

The key to using external diff and merge tools (other than GNU diff and diff3, of course) with Subversion is to use wrapper scripts which convert the input from Subversion into something that your differencing tool can understand, and then to convert the output of your tool back into a format which Subversion expects—the format that the GNU tools would have used. The following sections cover the specifics of those expectations.

[Замечание]Замечание

The decision on when to fire off a contextual diff or merge as part of a larger Subversion operation is made entirely by Subversion, and is affected by, among other things, whether or not the files being operated on are human-readable as determined by their svn:mime-type property. This means, for example, that even if you had the niftiest Microsoft Word-aware differencing or merging tool in the Universe, it would never be invoked by Subversion so long as your versioned Word documents had a configured MIME type that denoted that they were not human-readable (such as application/msword). For more about MIME type settings, see «Тип содержимого файла»

External diff

Subversion calls external diff programs with parameters suitable for the GNU diff utility, and expects only that the external program return with a successful error code. For most alternative diff program, only the sixth and seventh arguments, the paths of the files which represent the left and right sides of the diff, respectively, are of interest. Note that Subversion runs the diff program once per modified file covered by the Subversion operation, so if your program runs in an asynchronous fashion (or «backgrounded»), you might have several instances of it all running simultaneously. Finally, Subversion expects that your program return an errorcode of 1 if your program detected differences, or 0 if it did not—any other errorcode is considered a fatal error. [51]

Пример 7.2, «diffwrap.sh» and Пример 7.3, «diffwrap.bat» are templates for external diff tool wrappers in the Bourne shell and Windows batch scripting languages, respectively.

Пример 7.2. diffwrap.sh

#!/bin/sh

# Configure your favorite diff program here.
DIFF="/usr/local/bin/my-diff-tool"

# Subversion provides the paths we need as the sixth and seventh
# parameters.
LEFT=${6}
RIGHT=${7}

# Call the diff command (change the following line to make sense for
# your merge program).
$DIFF --left $LEFT --right $RIGHT

# Return an errorcode of 0 if no differences were detected, 1 if some were.
# Any other errorcode will be treated as fatal.


Пример 7.3. diffwrap.bat

@ECHO OFF

REM Configure your favorite diff program here.
SET DIFF="C:\Program Files\Funky Stuff\My Diff Tool.exe"

REM Subversion provides the paths we need as the sixth and seventh
REM parameters.
SET LEFT=%6
SET RIGHT=%7

REM Call the diff command (change the following line to make sense for
REM your merge program).
%DIFF% --left %LEFT% --right %RIGHT%

REM Return an errorcode of 0 if no differences were detected, 1 if some were.
REM Any other errorcode will be treated as fatal.


External diff3

Subversion calls external merge programs with parameters suitable for the GNU diff3 utility, expecting that the external program return with a successful error code and that the full file contents which result from the completed merge operation are printed on the standard output stream (so that Subversion can redirect them into the appropriate version controlled file). For most alternative merge programs, only the ninth, tenth, and eleventh arguments, the paths of the files which represent the «mine», «older», and «yours» inputs, respectively, are of interest. Note that because Subversion depends on the output of your merge program, you wrapper script must not exit before that output has been delivered to Subversion. When it finally does exit, it should return an errorcode of 0 if the merge was successful, or 1 if unresolved conflicts remain in the output—any other errorcode is considered a fatal error.

Пример 7.4, «diff3wrap.sh» and Пример 7.5, «diff3wrap.bat» are templates for external merge tool wrappers in the Bourne shell and Windows batch scripting languages, respectively.

Пример 7.4. diff3wrap.sh

#!/bin/sh

# Configure your favorite diff3/merge program here.
DIFF3="/usr/local/bin/my-merge-tool"

# Subversion provides the paths we need as the ninth, tenth, and eleventh
# parameters.
MINE=${9}
OLDER=${10}
YOURS=${11}

# Call the merge command (change the following line to make sense for
# your merge program).
$DIFF3 --older $OLDER --mine $MINE --yours $YOURS

# After performing the merge, this script needs to print the contents
# of the merged file to stdout.  Do that in whatever way you see fit.
# Return an errorcode of 0 on successful merge, 1 if unresolved conflicts
# remain in the result.  Any other errorcode will be treated as fatal.


Пример 7.5. diff3wrap.bat

@ECHO OFF

REM Configure your favorite diff3/merge program here.
SET DIFF3="C:\Program Files\Funky Stuff\My Merge Tool.exe"

REM Subversion provides the paths we need as the ninth, tenth, and eleventh
REM parameters.  But we only have access to nine parameters at a time, so we
REM shift our nine-parameter window twice to let us get to what we need.
SHIFT
SHIFT
SET MINE=%7
SET OLDER=%8
SET YOURS=%9

REM Call the merge command (change the following line to make sense for
REM your merge program).
%DIFF3% --older %OLDER% --mine %MINE% --yours %YOURS%

REM After performing the merge, this script needs to print the contents
REM of the merged file to stdout.  Do that in whatever way you see fit.
REM Return an errorcode of 0 on successful merge, 1 if unresolved conflicts
REM remain in the result.  Any other errorcode will be treated as fatal.





[48] Переменная среды окружения APPDATA указывает на папку Application Data поэтому к этой директории можно всегда обращаться как к %APPDATA%\Subversion.

[49] Anyone for potluck dinner?

[50] Subversion developers are good, but even the best make mistakes.

[51] The GNU diff manual page puts it this way: «An exit status of 0 means no differences were found, 1 means some differences were found, and 2 means trouble.»

Глава 8. Информация для разработчиков

Subversion has a modular design, implemented as a collection of C libraries. Each library has a well-defined purpose and interface, and those interfaces are available not only for Subversion itself to use, but for any software that wishes to embed or otherwise programmatically control Subversion. Most of those interfaces are available not only in C, but also in higher-level languages such as Python or Java.

This chapter is for those who wish to interact with Subversion through its public Application Programming Interface (API) or various language bindings. If you wish to write robust wrapper scripts around Subversion functionality to simplify your own life, are trying to develop more complex integrations between Subversion and other pieces of software, or just have an interest in Subversion's various library modules and what they offer, this chapter is for you. If, however, you don't foresee yourself participating with Subversion at such a level, feel free to skip this chapter with the confidence that your experience as a Subversion user will not be affected.

Layered Library Design

Each of Subversion's core libraries can be said to exist in one of three main layers—the Repository Layer, the Repository Access (RA) Layer, or the Client Layer. We will examine these layers shortly, but first, see our brief inventory of Subversion's libraries in Таблица 8.1, «A Brief Inventory of the Subversion Libraries». For the sake of consistency, we will refer to the libraries by their extensionless Unix library names (e.g.: libsvn_fs, libsvn_wc, mod_dav_svn).

Таблица 8.1. A Brief Inventory of the Subversion Libraries

LibraryDescription
libsvn_clientPrimary interface for client programs
libsvn_deltaTree and byte-stream differencing routines
libsvn_diffContextual differencing and merging routines
libsvn_fsFilesystem commons and module loader
libsvn_fs_baseThe Berkeley DB filesystem back-end
libsvn_fs_fsThe native filesystem (FSFS) back-end
libsvn_raRepository Access commons and module loader
libsvn_ra_davThe WebDAV Repository Access module
libsvn_ra_localThe local Repository Access module
libsvn_ra_svnThe custom protocol Repository Access module
libsvn_reposRepository interface
libsvn_subrMiscellaneous helpful subroutines
libsvn_wcThe working copy management library
mod_authz_svnApache authorization module for Subversion repositories access via WebDAV
mod_dav_svnApache module for mapping WebDAV operations to Subversion ones


The fact that the word «miscellaneous» only appears once in Таблица 8.1, «A Brief Inventory of the Subversion Libraries» is a good sign. The Subversion development team is serious about making sure that functionality lives in the right layer and libraries. Perhaps the greatest advantage of the modular design is its lack of complexity from a developer's point of view. As a developer, you can quickly formulate that kind of «big picture» that allows you to pinpoint the location of certain pieces of functionality with relative ease.

Another benefit of modularity is the ability to replace a given module with a whole new library that implements the same API without affecting the rest of the code base. In some sense, this happens within Subversion already. The libsvn_ra_dav, libsvn_ra_local, and libsvn_ra_svn all implement the same interface. And all three communicate with the Repository Layer—libsvn_ra_dav and libsvn_ra_svn do so across a network, and libsvn_ra_local connects to it directly. The libsvn_fs_base and libsvn_fs_fs libraries are another example of this.

The client itself also highlights modularity in the Subversion design. While Subversion itself comes with only a command-line client program, there are several third party programs which provide various forms of client GUI. These GUIs use the same APIs that the stock command-line client does. Subversion's libsvn_client library is the one-stop shop for most of the functionality necessary for designing a working Subversion client (see «Client Layer»).

Repository Layer

When referring to Subversion's Repository Layer, we're generally talking about two libraries—the repository library, and the filesystem library. These libraries provide the storage and reporting mechanisms for the various revisions of your version-controlled data. This layer is connected to the Client Layer via the Repository Access Layer, and is, from the perspective of the Subversion user, the stuff at the «other end of the line.»

The Subversion Filesystem is accessed via the libsvn_fs API, and is not a kernel-level filesystem that one would install in an operating system (like the Linux ext2 or NTFS), but a virtual filesystem. Rather than storing «files» and «directories» as real files and directories (as in, the kind you can navigate through using your favorite shell program), it uses one of two available abstract storage backends—either a Berkeley DB database environment, or a flat-file representation. (To learn more about the two repository back-ends, see «Repository Data Stores».) However, there has been considerable interest by the development community in giving future releases of Subversion the ability to use other back-end database systems, perhaps through a mechanism such as Open Database Connectivity (ODBC).

The filesystem API exported by libsvn_fs contains the kinds of functionality you would expect from any other filesystem API: you can create and remove files and directories, copy and move them around, modify file contents, and so on. It also has features that are not quite as common, such as the ability to add, modify, and remove metadata («properties») on each file or directory. Furthermore, the Subversion Filesystem is a versioning filesystem, which means that as you make changes to your directory tree, Subversion remembers what your tree looked like before those changes. And before the previous changes. And the previous ones. And so on, all the way back through versioning time to (and just beyond) the moment you first started adding things to the filesystem.

All the modifications you make to your tree are done within the context of a Subversion transaction. The following is a simplified general routine for modifying your filesystem:

  1. Begin a Subversion transaction.

  2. Make your changes (adds, deletes, property modifications, etc.).

  3. Commit your transaction.

Once you have committed your transaction, your filesystem modifications are permanently stored as historical artifacts. Each of these cycles generates a single new revision of your tree, and each revision is forever accessible as an immutable snapshot of «the way things were.»

Most of the functionality provided by the filesystem interface comes as an action that occurs on a filesystem path. That is, from outside of the filesystem, the primary mechanism for describing and accessing the individual revisions of files and directories comes through the use of path strings like /foo/bar, just as if you were addressing files and directories through your favorite shell program. You add new files and directories by passing their paths-to-be to the right API functions. You query for information about them by the same mechanism.

Unlike most filesystems, though, a path alone is not enough information to identify a file or directory in Subversion. Think of a directory tree as a two-dimensional system, where a node's siblings represent a sort of left-and-right motion, and descending into subdirectories a downward motion. Рисунок 8.1, «Files and directories in two dimensions» shows a typical representation of a tree as exactly that.

Рисунок 8.1. Files and directories in two dimensions

Files and directories in two dimensions


Of course, the Subversion filesystem has a nifty third dimension that most filesystems do not have—Time! [52] In the filesystem interface, nearly every function that has a path argument also expects a root argument. This svn_fs_root_t argument describes either a revision or a Subversion transaction (which is usually just a revision-to-be), and provides that third-dimensional context needed to understand the difference between /foo/bar in revision 32, and the same path as it exists in revision 98. Рисунок 8.2, «Versioning time—the third dimension!» shows revision history as an added dimension to the Subversion filesystem universe.

Рисунок 8.2. Versioning time—the third dimension!

Versioning time—the third dimension!


As we mentioned earlier, the libsvn_fs API looks and feels like any other filesystem, except that it has this wonderful versioning capability. It was designed to be usable by any program interested in a versioning filesystem. Not coincidentally, Subversion itself is interested in that functionality. But while the filesystem API should be sufficient for basic file and directory versioning support, Subversion wants more—and that is where libsvn_repos comes in.

The Subversion repository library (libsvn_repos) is basically a wrapper library around the filesystem functionality. This library is responsible for creating the repository layout, making sure that the underlying filesystem is initialized, and so on. Libsvn_repos also implements a set of hooks—scripts that are executed by the repository code when certain actions take place. These scripts are useful for notification, authorization, or whatever purposes the repository administrator desires. This type of functionality, and other utilities provided by the repository library, are not strictly related to implementing a versioning filesystem, which is why it was placed into its own library.

Developers who wish to use the libsvn_repos API will find that it is not a complete wrapper around the filesystem interface. That is, only certain major events in the general cycle of filesystem activity are wrapped by the repository interface. Some of these include the creation and commit of Subversion transactions, and the modification of revision properties. These particular events are wrapped by the repository layer because they have hooks associated with them. In the future, other events may be wrapped by the repository API. All of the remaining filesystem interaction will continue to occur directly via the libsvn_fs API, though.

For example, here is a code segment that illustrates the use of both the repository and filesystem interfaces to create a new revision of the filesystem in which a directory is added. Note that in this example, the SVN_ERR() macro simply checks for a non-successful error return from the function it wraps, and returns that error if it exists.

Пример 8.1. Using the Repository Layer

/* Create a new directory at the path NEW_DIRECTORY in the Subversion
   repository located at REPOS_PATH.  Perform all memory allocation in
   POOL.  This function will create a new revision for the addition of
   NEW_DIRECTORY.  */
static svn_error_t *
make_new_directory (const char *repos_path,
                    const char *new_directory,
                    apr_pool_t *pool)
{
  svn_error_t *err;
  svn_repos_t *repos;
  svn_fs_t *fs;
  svn_revnum_t youngest_rev;
  svn_fs_txn_t *txn;
  svn_fs_root_t *txn_root;
  const char *conflict_str;

  /* Open the repository located at REPOS_PATH.  */
  SVN_ERR (svn_repos_open (&repos, repos_path, pool));

  /* Get a pointer to the filesystem object that is stored in
     REPOS.  */
  fs = svn_repos_fs (repos);

  /* Ask the filesystem to tell us the youngest revision that
     currently exists.  */
  SVN_ERR (svn_fs_youngest_rev (&youngest_rev, fs, pool));

  /* Begin a new transaction that is based on YOUNGEST_REV.  We are
     less likely to have our later commit rejected as conflicting if we
     always try to make our changes against a copy of the latest snapshot
     of the filesystem tree.  */
  SVN_ERR (svn_fs_begin_txn (&txn, fs, youngest_rev, pool));

  /* Now that we have started a new Subversion transaction, get a root
     object that represents that transaction.  */
  SVN_ERR (svn_fs_txn_root (&txn_root, txn, pool));

  /* Create our new directory under the transaction root, at the path
     NEW_DIRECTORY.  */
  SVN_ERR (svn_fs_make_dir (txn_root, new_directory, pool));

  /* Commit the transaction, creating a new revision of the filesystem
     which includes our added directory path.  */
  err = svn_repos_fs_commit_txn (&conflict_str, repos,
                                 &youngest_rev, txn, pool);
  if (! err)
    {
      /* No error?  Excellent!  Print a brief report of our success.  */
      printf ("Directory '%s' was successfully added as new revision "
              "'%ld'.\n", new_directory, youngest_rev);
    }
  else if (err->apr_err == SVN_ERR_FS_CONFLICT)
    {
      /* Uh-oh.  Our commit failed as the result of a conflict
         (someone else seems to have made changes to the same area
         of the filesystem that we tried to modify).  Print an error
         message.  */
      printf ("A conflict occurred at path '%s' while attempting "
              "to add directory '%s' to the repository at '%s'.\n",
              conflict_str, new_directory, repos_path);
    }
  else
    {
      /* Some other error has occurred.  Print an error message.  */
      printf ("An error occurred while attempting to add directory '%s' "
              "to the repository at '%s'.\n",
              new_directory, repos_path);
    }

  /* Return the result of the attempted commit to our caller.  */
  return err;
}


In the previous code segment, calls were made to both the repository and filesystem interfaces. We could just as easily have committed the transaction using svn_fs_commit_txn(). But the filesystem API knows nothing about the repository library's hook mechanism. If you want your Subversion repository to automatically perform some set of non-Subversion tasks every time you commit a transaction (like, for example, sending an email that describes all the changes made in that transaction to your developer mailing list), you need to use the libsvn_repos-wrapped version of that function—svn_repos_fs_commit_txn(). This function will actually first run the pre-commit hook script if one exists, then commit the transaction, and finally will run a post-commit hook script. The hooks provide a special kind of reporting mechanism that does not really belong in the core filesystem library itself. (For more information regarding Subversion's repository hooks, see «Hook Scripts».)

The hook mechanism requirement is but one of the reasons for the abstraction of a separate repository library from the rest of the filesystem code. The libsvn_repos API provides several other important utilities to Subversion. These include the abilities to:

  1. create, open, destroy, and perform recovery steps on a Subversion repository and the filesystem included in that repository.

  2. describe the differences between two filesystem trees.

  3. query for the commit log messages associated with all (or some) of the revisions in which a set of files was modified in the filesystem.

  4. generate a human-readable «dump» of the filesystem, a complete representation of the revisions in the filesystem.

  5. parse that dump format, loading the dumped revisions into a different Subversion repository.

As Subversion continues to evolve, the repository library will grow with the filesystem library to offer increased functionality and configurable option support.

Repository Access Layer

If the Subversion Repository Layer is at «the other end of the line», the Repository Access Layer is the line itself. Charged with marshalling data between the client libraries and the repository, this layer includes the libsvn_ra module loader library, the RA modules themselves (which currently includes libsvn_ra_dav, libsvn_ra_local, and libsvn_ra_svn), and any additional libraries needed by one or more of those RA modules, such as the mod_dav_svn Apache module with which libsvn_ra_dav communicates or libsvn_ra_svn's server, svnserve.

Since Subversion uses URLs to identify its repository resources, the protocol portion of the URL schema (usually file:, http:, https:, or svn:) is used to determine which RA module will handle the communications. Each module registers a list of the protocols it knows how to «speak» so that the RA loader can, at runtime, determine which module to use for the task at hand. You can determine which RA modules are available to the Subversion command-line client, and what protocols they claim to support, by running svn --version:

$ svn --version
svn, version 1.2.3 (r15833)
   compiled Sep 13 2005, 22:45:22

Copyright (C) 2000-2005 CollabNet.
Subversion is open source software, see http://subversion.tigris.org/
This product includes software developed by CollabNet (http://www.Collab.Net/).

The following repository access (RA) modules are available:

* ra_dav : Module for accessing a repository via WebDAV (DeltaV) protocol.
  - handles 'http' scheme
  - handles 'https' scheme
* ra_svn : Module for accessing a repository using the svn network protocol.
  - handles 'svn' scheme
* ra_local : Module for accessing a repository on local disk.
  - handles 'file' scheme

RA-DAV (Repository Access Using HTTP/DAV)

The libsvn_ra_dav library is designed for use by clients that are being run on different machines than the servers with which they communicating, specifically servers reached using URLs that contain the http: or https: protocol portions. To understand how this module works, we should first mention a couple of other key components in this particular configuration of the Repository Access Layer—the powerful Apache HTTP Server, and the Neon HTTP/WebDAV client library.

Subversion's primary network server is the Apache HTTP Server. Apache is a time-tested, extensible open-source server process that is ready for serious use. It can sustain a high network load and runs on many platforms. The Apache server supports a number of different standard authentication protocols, and can be extended through the use of modules to support many others. It also supports optimizations like network pipelining and caching. By using Apache as a server, Subversion gets all of these features for free. And since most firewalls already allow HTTP traffic to pass through, system administrators typically don't even have to change their firewall configurations to allow Subversion to work.

Subversion uses HTTP and WebDAV (with DeltaV) to communicate with an Apache server. You can read more about this in the WebDAV section of this chapter, but in short, WebDAV and DeltaV are extensions to the standard HTTP 1.1 protocol that enable sharing and versioning of files over the web. Apache 2.0 and later versions come with mod_dav, an Apache module that understands the DAV extensions to HTTP. Subversion itself supplies mod_dav_svn, though, which is another Apache module that works in conjunction with (really, as a back-end to) mod_dav to provide Subversion's specific implementations of WebDAV and DeltaV.

When communicating with a repository over HTTP, the RA loader library chooses libsvn_ra_dav as the proper access module. The Subversion client makes calls into the generic RA interface, and libsvn_ra_dav maps those calls (which embody rather large-scale Subversion actions) to a set of HTTP/WebDAV requests. Using the Neon library, libsvn_ra_dav transmits those requests to the Apache server. Apache receives these requests (exactly as it does generic HTTP requests that your web browser might make), notices that the requests are directed at a URL that is configured as a DAV location (using the <Location> directive in httpd.conf), and hands the request off to its own mod_dav module. When properly configured, mod_dav knows to use Subversion's mod_dav_svn for any filesystem-related needs, as opposed to the generic mod_dav_fs that comes with Apache. So ultimately, the client is communicating with mod_dav_svn, which binds directly to the Subversion Repository Layer.

That was a simplified description of the actual exchanges taking place, though. For example, the Subversion repository might be protected by Apache's authorization directives. This could result in initial attempts to communicate with the repository being rejected by Apache on authorization grounds. At this point, libsvn_ra_dav gets back the notice from Apache that insufficient identification was supplied, and calls back into the Client Layer to get some updated authentication data. If the data is supplied correctly, and the user has the permissions that Apache seeks, libsvn_ra_dav's next automatic attempt at performing the original operation will be granted, and all will be well. If sufficient authentication information cannot be supplied, the request will ultimately fail, and the client will report the failure to the user.

By using Neon and Apache, Subversion gets free functionality in several other complex areas, too. For example, if Neon finds the OpenSSL libraries, it allows the Subversion client to attempt to use SSL-encrypted communications with the Apache server (whose own mod_ssl can «speak the language»). Also, both Neon itself and Apache's mod_deflate can understand the «deflate» algorithm (the same one used by the PKZIP and gzip programs), so requests can be sent in smaller, compressed chunks across the wire. Other complex features that Subversion hopes to support in the future include the ability to automatically handle server-specified redirects (for example, when a repository has been moved to a new canonical URL) and taking advantage of HTTP pipelining.

RA-SVN (Custom Protocol Repository Access)

In addition to the standard HTTP/WebDAV protocol, Subversion also provides an RA implementation that uses a custom protocol. The libsvn_ra_svn module implements its own network socket connectivity, and communicates with a stand-alone server—the svnserve program—on the machine that hosts the repository. Clients access the repository using the svn:// schema.

This RA implementation lacks most of the advantages of Apache mentioned in the previous section; however, it may be appealing to some system administrators nonetheless. It is dramatically easier to configure and run; setting up an svnserve process is nearly instantaneous. It is also much smaller (in terms of lines of code) than Apache, making it much easier to audit, for security reasons or otherwise. Furthermore, some system administrators may already have an SSH security infrastructure in place, and want Subversion to use it. Clients using ra_svn can easily tunnel the protocol over SSH.

RA-Local (Direct Repository Access)

Not all communications with a Subversion repository require a powerhouse server process and a network layer. For users who simply wish to access the repositories on their local disk, they may do so using file: URLs and the functionality provided by libsvn_ra_local. This RA module binds directly with the repository and filesystem libraries, so no network communication is required at all.

Subversion requires that the server name included as part of the file: URL be either localhost or empty, and that there be no port specification. In other words, your URLs should look like either file://localhost/path/to/repos or file:///path/to/repos.

Also, be aware that Subversion's file: URLs cannot be used in a regular web browser the way typical file: URLs can. When you attempt to view a file: URL in a regular web browser, it reads and displays the contents of the file at that location by examining the filesystem directly. However, Subversion's resources exist in a virtual filesystem (see «Repository Layer»), and your browser will not understand how to read that filesystem.

Your RA Library Here

For those who wish to access a Subversion repository using still another protocol, that is precisely why the Repository Access Layer is modularized! Developers can simply write a new library that implements the RA interface on one side and communicates with the repository on the other. Your new library can use existing network protocols, or you can invent your own. You could use inter-process communication (IPC) calls, or—let's get crazy, shall we?—you could even implement an email-based protocol. Subversion supplies the APIs; you supply the creativity.

Client Layer

On the client side, the Subversion working copy is where all the action takes place. The bulk of functionality implemented by the client-side libraries exists for the sole purpose of managing working copies—directories full of files and other subdirectories which serve as a sort of local, editable «reflection» of one or more repository locations—and propagating changes to and from the Repository Access layer.

Subversion's working copy library, libsvn_wc, is directly responsible for managing the data in the working copies. To accomplish this, the library stores administrative information about each working copy directory within a special subdirectory. This subdirectory, named .svn, is present in each working copy directory and contains various other files and directories which record state and provide a private workspace for administrative action. For those familiar with CVS, this .svn subdirectory is similar in purpose to the CVS administrative directories found in CVS working copies. For more information about the .svn administrative area, see «Inside the Working Copy Administration Area»in this chapter.

The Subversion client library, libsvn_client, has the broadest responsibility; its job is to mingle the functionality of the working copy library with that of the Repository Access Layer, and then to provide the highest-level API to any application that wishes to perform general revision control actions. For example, the function svn_client_checkout() takes a URL as an argument. It passes this URL to the RA layer and opens an authenticated session with a particular repository. It then asks the repository for a certain tree, and sends this tree into the working copy library, which then writes a full working copy to disk (.svn directories and all).

The client library is designed to be used by any application. While the Subversion source code includes a standard command-line client, it should be very easy to write any number of GUI clients on top of the client library. New GUIs (or any new client, really) for Subversion need not be clunky wrappers around the included command-line client—they have full access via the libsvn_client API to same functionality, data, and callback mechanisms that the command-line client uses.

Using the APIs

Developing applications against the Subversion library APIs is fairly straightforward. All of the public header files live in the subversion/include directory of the source tree. These headers are copied into your system locations when you build and install Subversion itself from source. These headers represent the entirety of the functions and types meant to be accessible by users of the Subversion libraries.

The first thing you might notice is that Subversion's datatypes and functions are namespace protected. Every public Subversion symbol name begins with svn_, followed by a short code for the library in which the symbol is defined (such as wc, client, fs, etc.), followed by a single underscore (_) and then the rest of the symbol name. Semi-public functions (used among source files of a given library but not by code outside that library, and found inside the library directories themselves) differ from this naming scheme in that instead of a single underscore after the library code, they use a double underscore (__). Functions that are private to a given source file have no special prefixing, and are declared static. Of course, a compiler isn't interested in these naming conventions, but they help to clarify the scope of a given function or datatype.

The Apache Portable Runtime Library

Along with Subversion's own datatypes, you will see many references to datatypes that begin with apr_—symbols from the Apache Portable Runtime (APR) library. APR is Apache's portability library, originally carved out of its server code as an attempt to separate the OS-specific bits from the OS-independent portions of the code. The result was a library that provides a generic API for performing operations that differ mildly—or wildly—from OS to OS. While the Apache HTTP Server was obviously the first user of the APR library, the Subversion developers immediately recognized the value of using APR as well. This means that there are practically no OS-specific code portions in Subversion itself. Also, it means that the Subversion client compiles and runs anywhere that the server does. Currently this list includes all flavors of Unix, Win32, BeOS, OS/2, and Mac OS X.

In addition to providing consistent implementations of system calls that differ across operating systems, [53] APR gives Subversion immediate access to many custom datatypes, such as dynamic arrays and hash tables. Subversion uses these types extensively throughout the codebase. But perhaps the most pervasive APR datatype, found in nearly every Subversion API prototype, is the apr_pool_t—the APR memory pool. Subversion uses pools internally for all its memory allocation needs (unless an external library requires a different memory management schema for data passed through its API), [54] and while a person coding against the Subversion APIs is not required to do the same, they are required to provide pools to the API functions that need them. This means that users of the Subversion API must also link against APR, must call apr_initialize() to initialize the APR subsystem, and then must create and manage pools for use with Subversion API calls, typically by using svn_pool_create(), svn_pool_clear(), and svn_pool_destroy().

URL and Path Requirements

With remote version control operation as the whole point of Subversion's existence, it makes sense that some attention has been paid to internationalization (i18n) support. After all, while «remote» might mean «across the office», it could just as well mean «across the globe.» To facilitate this, all of Subversion's public interfaces that accept path arguments expect those paths to be canonicalized, and encoded in UTF-8. This means, for example, that any new client binary that drives the libsvn_client interface needs to first convert paths from the locale-specific encoding to UTF-8 before passing those paths to the Subversion libraries, and then re-convert any resultant output paths from Subversion back into the locale's encoding before using those paths for non-Subversion purposes. Fortunately, Subversion provides a suite of functions (see subversion/include/svn_utf.h) that can be used by any program to do these conversions.

Also, Subversion APIs require all URL parameters to be properly URI-encoded. So, instead of passing file:///home/username/My File.txt as the URL of a file named My File.txt, you need to pass file:///home/username/My%20File.txt. Again, Subversion supplies helper functions that your application can use—svn_path_uri_encode() and svn_path_uri_decode(), for URI encoding and decoding, respectively.

Using Languages Other than C and C++

If you are interested in using the Subversion libraries in conjunction with something other than a C program—say a Python or Perl script—Subversion has some support for this via the Simplified Wrapper and Interface Generator (SWIG). The SWIG bindings for Subversion are located in subversion/bindings/swig and whilst still maturing, they are in a usable state. These bindings allow you to call Subversion API functions indirectly, using wrappers that translate the datatypes native to your scripting language into the datatypes needed by Subversion's C libraries.

There is an obvious benefit to accessing the Subversion APIs via a language binding—simplicity. Generally speaking, languages such as Python and Perl are much more flexible and easy to use than C or C++. The sort of high-level datatypes and context-driven type checking provided by these languages are often better at handling information that comes from users. As you know, humans are proficient at botching up input to a program, and scripting languages tend to handle that misinformation more gracefully. Of course, often that flexibility comes at the cost of performance. That is why using a tightly-optimized, C-based interface and library suite, combined with a powerful, flexible binding language, is so appealing.

Let's look at a sample program that uses Subversion's Python SWIG bindings to recursively crawl the youngest repository revision, and print the various paths reached during the crawl.

Пример 8.2. Using the Repository Layer with Python

#!/usr/bin/python

"""Crawl a repository, printing versioned object path names."""

import sys
import os.path
import svn.fs, svn.core, svn.repos

def crawl_filesystem_dir(root, directory, pool):
    """Recursively crawl DIRECTORY under ROOT in the filesystem, and return
    a list of all the paths at or below DIRECTORY.  Use POOL for all
    allocations."""

    # Print the name of this path.
    print directory + "/"

    # Get the directory entries for DIRECTORY.
    entries = svn.fs.svn_fs_dir_entries(root, directory, pool)

    # Use an iteration subpool.
    subpool = svn.core.svn_pool_create(pool)

    # Loop over the entries.
    names = entries.keys()
    for name in names:
        # Clear the iteration subpool.
        svn.core.svn_pool_clear(subpool)

        # Calculate the entry's full path.
        full_path = directory + '/' + name

        # If the entry is a directory, recurse.  The recursion will return
        # a list with the entry and all its children, which we will add to
        # our running list of paths.
        if svn.fs.svn_fs_is_dir(root, full_path, subpool):
            crawl_filesystem_dir(root, full_path, subpool)
        else:
            # Else it's a file, so print its path here.
            print full_path

    # Destroy the iteration subpool.
    svn.core.svn_pool_destroy(subpool)

def crawl_youngest(pool, repos_path):
    """Open the repository at REPOS_PATH, and recursively crawl its
    youngest revision."""

    # Open the repository at REPOS_PATH, and get a reference to its
    # versioning filesystem.
    repos_obj = svn.repos.svn_repos_open(repos_path, pool)
    fs_obj = svn.repos.svn_repos_fs(repos_obj)

    # Query the current youngest revision.
    youngest_rev = svn.fs.svn_fs_youngest_rev(fs_obj, pool)

    # Open a root object representing the youngest (HEAD) revision.
    root_obj = svn.fs.svn_fs_revision_root(fs_obj, youngest_rev, pool)

    # Do the recursive crawl.
    crawl_filesystem_dir(root_obj, "", pool)

if __name__ == "__main__":
    # Check for sane usage.
    if len(sys.argv) != 2:
        sys.stderr.write("Usage: %s REPOS_PATH\n"
                         % (os.path.basename(sys.argv[0])))
        sys.exit(1)

    # Canonicalize (enough for Subversion, at least) the repository path.
    repos_path = os.path.normpath(sys.argv[1])
    if repos_path == '.': 
        repos_path = ''

    # Call the app-wrapper, which takes care of APR initialization/shutdown
    # and the creation and cleanup of our top-level memory pool.
    svn.core.run_app(crawl_youngest, repos_path)


This same program in C would need to deal with custom datatypes (such as those provided by the APR library) for representing the hash of entries and the list of paths, but Python has hashes (called «dictionaries») and lists as built-in datatypes, and provides a rich collection of functions for operating on those types. So SWIG (with the help of some customizations in Subversion's language bindings layer) takes care of mapping those custom datatypes into the native datatypes of the target language. This provides a more intuitive interface for users of that language.

The Subversion Python bindings can be used for working copy operations, too. In the previous section of this chapter, we mentioned the libsvn_client interface, and how it exists for the sole purpose of simplifying the process of writing a Subversion client. The following is a brief example of how that library can be accessed via the SWIG bindings to recreate a scaled-down version of the svn status command.

Пример 8.3. A Python Status Crawler

#!/usr/bin/env python

"""Crawl a working copy directory, printing status information."""

import sys
import os.path
import getopt
import svn.core, svn.client, svn.wc

def generate_status_code(status):
    """Translate a status value into a single-character status code,
    using the same logic as the Subversion command-line client."""

    if status == svn.wc.svn_wc_status_none:
        return ' '
    if status == svn.wc.svn_wc_status_normal:
        return ' '
    if status == svn.wc.svn_wc_status_added:
        return 'A'
    if status == svn.wc.svn_wc_status_missing:
        return '!'
    if status == svn.wc.svn_wc_status_incomplete:
        return '!'
    if status == svn.wc.svn_wc_status_deleted:
        return 'D'
    if status == svn.wc.svn_wc_status_replaced:
        return 'R'
    if status == svn.wc.svn_wc_status_modified:
        return 'M'
    if status == svn.wc.svn_wc_status_merged:
        return 'G'
    if status == svn.wc.svn_wc_status_conflicted:
        return 'C'
    if status == svn.wc.svn_wc_status_obstructed:
        return '~'
    if status == svn.wc.svn_wc_status_ignored:
        return 'I'
    if status == svn.wc.svn_wc_status_external:
        return 'X'
    if status == svn.wc.svn_wc_status_unversioned:
        return '?'
    return '?'

def do_status(pool, wc_path, verbose):
    # Calculate the length of the input working copy path.
    wc_path_len = len(wc_path)

    # Build a client context baton.
    ctx = svn.client.svn_client_ctx_t()

    def _status_callback(path, status, root_path_len=wc_path_len):
        """A callback function for svn_client_status."""

        # Print the path, minus the bit that overlaps with the root of
        # the status crawl
        text_status = generate_status_code(status.text_status)
        prop_status = generate_status_code(status.prop_status)
        print '%s%s  %s' % (text_status, prop_status, path[wc_path_len + 1:])

    # Do the status crawl, using _status_callback() as our callback function.
    svn.client.svn_client_status(wc_path, None, _status_callback,
                                 1, verbose, 0, 0, ctx, pool)

def usage_and_exit(errorcode):
    """Print usage message, and exit with ERRORCODE."""
    stream = errorcode and sys.stderr or sys.stdout
    stream.write("""Usage: %s OPTIONS WC-PATH
Options:
  --help, -h    : Show this usage message
  --verbose, -v : Show all statuses, even uninteresting ones
""" % (os.path.basename(sys.argv[0])))
    sys.exit(errorcode)

if __name__ == '__main__':
    # Parse command-line options.
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hv", ["help", "verbose"])
    except getopt.GetoptError:
        usage_and_exit(1)
    verbose = 0
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage_and_exit(0)
        if opt in ("-v", "--verbose"):
            verbose = 1
    if len(args) != 1:
        usage_and_exit(2)

    # Canonicalize (enough for Subversion, at least) the working copy path.
    wc_path = os.path.normpath(args[0])
    if wc_path == '.': 
        wc_path = ''

    # Call the app-wrapper, which takes care of APR initialization/shutdown
    # and the creation and cleanup of our top-level memory pool.
    svn.core.run_app(do_status, wc_path, verbose)


Subversion's language bindings unfortunately tend to lack the level of attention given to the core Subversion modules. However, there have been significant efforts towards creating functional bindings for Python, Perl, and Ruby. To some extent, the work done preparing the SWIG interface files for these languages is reusable in efforts to generate bindings for other languages supported by SWIG (which includes versions of C#, Guile, Java, MzScheme, OCaml, PHP, Tcl, and others). However, some extra programming is required to compensate for complex APIs that SWIG needs some help interfacing with. For more information on SWIG itself, see the project's website at http://www.swig.org/.

Inside the Working Copy Administration Area

As we mentioned earlier, each directory of a Subversion working copy contains a special subdirectory called .svn which houses administrative data about that working copy directory. Subversion uses the information in .svn to keep track of things like:

  • Which repository location(s) are represented by the files and subdirectories in the working copy directory.

  • What revision of each of those files and directories are currently present in the working copy.

  • Any user-defined properties that might be attached to those files and directories.

  • Pristine (un-edited) copies of the working copy files.

While there are several other bits of data stored in the .svn directory, we will examine only a couple of the most important items.

The Entries File

Perhaps the single most important file in the .svn directory is the entries file. The entries file is an XML document which contains the bulk of the administrative information about a versioned resource in a working copy directory. It is this one file which tracks the repository URLs, pristine revision, file checksums, pristine text and property timestamps, scheduling and conflict state information, last-known commit information (author, revision, timestamp), local copy history—practically everything that a Subversion client is interested in knowing about a versioned (or to-be-versioned) resource!

The following is an example of an actual entries file:

Пример 8.4. Contents of a Typical .svn/entries File

<?xml version="1.0" encoding="utf-8"?>
<wc-entries
   xmlns="svn:">
<entry
   committed-rev="1"
   name=""
   committed-date="2005-04-04T13:32:28.526873Z"
   url="http://svn.red-bean.com/repos/greek-tree/A/D"
   last-author="jrandom"
   kind="dir"
   uuid="4e820d15-a807-0410-81d5-aa59edf69161"
   revision="1"/>
<entry
   name="lambda"
   copied="true"
   kind="file"
   copyfrom-rev="1"
   schedule="add"
   copyfrom-url="http://svn.red-bean.com/repos/greek-tree/A/B/lambda"/>
<entry
   committed-rev="1"
   name="gamma"
   text-time="2005-12-11T16:32:46.000000Z"
   committed-date="2005-04-04T13:32:28.526873Z"
   checksum="ada10d942b1964d359e048dbacff3460"
   last-author="jrandom"
   kind="file"
   prop-time="2005-12-11T16:32:45.000000Z"/>
<entry
   name="zeta"
   kind="file"
   schedule="add"
   revision="0"/>
<entry
   name="G"
   kind="dir"/>
<entry
   name="H"
   kind="dir"
   schedule="delete"/>
</wc-entries>


As you can see, the entries file is essentially a list of entries. Each entry tag represents one of three things: the working copy directory itself (called the «this directory» entry, and noted as having an empty value for its name attribute), a file in that working copy directory (noted by having its kind attribute set to "file"), or a subdirectory in that working copy (kind here is set to "dir"). The files and subdirectories whose entries are stored in this file are either already under version control, or (as in the case of the file named zeta above) are scheduled to be added to version control when the user next commits this working copy directory's changes. Each entry has a unique name, and each entry has a node kind.

Developers should be aware of some special rules that Subversion uses when reading and writing its entries files. While each entry has a revision and URL associated with it, note that not every entry tag in the sample file has explicit revision or url attributes attached to it. Subversion allows entries to not explicitly store those two attributes when their values are the same as (in the revision case) or trivially calculable from [55] (in the url case) the data stored in the «this directory» entry. Note also that for subdirectory entries, Subversion stores only the crucial attributes—name, kind, url, revision, and schedule. In an effort to reduce duplicated information, Subversion dictates that the method for determining the full set of information about a subdirectory is to traverse down into that subdirectory, and read the «this directory» entry from its own .svn/entries file. However, a reference to the subdirectory is kept in its parent's entries file, with enough information to permit basic versioning operations in the event that the subdirectory itself is actually missing from disk.

Pristine Copies and Property Files

As mentioned before, the .svn directory also holds the pristine «text-base» versions of files. Those can be found in .svn/text-base. The benefits of these pristine copies are multiple—network-free checks for local modifications and difference reporting, network-free reversion of modified or missing files, smaller transmission of changes to the server—but comes at the cost of having each versioned file stored at least twice on disk. These days, this seems to be a negligible penalty for most files. However, the situation gets uglier as the size of your versioned files grows. Some attention is being given to making the presence of the «text-base» an option. Ironically though, it is as your versioned files' sizes get larger that the existence of the «text-base» becomes more crucial—who wants to transmit a huge file across a network just because they want to commit a tiny change to it?

Similar in purpose to the «text-base» files are the property files and their pristine «prop-base» copies, located in .svn/props and .svn/prop-base respectively. Since directories can have properties, too, there are also .svn/dir-props and .svn/dir-prop-base files. Each of these property files («working» and «base» versions) uses a simple «hash-on-disk» file format for storing the property names and values.

WebDAV

WebDAV (shorthand for «Web-based Distributed Authoring and Versioning») is an extension of the standard HTTP protocol designed to make the web into a read/write medium, instead of the basically read-only medium that exists today. The theory is that directories and files can be shared—as both readable and writable objects—over the web. RFCs 2518 and 3253 describe the WebDAV/DeltaV extensions to HTTP, and are available (along with a lot of other useful information) at http://www.webdav.org/.

A number of operating system file browsers are already able to mount networked directories using WebDAV. On Win32, the Windows Explorer can browse what it calls Web Folders (which are just WebDAV-ready network locations) as if they were regular shared folders. Mac OS X also has this capability, as do the Nautilus and Konqueror browsers (under GNOME and KDE, respectively).

How does all of this apply to Subversion? The mod_dav_svn Apache module uses HTTP, extended by WebDAV and DeltaV, as one of its network protocols. Subversion uses mod_dav_svn to map between Subversion's versioning concepts and those of RFCs 2518 and 3253.

For a more thorough discussion of WebDAV, how it works, and how Subversion uses it, see Приложение C, WebDAV и автоматическое управление версиями. Among other things, that appendix discusses the degree to which Subversion adheres to the generic WebDAV specification, and how that affects interoperability with generic WebDAV clients.




[52] We understand that this may come as a shock to sci-fi fans who have long been under the impression that Time was actually the fourth dimension, and we apologize for any emotional trauma induced by our assertion of a different theory.

[53] Subversion uses ANSI system calls and datatypes as much as possible.

[54] Neon and Berkeley DB are examples of such libraries.

[55] That is, the URL for the entry is the same as the concatenation of the parent directory's URL and the entry's name.

Глава 9. Полное справочное руководство по Subversion

Эта глава является исчерпывающим справочным руководством по использованию Subversion. Она описывает работу программы-клиента командной строки (svn) и всех его подкоманд, а так же программы администрирования хранилища (svnadmin и svnlook) и соответствующие им подкоманды.

Клиент командной строки Subversion: svn

Для того что бы воспользоваться клиентом командной строки, введите svn, и желаемую подкоманду [56], а так же любые другие параметры командной строки, которые хотите задействовать. Порядок, в котором подкоманды и параметры командной строки должны быть использованы, не играет существенной роли. Например, всё нижеприведённое есть правильное использование svn status:

$ svn -v status
$ svn status -v
$ svn status -v myfile

Множество примеров использования большинства клиентских команд может быть найдено в главе Глава 2, Экскурсия по Subversion. Команды для управления свойствами описаны в главе «Свойства».

Параметры командной строкиsvn

Хотя Subversion имеет множество параметров командной строки для своих подкоманд, в каждый из них вкладывается один и тот же смысл в независимости от подкоманды с которой он используется. Например, --verbose (-v) всегда означает «детальный вывод», в независимости от того, с какой подкомандой вы его используете.

--auto-props

Включает auto-props, переопределяя значение директивы enable-auto-props из файла config.

--config-dir DIR

Заставляет Subversion использовать настройки из указанного каталога вместо используемого по умолчанию (.subversion в домашнем каталоге пользователя).

--diff-cmd CMD

Позволяет указать внешнюю программу построения различий между файлами. По умолчанию, подкоманда svn diff использует внутренний механизм сравнения Subversion, выдающий результат в едином формате записи различий (unified diffs). Воспользоваться внешней программой diff можно указав ее имя в качестве аргумента --diff-cmd. Необходимые аргументы могут быть переданы программе diff через параметр --extensions (будет описан ниже в этой главе).

--diff3-cmd CMD

Позволяет указать внешнюю программу для слияния файлов.

--dry-run

Выполняет все действия команды без внесения изменений на диск или в хранилище.

--editor-cmd CMD

Определяет внешнюю программу для редактирования комментария или свойства. Подробнее о том, как указать используемый по умолчанию редактор, смотрите раздел, посвященный editor-cmd в «Config».

--encoding ENC

Указывает Subversion кодировку комментариев. По умолчанию используется кодировка, установленная вашей операционной системе. Если ваш комментарий в другой кодировке - укажите ее явно.

--extensions (-x) ARGS

Определяет параметр который Subversion должна передать внешней программе diff, когда выясняется различие между файлами. Для передачи нескольких параметров, их нужно заключить их в кавычки (например, svn diff --diff-cmd /usr/bin/diff -x "-b -E"). Этот параметр командной строки может использоваться только совместно с параметром --diff-cmd.

--file (-F) FILENAME

Указывает что следует использовать содержимое указанного файла в качестве входных данных, запрашиваемых вызываемой подкомандой.

--force

Принуждает выполнить некоторые команды или операции. Есть рад операций, которые Subversion откажется выполнить в определенных условиях. Задавая этот параметр вы явно говорите Subversion «Я осознаю все возможные последствия моих действий, так что делай что тебе велят ». Этот параметр эквивалентен выполнению электромонтажных работ "под напряжением"—не зная что делаешь, рискуешь "попасть под фазу".

--force-log

Принуждает параметры --message (-m) или --file (-F) использовать следующий аргумент, каким бы подозрительным он не был. По умолчанию, Subversion будет выдавать ошибку, если значения этих параметров выглядят так, как если бы они были объектами, обрабатываемыми подкомандой. Например, когда в качестве значения параметра --file (-F) используется имя файла находящегося под контролем версий, Subversion предполагает что была допущена ошибка. Ей кажется, что вместо положенного в таком случае обычного файла, не находящегося под контролем версий, по ошибке был указан целевой файл вызываемой операции. Чтобы подтвердить свои намерения и обходить ошибки подобного рода, нужно явно указывать параметр --force-log для подкоманд, предполагающих ввод сообщений истории изменений.

--help (-h or -?)

Если используется с одной или более подкоманд—выводит внутреннюю подсказку каждой подкоманды. Если без подкоманд, то отображает общую подсказку.

--ignore-ancestry

Сообщает Subversion о необходимости игнорировать историю изменений при вычислении различий. То есть, полагаться только на текущее содержимое.

--ignore-externals

Сообщает Subversion о необходимости игнорировать внешние определения и соответствующие рабочие копии.

--incremental

Выводит результаты в удобном для конкатенации виде.

--limit NUM

Выводит только первые NUM сообщений истории изменений.

--message (-m) MESSAGE

Указывает на то, что следующим параметром является пояснение фиксируемых изменений. Например:

$ svn commit -m "They don't make Sunday."
--new ARG

Определяет ARG как более новый целевой объект.

--no-auth-cache

Препятствует хешированию идентификационной информации (например имя и пароль) в административном каталоге Subversion.

--no-auto-props

Отключает auto-props, переопределяя параметр enable-auto-props из файла config.

--no-diff-added

Препятствует отображению Subversion различий для добавленных под контроль версий файлов. По умолчанию, для добавленного файла svn diff выводит различия так, как если бы вы добавили содержимое для уже существующего, но пустого файла.

--no-diff-deleted

Препятствует отображению Subversion различий для удаленных из под контроля версий файлов. По умолчанию, для удаленного файла svn diff выводит различия так, как если файл существует, но с пустым содержимым.

--no-ignore

Показывает все файлы в списке состояния файлов, которые были бы пропущены как подпадающие под шаблон настройки конфигурации global-ignores или свойства svn:ignore. Смотри «Config» и «Пропуск неверсионированных элементов» для дополнительной информации.

--no-unlock

Не снимает блокировку с файлов автоматически. По умолчанию блокировка снимается для всех фалов, участвующих в фиксации изменений. Смотри «Locking» для для дополнительной информации.

--non-interactive

В случае ошибки идентификации или неполноты параметров идентификации, препятствует их запрашиванию (например, запросу имени или пароля). Это полезно при вызове Subversion из автоматизированных скриптов, в этом случае ошибка выполнения скрипта лучше, чем его останов интерактивными запросами Subversion о дополнительной информации.

--non-recursive (-N)

Запрещает рекурсивное выполнение подкоманды для вложенных каталогов. Большинство подкоманд выполняются рекурсивно по умолчанию, но некоторые—обычно те, что могут удалять или отменять ваши локальные изменения—таковыми не являются.

--notice-ancestry

Предлагает учитывать историю изменений при вычислении различий.

--old ARG

Определяет ARG как более поздний целевой объект.

--password PASS

Указывает на ваше желание явно задать пароль для аутентификации—как бы то ни было, если пароль потребуется, Subversion его у вас спросит.

--quiet (-q)

Требует сообщать только существенную информацию.

--recursive (-R)

Выполняет подкоманды рекурсивно для всех вложенных каталогов. Большинство подкоманд выполняются рекурсивно по умолчанию.

--relocate FROM TO [PATH...]

Используется совместно с подкомандой svn switch, предписывая вашей рабочей копии ссылаться на другое хранилище. Это полезно при изменении адреса вашего хранилища, когда вы уже имеете существующую рабочую копию, которую бы желали продолжать использовать. Обратитесь к руководству svn switch для получения примера использования.

--revision (-r) REV

Отражает ваше намерение выполнить операцию для указанной версии (или диапазона версий). В качестве значений параметра вы можете указывать номер версии, их ключевые слова или дату (в фигурных скобках). Если вы желаете указать диапазон версий, вы должны использовать двоеточие в качестве разделителя. Например:

$ svn log -r 1729
$ svn log -r 1729:HEAD
$ svn log -r 1729:1744
$ svn log -r {2001-12-04}:{2002-02-17}
$ svn log -r 1729:{2002-02-17}

Используйте «Ключевые слова правок» для дополнительной информации.

--revprop

Оперирует со свойствами правки, a не свойствами файла или каталога. Этот параметр требует указания версии посредством --revision (-r). Обратитесь к «Unversioned Properties» для более глубокого понимания неверсионных свойств.

--show-updates (-u)

Принуждает программу-клиента вывести информацию о нуждающихся в обновлении файлах вашей рабочей копии. При этом самого обновления не происходит—вы только видите список файлов, которые будут обновлены если вы запустите svn update.

--stop-on-copy

Говорит Subversion прекратить обработку истории изменений объекта, хранимого под контролем версий, как только встретится упоминание в истории о том что объект был скопирован из другого места в хранилище.

--strict

Требует от Subversion использовать строгую семантику. Описать изменение поведения подкоманды довольно трудно без учета специфики самой подкоманды.

--targets FILENAME

Используя этот параметр вы можете указать Subversion на файл, содержащий список файлов, которыми вы хотите оперировать, вместо того чтобы перечислять их в командной строке.

--username NAME

Указывает на имя пользователя для аутентификации. Как бы то ни было, если имя пользователя потребуется, Subversion его у вас спросит.

--verbose (-v)

Выражает просьбу комментировать процесс выполнения операции как можно более детально. Это может привести к выводу дополнительных полей, подробной информации по каждому файлу или более полной информации о выполняемой операции.

--version

Выводит информацию о версии программы-клиента. В дополнение к номеру версии выводится список всех способов доступа к хранилищу, которыми может оперировать этот клиент. С параметром --quiet (-q) в компактной форме выводится только информация о версии клиента.

--xml

Печатает вывод в XML-формате.

Подкоманды svn

Название

svn add — Добавляет файлы, директории и символические связи.

Формат

svn add PATH...

Описание

Добавляет файлы, директории и символические связи в вашу рабочею копию, помечая их для последующего добавления в хранилище. При фиксации изменений они добавляются в хранилище . Если вы что-то добавили, но потом передумали фиксировать добавление изменений, то снять метку добавления можно подкомандой svn revert.

Альтернативные имена

None

Изменяет

Рабочую копию

Требует доступа к хранилищу

Нет

Параметры

--targets FILENAME
--non-recursive (-N)
--quiet (-q)
--config-dir DIR
--auto-props
--no-auto-props
--force

Пример

Для добавления файла под контроль версий вашей рабочей копии:

$ svn add foo.c
A         foo.c

Если добавляется каталог, то по умолчанию svn add действует рекурсивно:

$ svn add testdir
A         testdir
A         testdir/a
A         testdir/b
A         testdir/c
A         testdir/d

Вы можете добавить каталог без добавления его содержимого:

$ svn add --non-recursive otherdir
A         otherdir

Обычно команда svn add * игнорирует каталоги, уже находящиеся под контролем версий. Иногда бывает нужно добавить все неверсионные объекты из вашей рабочей копии, включая те, что находятся внутри каталогов. Указав параметр --force, вы принудите svn add рекурсивно пройти по каталогам уже находящимся под контролем версий:

$ svn add * --force
A         foo.c
A         somedir/bar.c
A         otherdir/docs/baz.doc
…

Название

svn blame — Построчно показывает автора и версию для указанных файлов или URL-ов.

Формат

svn blame TARGET[@REV]...

Описание

Построчно показывает автора и версию для указанных файлов или URL-ов. Каждая строка текста начинается с имени автора (имени пользователя) и номера правки. Таким образом указывается кто и когда изменял эту строку последний раз.

Альтернативные имена

praise, annotate, ann

Изменяет

Ничего не меняет

Требует доступа к хранилищу

Да

Параметры

--revision (-r) REV
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR
--verbose (-v)

Примеры

Если вы хотите просмотреть аннотацию для файла readme.txt в тестовом хранилище:

$ svn blame http://svn.red-bean.com/repos/test/readme.txt
     3      sally This is a README file.
     5      harry You should read this.

Название

svn cat — Выводит содержимое указанных файлов или URL-ов.

Формат

svn cat TARGET[@REV]...

Описание

Выводит содержимое указанных файлов или URL-ов. Для перечисления содержимого каталогов используйте svn list.

Альтернативные имена

Нет

Изменяет

Ничего не меняет

Требует доступа к хранилищу

Да

Параметры

--revision (-r) REV
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR

Примеры

Если вы хотите просмотреть содержимое readme.txt из хранилища не создавая его рабочей копии, выполните:

$ svn cat http://svn.red-bean.com/repos/test/readme.txt
This is a README file.
You should read this.
[Подсказка]Подсказка

Если ваша рабочая копия устарела (или вы что-то в ней локально изменили), но хотите посмотреть HEAD версию файла, имеющегося в вашей рабочей копии, подкоманда svn cat автоматически извлечет HEAD версию, ей нужно только указать путь к этому файлу:

$ cat foo.c
This file is in my local working copy
and has changes that I've made.

$ svn cat foo.c
Latest revision fresh from the repository!

Название

svn checkout — Создает рабочую копию на основе данных из хранилища.

Формат

svn checkout URL[@REV]... [PATH]

Описание

Создает рабочую копию на основе данных из хранилища. Если PATH пропущен, базовое имя URL будет использоваться в качестве имени для каталога рабочей копии. Если задано несколько URL, соответствующие копии будут создаваться в подкаталоге PATH, каждая в своем каталоге образованном из базового имени URL.

Альтернативные имена

co

Изменяет

Создает рабочую копию.

Требует доступа к хранилищу

Да

Параметры

--revision (-r) REV
--quiet (-q)
--non-recursive (-N)
--username USER
--password PASS
--no-auth-cache
--non-interactive
--ignore-externals
--config-dir DIR

Примеры

Создать рабочую копию в директории с именем mine:

$ svn checkout file:///tmp/repos/test mine
A  mine/a
A  mine/b
Checked out revision 2.
$ ls
mine

Создать рабочие копии двух разных каталогов:

$ svn checkout file:///tmp/repos/test  file:///tmp/repos/quiz
A  test/a
A  test/b
Checked out revision 2.
A  quiz/l
A  quiz/m
Checked out revision 2.
$ ls
quiz  test

Создать рабочие копии двух разных каталогов в каталоге с именем working-copies:

$ svn checkout file:///tmp/repos/test  file:///tmp/repos/quiz working-copies
A  working-copies/test/a
A  working-copies/test/b
Checked out revision 2.
A  working-copies/quiz/l
A  working-copies/quiz/m
Checked out revision 2.
$ ls
working-copies

Если вы прервете создание копии (или что-то другое прервет, например, разрыв связи и т.п.), вы можете повторить процесс задав команду повторно или запросив обновить рабочую копию:

$ svn checkout file:///tmp/repos/test test
A  test/a
A  test/b
^C
svn: The operation was interrupted
svn: caught SIGINT

$ svn checkout file:///tmp/repos/test test
A  test/c
A  test/d
^C
svn: The operation was interrupted
svn: caught SIGINT

$ cd test
$ svn update
A  test/e
A  test/f
Updated to revision 3.

Название

svn cleanup — Рекурсивно чистит рабочую копию.

Формат

svn cleanup [PATH...]

Описание

Рекурсивно чистит рабочую копию, удаляя блокировки и выполняет незавершенные операции. Как только столкнетесь с ошибкой «рабочая копия заблокирована», запустите эту подкоманду для удаления старых блокировок и приведения рабочей копии в работоспособное состояние.

Если по некоторым причинам команда svn update завершилась с ошибкой из-за проблем с запущенным внешней программой различий (например, из-за пользовательского ввода или сбоя в сети), нужно задать параметр --diff3-cmd чтобы дать возможность при чистке копии завершить слияние используя внешнюю программу diff. Вы также можете указать конфигурационный каталог посредством параметра --config-dir, но постарайтесь не злоупотреблять этими параметрами.

Альтернативные имена

Нет

Изменяет

Рабочую копию.

Требует доступа к хранилищу

Нет

Параметры

--diff3-cmd CMD
--config-dir DIR

Примеры

Не много примеров использования подкоманды svn cleanup можно привести, так как она работает молча. Если вы не указали PATH, будет использовано «.» .

$ svn cleanup

$ svn cleanup /path/to/working-copy

Название

svn commit — Фиксирует сделанные вами изменения рабочей копии в хранилище.

Формат

svn commit [PATH...]

Описание

Фиксирует сделанные вами изменения рабочей копии в хранилище. Если вы не воспользовались ни --file, ни --message параметром, svn запустит внешний редактор для составления комментария. Обращайтесь за подробностями к описанию параметра editor-cmd в «Config».

svn commit отправит хранилищу все рекурсивно найденные метки блокировок и разблокирует соответствующие этим меткам ресурсы, если не был указан параметр --no-unlock. Место поиска задается указанием PATH.

[Подсказка]Подсказка

Если вы начали фиксацию изменений и Subversion запустила ваш внешний редактор для составления комментария, вы все еще можете прервать операцию фиксации изменений. Если вы хотите отменить фиксации, просто выйдете из редактора без сохранения изменений. Subversion заинтересуется - хотите ли вы прервать операцию, продолжить без описания изменений или же редактировать описания изменений снова.

Альтернативные имена

ci (сокращение от «check in»; a не «co», что есть сокращение для «checkout»)

Изменяет

Как рабочую копию, так и хранилище

Требует доступа к хранилищу

Да

Параметры

--message (-m) TEXT
--file (-F) FILE
--quiet (-q)
--no-unlock
--non-recursive (-N)
--targets FILENAME
--force-log
--username USER
--password PASS
--no-auth-cache
--non-interactive
--encoding ENC
--config-dir DIR

Примеры

Зафиксировать изменения файлов в хранилище из текущего каталога («.») и его подкаталогов, задав пояснение изменений в командной строке:

$ svn commit -m "added howto section."
Sending        a
Transmitting file data .
Committed revision 3.

Зафиксировать изменения файла foo.c (явно заданного в командной строке)задав пояснение изменений содержимым файла msg:

$ svn commit -F msg foo.c
Sending        foo.c
Transmitting file data .
Committed revision 5.

Если вы хотите использовать содержимое файла находящегося под контролем версий в качестве комментария (используя параметр --file), вы должны задать параметр --force-log для явного выражения своих намерений:

$ svn commit --file file_under_vc.txt foo.c
svn: The log message file is under version control
svn: Log message file is a versioned file; use '--force-log' to override

$ svn commit --force-log --file file_under_vc.txt foo.c
Sending        foo.c
Transmitting file data .
Committed revision 6.

Зафиксировать факт удаления файла:

$ svn commit -m "removed file 'c'."
Deleting       c

Committed revision 7.

Название

svn copy — Копирует файл или каталог в рабочей копии или хранилище.

Формат

svn copy SRC DST

Описание

Копирует файл в рабочей копии или в хранилище. SRC и DST могут быть путями как внутри рабочей копии, так и URL внутри хранилища:

WC -> WC

Планирует копирование объекта (вместе с историей).

WC -> URL

Создает копию объекта из рабочей копии непосредственно в хранилище.

URL -> WC

Выгружает копию объекта из хранилища в рабочую копию и планирует ее добавление.

URL -> URL

Выполняет копирование объектов непосредственно в хранилище. Обычно используется для создания ветки.

[Замечание]Замечание

Вы можете копировать файлы только внутри одного хранилища. Subversion не поддерживает межхранилищного копирования.

Альтернативные имена

cp

Изменяет

Хранилище, если копия задается через URL

Рабочая копия, если копия создается внутри неё.

Требует доступа к хранилищу

Да, если копируемый объект или место назначения расположены в хранилище, а так же если необходимо найти номер правки.

Параметры

--message (-m) TEXT
--file (-F) FILE
--revision (-r) REV
--quiet (-q)
--username USER
--password PASS
--no-auth-cache
--non-interactive
--force-log
--editor-cmd EDITOR
--encoding ENC
--config-dir DIR

Примеры

Создание копии объекта внутри рабочей копии (физическое копирование происходит после выполнения команды фиксации изменений):

$ svn copy foo.txt bar.txt
A         bar.txt
$ svn status
A  +   bar.txt

Создание копии объекта из рабочей копии в хранилище по заданному URL (изменения в хранилище вносятся незамедлительно, так что требуется задать пояснения изменений):

$ svn copy near.txt file:///tmp/repos/test/far-away.txt -m "Remote copy."

Committed revision 8.

Создание копии объекта из хранилища в рабочую копию (полученная копия планируется на добавление и в хранилище появится только после команды фиксации изменений:

[Подсказка]Подсказка

Это рекомендованный способ воскрешать случайно удаленные из хранилища файлы!

$ svn copy file:///tmp/repos/test/far-away near-here
A         near-here

И наконец, копирование внутри хранилища:

$ svn copy file:///tmp/repos/test/far-away file:///tmp/repos/test/over-there -m "remote copy."

Committed revision 9.
[Подсказка]Подсказка

Это простейший способ «установить метку» на версию в хранилище—просто выполните svn copy желаемой версии (хотя обычно это HEAD) в желаемый каталог.

$ svn copy file:///tmp/repos/test/trunk file:///tmp/repos/test/tags/0.6.32-prerelease -m "tag tree"

Committed revision 12.

Да, и не волнуйтесь, если забыли вовремя пометить версию—вы всегда можете сделать это сославшись на старую версию:

$ svn copy -r 11 file:///tmp/repos/test/trunk file:///tmp/repos/test/tags/0.6.32-prerelease -m "Forgot to tag at rev 11"

Committed revision 13.

Название

svn delete — Удаляет объект из рабочей копии или хранилища.

Формат

svn delete PATH...
svn delete URL...

Описание

Объекты определенные через PATH вносятся в план удаления следующей фиксацией изменений. При этом файлы под контролем версий удаляются из рабочей копии немедленно. Команда не удаляет версионированные или модифицированные объекты. Если вы этого необходимо—используйте параметр --force.

Объекты определенные через URL сразу же фиксируются как удаленные. При использовании в команде нескольких URL - удаление фиксируется атомарно.

Альтернативные имена

del, remove, rm

Изменяет

Рабочую копию в случае работы с файлами и хранилище при использовании URL

Требует доступа к хранилищу

Только в случае работы с URL

Параметры

--force
--force-log
--message (-m) TEXT
--file (-F) FILE
--quiet (-q)
--targets FILENAME
--username USER
--password PASS
--no-auth-cache
--non-interactive
--editor-cmd EDITOR
--encoding ENC
--config-dir DIR

Примеры

Использование svn для удаления файла из вашей рабочей копии на самом деле только планирует его на удаление. Только фиксируя изменения вы удаляете файл из хранилища.

$ svn delete myfile
D         myfile

$ svn commit -m "Deleted file 'myfile'."
Deleting       myfile
Transmitting file data .
Committed revision 14.

Так как удаление по URL отражается в хранилище сразу, вам необходимо задать комментарий:

$ svn delete -m "Deleting file 'yourfile'" file:///tmp/repos/test/yourfile

Committed revision 15.

Это пример принудительного удаления версионированного файла который был локально изменен:

$ svn delete over-there
svn: Attempting restricted operation for modified resource
svn: Use --force to override this restriction
svn: 'over-there' has local modifications

$ svn delete --force over-there
D         over-there

Название

svn diff — Display the differences between two paths.

Synopsis

diff [-r N[:M]] [TARGET[@REV]...]
diff [-r N[:M]] --old OLD-TGT[@OLDREV] [--new NEW-TGT[@NEWREV]] [PATH...]
diff OLD-URL[@OLDREV] NEW-URL[@NEWREV]

Description

Display the differences between two paths. The three different ways you can use svn diff are:

svn diff [-r N[:M]] [--old OLD-TGT] [--new NEW-TGT] [PATH...] displays the differences between OLD-TGT and NEW-TGT. If PATHs are given, they are treated as relative to OLD-TGT and NEW-TGT and the output is restricted to differences in only those paths. OLD-TGT and NEW-TGT may be working copy paths or URL[@REV]. OLD-TGT defaults to the current working directory and NEW-TGT defaults to OLD-TGT. N defaults to BASE or, if OLD-TGT is a URL, to HEAD. M defaults to the current working version or, if NEW-TGT is a URL, to HEAD. svn diff -r N sets the revision of OLD-TGT to N, svn diff -r N:M also sets the revision of NEW-TGT to M.

svn diff -r N:M URL is shorthand for svn diff -r N:M --old=URL --new=URL.

svn diff [-r N[:M]] URL1[@N] URL2[@M] is shorthand for svn diff [-r N[:M]] --old=URL1 --new=URL2.

If TARGET is a URL, then revs N and M can be given either via the --revision or by using «@» notation as described earlier.

If TARGET is a working copy path, then the --revision switch means:

--revision N:M

The server compares TARGET@N and TARGET@M.

--revision N

The client compares TARGET@N against working copy.

(no --revision)

The client compares base and working copies of TARGET.

If the alternate syntax is used, the server compares URL1 and URL2 at revisions N and M respectively. If either N or M are omitted, a value of HEAD is assumed.

By default, svn diff ignores the ancestry of files and merely compares the contents of the two files being compared. If you use --notice-ancestry, the ancestry of the paths in question will be taken into consideration when comparing revisions (that is, if you run svn diff on two files with identical contents but different ancestry you will see the entire contents of the file as having been removed and added again).

Alternate Names

di

Changes

Nothing

Accesses Repository

For obtaining differences against anything but BASE revision in your working copy

Switches

--revision (-r) REV
--old OLD-TARGET
--new NEW-TARGET
--extensions (-x) "ARGS"
--non-recursive (-N)
--diff-cmd CMD
--notice-ancestry
--username USER
--password PASS
--no-auth-cache
--non-interactive
--no-diff-deleted
--config-dir DIR

Examples

Compare BASE and your working copy (one of the most popular uses of svn diff):

$ svn diff COMMITTERS
Index: COMMITTERS
===================================================================
--- COMMITTERS  (revision 4404)
+++ COMMITTERS  (working copy)

See how your working copy's modifications compare against an older revision:

$ svn diff -r 3900 COMMITTERS
Index: COMMITTERS
===================================================================
--- COMMITTERS  (revision 3900)
+++ COMMITTERS  (working copy)

Compare revision 3000 to revision 3500 using «@» syntax:

$ svn diff http://svn.collab.net/repos/svn/trunk/COMMITTERS@3000 http://svn.collab.net/repos/svn/trunk/COMMITTERS@3500
Index: COMMITTERS
===================================================================
--- COMMITTERS  (revision 3000)
+++ COMMITTERS  (revision 3500)
…

Compare revision 3000 to revision 3500 using range notation (you only pass the one URL in this case):

$ svn diff -r 3000:3500 http://svn.collab.net/repos/svn/trunk/COMMITTERS
Index: COMMITTERS
===================================================================
--- COMMITTERS  (revision 3000)
+++ COMMITTERS  (revision 3500)

Compare revision 3000 to revision 3500 of all files in trunk using range notation:

$ svn diff -r 3000:3500 http://svn.collab.net/repos/svn/trunk
          

Compare revision 3000 to revision 3500 of only three files in trunk using range notation:

$ svn diff -r 3000:3500 --old http://svn.collab.net/repos/svn/trunk COMMITTERS README HACKING
          

If you have a working copy, you can obtain the differences without typing in the long URLs:

$ svn diff -r 3000:3500 COMMITTERS
Index: COMMITTERS
===================================================================
--- COMMITTERS  (revision 3000)
+++ COMMITTERS  (revision 3500)

Use --diff-cmd CMD -x to pass arguments directly to the external diff program

$ svn diff --diff-cmd /usr/bin/diff -x "-i -b" COMMITTERS
Index: COMMITTERS
===================================================================
0a1,2
> This is a test
>

Название

svn export — Export a clean directory tree.

Synopsis

svn export [-r REV] URL[@PEGREV] [PATH]
svn export [-r REV] PATH1[@PEGREV] [PATH2]

Description

The first form exports a clean directory tree from the repository specified by URL, at revision REV if it is given, otherwise at HEAD, into PATH. If PATH is omitted, the last component of the URL is used for the local directory name.

The second form exports a clean directory tree from the working copy specified by PATH1 into PATH2. All local changes will be preserved, but files not under version control will not be copied.

Alternate Names

None

Changes

Local disk

Accesses Repository

Only if exporting from a URL

Switches

--revision (-r) REV
--quiet (-q)
--force
--username USER
--password PASS
--no-auth-cache
--non-interactive
--non-recursive (-N)
--config-dir DIR
--native-eol EOL
--ignore-externals

Examples

Export from your working copy (doesn't print every file and directory):

$ svn export a-wc my-export
Export complete.

Export directly from the repository (prints every file and directory):

$ svn export file:///tmp/repos my-export
A  my-export/test
A  my-export/quiz
…
Exported revision 15.

When rolling operating-system-specific release packages, it can be useful to export a tree which uses a specific EOL character for line endings. The --native-eol option will do this, but it only affects files that have svn:eol-style = native properties attached to them. For example, to export a tree with all CRLF line endings (possibly for a Windows .zip file distribution):

$ svn export file://tmp/repos my-export --native-eol CRLF
A  my-export/test
A  my-export/quiz
…
Exported revision 15.

Название

svn help — Help!

Synopsis

svn help [SUBCOMMAND...]

Description

This is your best friend when you're using Subversion and this book isn't within reach!

Alternate Names

?, h

The options -?, -h and --help have the same effect as using the help subcommand.

Changes

Nothing

Accesses Repository

No

Switches

--version
--quiet (-q)
--config-dir DIR

Название

svn import — Commit an unversioned file or tree into the repository.

Synopsis

svn import [PATH] URL

Description

Recursively commit a copy of PATH to URL. If PATH is omitted «.» is assumed. Parent directories are created in the repository as necessary.

Alternate Names

None

Changes

Repository

Accesses Repository

Yes

Switches

--message (-m) TEXT
--file (-F) FILE
--quiet (-q)
--non-recursive (-N)
--username USER
--password PASS
--no-auth-cache
--non-interactive
--force-log
--editor-cmd EDITOR
--encoding ENC
--config-dir DIR
--auto-props
--no-auto-props
--ignore-externals

Examples

This imports the local directory myproj into the root of your repository:

$ svn import -m "New import" myproj http://svn.red-bean.com/repos/test
Adding         myproj/sample.txt
…
Transmitting file data .........
Committed revision 16.

This imports the local directory myproj into trunk/misc in your repository. The directory trunk/misc need not exist before you import into it—svn import will recursively create directories for you:

$ svn import -m "New import" myproj \
    http://svn.red-bean.com/repos/test/trunk/misc/myproj
Adding         myproj/sample.txt
…
Transmitting file data .........
Committed revision 19.

After importing data, note that the original tree is not under version control. To start working, you still need to svn checkout a fresh working copy of the tree.


Название

svn info — Display information about a local or remote item.

Synopsis

svn info [TARGET...]

Description

Print information about the working copy paths or URLs specified. The information shown for both may include:

  • Path

  • Name

  • URL

  • Repository Root

  • Repository UUID

  • Revision

  • Node Kind

  • Last Changed Author

  • Last Changed Revision

  • Last Changed Date

  • Lock Token

  • Lock Owner

  • Lock Created (date)

  • Lock Expires (date)

Additional kinds of information available only for working copy paths are:

  • Schedule

  • Copied From URL

  • Copied From Rev

  • Text Last Updated

  • Properties Last Updated

  • Checksum

  • Conflict Previous Base File

  • Conflict Previous Working File

  • Conflict Current Base File

  • Conflict Properties File

Alternate Names

None

Changes

Nothing

Accesses Repository

Only if operating on URLs

Switches

--revision (-r) REV
--recursive (-R)
--targets FILENAME
--incremental
--xml
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR

Examples

svn info will show you all the useful information that it has for items in your working copy. It will show information for files:

$ svn info foo.c
Path: foo.c
Name: foo.c
URL: http://svn.red-bean.com/repos/test/foo.c
Repository Root: http://svn.red-bean.com/repos/test
Repository UUID: 5e7d134a-54fb-0310-bd04-b611643e5c25
Revision: 4417
Node Kind: file
Schedule: normal
Last Changed Author: sally
Last Changed Rev: 20
Last Changed Date: 2003-01-13 16:43:13 -0600 (Mon, 13 Jan 2003)
Text Last Updated: 2003-01-16 21:18:16 -0600 (Thu, 16 Jan 2003)
Properties Last Updated: 2003-01-13 21:50:19 -0600 (Mon, 13 Jan 2003)
Checksum: d6aeb60b0662ccceb6bce4bac344cb66

It will also show information for directories:

$ svn info vendors
Path: vendors
URL: http://svn.red-bean.com/repos/test/vendors
Repository Root: http://svn.red-bean.com/repos/test
Repository UUID: 5e7d134a-54fb-0310-bd04-b611643e5c25
Revision: 19
Node Kind: directory
Schedule: normal
Last Changed Author: harry
Last Changed Rev: 19
Last Changed Date: 2003-01-16 23:21:19 -0600 (Thu, 16 Jan 2003)
Properties Last Updated: 2003-01-16 23:39:02 -0600 (Thu, 16 Jan 2003)

svn info also acts on URLs (also note that the file readme.doc in this example is locked, so lock information is also provided):

$ svn info http://svn.red-bean.com/repos/test/readme.doc
Path: readme.doc
Name: readme.doc
URL: http://svn.red-bean.com/repos/test/readme.doc
Repository Root: http://svn.red-bean.com/repos/test
Repository UUID: 5e7d134a-54fb-0310-bd04-b611643e5c25
Revision: 1
Node Kind: file
Schedule: normal
Last Changed Author: sally
Last Changed Rev: 42
Last Changed Date: 2003-01-14 23:21:19 -0600 (Tue, 14 Jan 2003)
Lock Token: opaquelocktoken:14011d4b-54fb-0310-8541-dbd16bd471b2
Lock Owner: harry
Lock Created: 2003-01-15 17:35:12 -0600 (Wed, 15 Jan 2003)
Lock Comment (1 line):
My test lock comment

Название

svn list — List directory entries in the repository.

Synopsis

svn list [TARGET[@REV]...]

Description

List each TARGET file and the contents of each TARGET directory as they exist in the repository. If TARGET is a working copy path, the corresponding repository URL will be used.

The default TARGET is «.», meaning the repository URL of the current working copy directory.

With --verbose, the following fields show the status of the item:

  • Revision number of the last commit

  • Author of the last commit

  • Size (in bytes)

  • Date and time of the last commit

With --xml, output is in XML format (with a header and an enclosing document element unless --incremental is also specified). All of the information is present; the --verbose option is not accepted.

Alternate Names

ls

Changes

Nothing

Accesses Repository

Yes

Switches

--revision (-r) REV
--verbose (-v)
--recursive (-R)
--incremental
--xml
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR

Examples

svn list is most useful if you want to see what files a repository has without downloading a working copy:

$ svn list http://svn.red-bean.com/repos/test/support
README.txt
INSTALL
examples/
…

You can pass the --verbose switch for additional information, rather like the UNIX command ls -l:

$ svn list --verbose file:///tmp/repos
     16 sally         28361 Jan 16 23:18 README.txt
     27 sally             0 Jan 18 15:27 INSTALL
     24 harry               Jan 18 11:27 examples/

For further details, see «svn list».


Название

svn lock — Lock working copy paths or URLs in the repository, so that no other user can commit changes to them.

Synopsis

svn lock TARGET...

Description

Lock each TARGET. If any TARGET is already locked by another user, print a warning and continue locking the rest of the TARGETs. Use --force to steal a lock from another user or working copy.

Alternate Names

None

Changes

Working Copy, Repository

Accesses Repository

Yes

Switches

--targets FILENAME
--message (-m) TEXT
--file (-F) FILE
--force-log
--encoding ENC
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR
--force

Examples

Lock two files in your working copy:


$ svn lock tree.jpg house.jpg
'tree.jpg' locked by user 'harry'.
'house.jpg' locked by user 'harry'.

Lock a file in your working copy that is currently locked by another user:

$ svn lock tree.jpg
svn: warning: Path '/tree.jpg is already locked by user 'harry in \
     filesystem '/svn/repos/db'

$ svn lock --force foo
'tree.jpg' locked by user 'sally'.

Lock a file without a working copy:

$ svn lock http://svn.red-bean.com/repos/test/tree.jpg
'tree.jpg' locked by user 'sally'.

For further details, see «Locking».


Название

svn log — Display commit log messages.

Synopsis

svn log [PATH]
svn log URL [PATH...]

Description

The default target is the path of your current directory. If no arguments are supplied, svn log shows the log messages for all files and directories inside of (and including) the current working directory of your working copy. You can refine the results by specifying a path, one or more revisions, or any combination of the two. The default revision range for a local path is BASE:1.

If you specify a URL alone, then it prints log messages for everything that the URL contains. If you add paths past the URL, only messages for those paths under that URL will be printed. The default revision range for a URL is HEAD:1.

With --verbose, svn log will also print all affected paths with each log message. With --quiet, svn log will not print the log message body itself (this is compatible with --verbose).

Each log message is printed just once, even if more than one of the affected paths for that revision were explicitly requested. Logs follow copy history by default. Use --stop-on-copy to disable this behavior, which can be useful for determining branch points.

Alternate Names

None

Changes

Nothing

Accesses Repository

Yes

Switches

--revision (-r) REV
--quiet (-q)
--verbose (-v)
--targets FILENAME
--stop-on-copy
--incremental
--limit NUM
--xml
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR

Examples

You can see the log messages for all the paths that changed in your working copy by running svn log from the top:

$ svn log
------------------------------------------------------------------------
r20 | harry | 2003-01-17 22:56:19 -0600 (Fri, 17 Jan 2003) | 1 line

Tweak.
------------------------------------------------------------------------
r17 | sally | 2003-01-16 23:21:19 -0600 (Thu, 16 Jan 2003) | 2 lines
…

Examine all log messages for a particular file in your working copy:

$ svn log foo.c
------------------------------------------------------------------------
r32 | sally | 2003-01-13 00:43:13 -0600 (Mon, 13 Jan 2003) | 1 line

Added defines.
------------------------------------------------------------------------
r28 | sally | 2003-01-07 21:48:33 -0600 (Tue, 07 Jan 2003) | 3 lines
…

If you don't have a working copy handy, you can log a URL:

$ svn log http://svn.red-bean.com/repos/test/foo.c
------------------------------------------------------------------------
r32 | sally | 2003-01-13 00:43:13 -0600 (Mon, 13 Jan 2003) | 1 line

Added defines.
------------------------------------------------------------------------
r28 | sally | 2003-01-07 21:48:33 -0600 (Tue, 07 Jan 2003) | 3 lines
…

If you want several distinct paths underneath the same URL, you can use the URL [PATH...] syntax.

$ svn log http://svn.red-bean.com/repos/test/ foo.c bar.c
------------------------------------------------------------------------
r32 | sally | 2003-01-13 00:43:13 -0600 (Mon, 13 Jan 2003) | 1 line

Added defines.
------------------------------------------------------------------------
r31 | harry | 2003-01-10 12:25:08 -0600 (Fri, 10 Jan 2003) | 1 line

Added new file bar.c
------------------------------------------------------------------------
r28 | sally | 2003-01-07 21:48:33 -0600 (Tue, 07 Jan 2003) | 3 lines
…

When you're concatenating the results of multiple calls to the log command, you may want to use the --incremental switch. svn log normally prints out a dashed line at the beginning of a log message, after each subsequent log message, and following the final log message. If you ran svn log on a range of two revisions, you would get this:

$ svn log -r 14:15
------------------------------------------------------------------------
r14 | …

------------------------------------------------------------------------
r15 | …

------------------------------------------------------------------------

However, if you wanted to gather 2 non-sequential log messages into a file, you might do something like this:

$ svn log -r 14 > mylog
$ svn log -r 19 >> mylog
$ svn log -r 27 >> mylog
$ cat mylog
------------------------------------------------------------------------
r14 | …

------------------------------------------------------------------------
------------------------------------------------------------------------
r19 | …

------------------------------------------------------------------------
------------------------------------------------------------------------
r27 | …

------------------------------------------------------------------------

You can avoid the clutter of the double dashed lines in your output by using the incremental switch:

$ svn log --incremental -r 14 > mylog
$ svn log --incremental -r 19 >> mylog
$ svn log --incremental -r 27 >> mylog
$ cat mylog
------------------------------------------------------------------------
r14 | …

------------------------------------------------------------------------
r19 | …

------------------------------------------------------------------------
r27 | …

The --incremental switch provides similar output control when using the --xml switch.

[Подсказка]Подсказка

If you run svn log on a specific path and provide a specific revision and get no output at all

$ svn log -r 20 http://svn.red-bean.com/untouched.txt
------------------------------------------------------------------------

That just means that the path was not modified in that revision. If you log from the top of the repository, or know the file that changed in that revision, you can specify it explicitly:

$ svn log -r 20 touched.txt
------------------------------------------------------------------------
r20 | sally | 2003-01-17 22:56:19 -0600 (Fri, 17 Jan 2003) | 1 line

Made a change.
------------------------------------------------------------------------

Название

svn merge — Apply the differences between two sources to a working copy path.

Synopsis

svn merge sourceURL1[@N] sourceURL2[@M] [WCPATH]
svn merge sourceWCPATH1@N sourceWCPATH2@M [WCPATH]
svn merge -r N:M SOURCE[@REV] [WCPATH]

Description

In the first and second forms, the source paths (URLs in the first form, working copy paths in the second) are specified at revisions N and M. These are the two sources to be compared. The revisions default to HEAD if omitted.

In the third form, SOURCE can be a URL or working copy item, in which case the corresponding URL is used. This URL, at revisions N and M, defines the two sources to be compared.

WCPATH is the working copy path that will receive the changes. If WCPATH is omitted, a default value of «.» is assumed, unless the sources have identical basenames that match a file within «.»: in which case, the differences will be applied to that file.

Unlike svn diff, the merge command takes the ancestry of a file into consideration when performing a merge operation. This is very important when you're merging changes from one branch into another and you've renamed a file on one branch but not the other.

Alternate Names

None

Changes

Working copy

Accesses Repository

Only if working with URLs

Switches

--revision (-r) REV
--non-recursive (-N)
--quiet (-q)
--force
--dry-run
--diff3-cmd CMD
--ignore-ancestry
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR

Examples

Merge a branch back into the trunk (assuming that you have a working copy of the trunk, and that the branch was created in revision 250):

$ svn merge -r 250:HEAD http://svn.red-bean.com/repos/branches/my-branch
U  myproj/tiny.txt
U  myproj/thhgttg.txt
U  myproj/win.txt
U  myproj/flo.txt

If you branched at revision 23, and you want to merge changes on trunk into your branch, you could do this from inside the working copy of your branch:

$ svn merge -r 23:30 file:///tmp/repos/trunk/vendors
U  myproj/thhgttg.txt
…

To merge changes to a single file:

$ cd myproj
$ svn merge -r 30:31 thhgttg.txt
U  thhgttg.txt

Название

svn mkdir — Create a new directory under version control.

Synopsis

svn mkdir PATH...
svn mkdir URL...

Description

Create a directory with a name given by the final component of the PATH or URL. A directory specified by a working copy PATH is scheduled for addition in the working copy. A directory specified by a URL is created in the repository via an immediate commit. Multiple directory URLs are committed atomically. In both cases all the intermediate directories must already exist.

Alternate Names

None

Changes

Working copy, repository if operating on a URL

Accesses Repository

Only if operating on a URL

Switches

--message (-m) TEXT
--file (-F) FILE
--quiet (-q)
--username USER
--password PASS
--no-auth-cache
--non-interactive
--editor-cmd EDITOR
--encoding ENC
--force-log
--config-dir DIR

Examples

Create a directory in your working copy:

$ svn mkdir newdir
A         newdir

Create one in the repository (instant commit, so a log message is required):

$ svn mkdir -m "Making a new dir." http://svn.red-bean.com/repos/newdir

Committed revision 26.

Название

svn move — Move a file or directory.

Synopsis

svn move SRC DST

Description

This command moves a file or directory in your working copy or in the repository.

[Подсказка]Подсказка

This command is equivalent to an svn copy followed by svn delete.

[Замечание]Замечание

Subversion does not support moving between working copies and URLs. In addition, you can only move files within a single repository—Subversion does not support cross-repository moving.

WC -> WC

Move and schedule a file or directory for addition (with history).

URL -> URL

Complete server-side rename.

Alternate Names

mv, rename, ren

Changes

Working copy, repository if operating on a URL

Accesses Repository

Only if operating on a URL

Switches

--message (-m) TEXT
--file (-F) FILE
--revision (-r) REV
--quiet (-q)
--force
--username USER
--password PASS
--no-auth-cache
--non-interactive
--editor-cmd EDITOR
--encoding ENC
--force-log
--config-dir DIR

Examples

Move a file in your working copy:

$ svn move foo.c bar.c
A         bar.c
D         foo.c

Move a file in the repository (an immediate commit, so it requires a commit message):

$ svn move -m "Move a file" http://svn.red-bean.com/repos/foo.c \
                            http://svn.red-bean.com/repos/bar.c

Committed revision 27.

Название

svn propdel — Remove a property from an item.

Synopsis

svn propdel PROPNAME [PATH...]
svn propdel PROPNAME --revprop -r REV [URL]

Description

This removes properties from files, directories, or revisions. The first form removes versioned properties in your working copy, while the second removes unversioned remote properties on a repository revision.

Alternate Names

pdel, pd

Changes

Working copy, repository only if operating on a URL

Accesses Repository

Only if operating on a URL

Switches

--quiet (-q)
--recursive (-R)
--revision (-r) REV
--revprop
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR

Examples

Delete a property from a file in your working copy

$ svn propdel svn:mime-type  some-script
property 'svn:mime-type' deleted from 'some-script'.

Delete a revision property:

$ svn propdel --revprop -r 26 release-date
property 'release-date' deleted from repository revision '26'

Название

svn propedit — Edit the property of one or more items under version control.

Synopsis

svn propedit PROPNAME PATH...
svn propedit PROPNAME --revprop -r REV [URL]

Description

Edit one or more properties using your favorite editor. The first form edits versioned properties in your working copy, while the second edits unversioned remote properties on a repository revision.

Alternate Names

pedit, pe

Changes

Working copy, repository only if operating on a URL

Accesses Repository

Only if operating on a URL

Switches

--revision (-r) REV
--revprop
--username USER
--password PASS
--no-auth-cache
--non-interactive
--encoding ENC
--editor-cmd EDITOR
--config-dir DIR

Examples

svn propedit makes it easy to modify properties that have multiple values:

$ svn propedit svn:keywords  foo.c
    <svn will launch your favorite editor here, with a buffer open
    containing the current contents of the svn:keywords property.  You
    can add multiple values to a property easily here by entering one
    value per line.>
Set new value for property 'svn:keywords' on 'foo.c'

Название

svn propget — Print the value of a property.

Synopsis

svn propget PROPNAME [TARGET[@REV]...]
svn propget PROPNAME --revprop -r REV [URL]

Description

Print the value of a property on files, directories, or revisions. The first form prints the versioned property of an item or items in your working copy, while the second prints unversioned remote property on a repository revision. See «Свойства» for more information on properties.

Alternate Names

pget, pg

Changes

Working copy, repository only if operating on a URL

Accesses Repository

Only if operating on a URL

Switches

--recursive (-R)
--revision (-r) REV
--revprop
--strict
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR

Examples

Examine a property of a file in your working copy:

$ svn propget svn:keywords foo.c
Author
Date
Rev

The same goes for a revision property:

$ svn propget svn:log --revprop -r 20
Began journal.

Название

svn proplist — List all properties.

Synopsis

svn proplist [TARGET[@REV]...]
svn proplist --revprop -r REV [URL]

Description

List all properties on files, directories, or revisions. The first form lists versioned properties in your working copy, while the second lists unversioned remote properties on a repository revision.

Alternate Names

plist, pl

Changes

Working copy, repository only if operating on a URL

Accesses Repository

Only if operating on a URL

Switches

--verbose (-v)
--recursive (-R)
--revision (-r) REV
--quiet (-q)
--revprop
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR

Examples

You can use proplist to see the properties on an item in your working copy:

$ svn proplist foo.c
Properties on 'foo.c':
  svn:mime-type
  svn:keywords
  owner

But with the --verbose flag, svn proplist is extremely handy as it also shows you the values for the properties:

$ svn proplist --verbose foo.c
Properties on 'foo.c':
  svn:mime-type : text/plain
  svn:keywords : Author Date Rev
  owner : sally

Название

svn propset — Set PROPNAME to PROPVAL on files, directories, or revisions.

Synopsis

svn propset PROPNAME [PROPVAL | -F VALFILE] PATH...
svn propset PROPNAME --revprop -r REV [PROPVAL | -F VALFILE] [URL]

Description

Set PROPNAME to PROPVAL on files, directories, or revisions. The first example creates a versioned, local property change in the working copy, and the second creates an unversioned, remote property change on a repository revision.

[Подсказка]Подсказка

Subversion has a number of «special» properties that affect its behavior. See «Свойства Subversion» for more on these properties.

Alternate Names

pset, ps

Changes

Working copy, repository only if operating on a URL

Accesses Repository

Only if operating on a URL

Switches

--file (-F) FILE
--quiet (-q)
--revision (-r) REV
--targets FILENAME
--recursive (-R)
--revprop
--username USER
--password PASS
--no-auth-cache
--non-interactive
--encoding ENC
--force
--config-dir DIR

Examples

Set the mimetype on a file:

$ svn propset svn:mime-type image/jpeg foo.jpg
property 'svn:mime-type' set on 'foo.jpg'

On a UNIX system, if you want a file to have the executable permission set:

$ svn propset svn:executable ON somescript
property 'svn:executable' set on 'somescript'

Perhaps you have an internal policy to set certain properties for the benefit of your coworkers:

$ svn propset owner sally foo.c
property 'owner' set on 'foo.c'

If you made a mistake in a log message for a particular revision and want to change it, use --revprop and set svn:log to the new log message:

$ svn propset --revprop -r 25 svn:log "Journaled about trip to New York."
property 'svn:log' set on repository revision '25'

Or, if you don't have a working copy, you can provide a URL.

$ svn propset --revprop -r 26 svn:log "Document nap." http://svn.red-bean.com/repos
property 'svn:log' set on repository revision '25'

Lastly, you can tell propset to take its input from a file. You could even use this to set the contents of a property to something binary:

$ svn propset owner-pic -F sally.jpg moo.c
property 'owner-pic' set on 'moo.c'
[Замечание]Замечание

By default, you cannot modify revision properties in a Subversion repository. Your repository administrator must explicitly enable revision property modifications by creating a hook named pre-revprop-change. See «Hook Scripts» for more information on hook scripts.


Название

svn resolved — Remove «conflicted» state on working copy files or directories.

Synopsis

svn resolved PATH...

Description

Remove «conflicted» state on working copy files or directories. This routine does not semantically resolve conflict markers; it merely removes conflict-related artifact files and allows PATH to be committed again; that is, it tells Subversion that the conflicts have been «resolved». See «Разрешение конфликтов (при слиянии с чужими изменениями)» for an in-depth look at resolving conflicts.

Alternate Names

None

Changes

Working copy

Accesses Repository

No

Switches

--targets FILENAME
--recursive (-R)
--quiet (-q)
--config-dir DIR

Examples

If you get a conflict on an update, your working copy will sprout three new files:

$ svn update
C  foo.c
Updated to revision 31.
$ ls
foo.c
foo.c.mine
foo.c.r30
foo.c.r31

Once you've resolved the conflict and foo.c is ready to be committed, run svn resolved to let your working copy know you've taken care of everything.

[Внимание]Внимание

You can just remove the conflict files and commit, but svn resolved fixes up some bookkeeping data in the working copy administrative area in addition to removing the conflict files, so we recommend that you use this command.


Название

svn revert — Undo all local edits.

Synopsis

svn revert PATH...

Description

Reverts any local changes to a file or directory and resolves any conflicted states. svn revert will not only revert the contents of an item in your working copy, but also any property changes. Finally, you can use it to undo any scheduling operations that you may have done (e.g. files scheduled for addition or deletion can be «unscheduled»).

Alternate Names

None

Changes

Working copy

Accesses Repository

No

Switches

--targets FILENAME
--recursive (-R)
--quiet (-q)
--config-dir DIR

Examples

Discard changes to a file:

$ svn revert foo.c
Reverted foo.c

If you want to revert a whole directory of files, use the --recursive flag:

$ svn revert --recursive .
Reverted newdir/afile
Reverted foo.c
Reverted bar.txt

Lastly, you can undo any scheduling operations:

$ svn add mistake.txt whoops
A         mistake.txt
A         whoops
A         whoops/oopsie.c

$ svn revert mistake.txt whoops
Reverted mistake.txt
Reverted whoops

$ svn status
?      mistake.txt
?      whoops
[Замечание]Замечание

If you provide no targets to svn revert, it will do nothing—to protect you from accidentally losing changes in your working copy, svn revert requires you to provide at least one target.


Название

svn status — Print the status of working copy files and directories.

Synopsis

svn status [PATH...]

Description

Print the status of working copy files and directories. With no arguments, it prints only locally modified items (no repository access). With --show-updates, add working revision and server out-of-date information. With --verbose, print full revision information on every item.

The first six columns in the output are each one character wide, and each column gives you information about different aspects of each working copy item.

The first column indicates that an item was added, deleted, or otherwise changed.

' '

No modifications.

'A'

Item is scheduled for Addition.

'D'

Item is scheduled for Deletion.

'M'

Item has been modified.

'R'

Item has been replaced in your working copy. This means the file was scheduled for deletion, and then a new file with the same name was scheduled for addition in its place.

'C'

The contents (as opposed to the properties) of the item conflict with updates received from the repository.

'X'

Item is related to an externals definition.

'I'

Item is being ignored (e.g. with the svn:ignore property).

'?'

Item is not under version control.

'!'

Item is missing (e.g. you moved or deleted it without using svn). This also indicates that a directory is incomplete (a checkout or update was interrupted).

'~'

Item is versioned as one kind of object (file, directory, link), but has been replaced by different kind of object.

The second column tells the status of a file's or directory's properties.

' '

No modifications.

'M'

Properties for this item have been modified.

'C'

Properties for this item are in conflict with property updates received from the repository.

The third column is populated only if the working copy directory is locked. (See «svn cleanup».)

' '

Item is not locked.

'L'

Item is locked.

The fourth column is populated only if the item is scheduled for addition-with-history.

' '

No history scheduled with commit.

'+'

History scheduled with commit.

The fifth column is populated only if the item is switched relative to its parent (see «Переключение рабочей копии»).

' '

Item is a child of its parent directory.

'S'

Item is switched.

The sixth column is populated with lock information.

' '

When --show-updates is used, the file is not locked. If --show-updates is not used, this merely means that the file is not locked in this working copy.

K

File is locked in this working copy.

O

File is locked either by another user or in another working copy. This only appears when --show-updates is used.

T

File was locked in this working copy, but the lock has been «stolen»and is invalid. The file is currently locked in the repository. This only appears when --show-updates is used.

B

File was locked in this working copy, but the lock has been «broken»and is invalid. The file is no longer locked This only appears when --show-updates is used.

The out-of-date information appears in the seventh column (only if you pass the --show-updates switch).

' '

The item in your working copy is up-to-date.

'*'

A newer revision of the item exists on the server.

The remaining fields are variable width and delimited by spaces. The working revision is the next field if the --show-updates or --verbose switches are passed.

If the --verbose switch is passed, the last committed revision and last committed author are displayed next.

The working copy path is always the final field, so it can include spaces.

Alternate Names

stat, st

Changes

Nothing

Accesses Repository

Only if using --show-updates

Switches

--show-updates (-u)
--verbose (-v)
--non-recursive (-N)
--quiet (-q)
--no-ignore
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR
--ignore-externals

Examples

This is the easiest way to find out what changes you have made to your working copy:

$ svn status wc
 M     wc/bar.c
A  +   wc/qax.c

If you want to find out what files in your working copy are out-of-date, pass the --show-updates switch (this will not make any changes to your working copy). Here you can see that wc/foo.c has changed in the repository since we last updated our working copy:

$ svn status --show-updates wc
 M           965    wc/bar.c
       *     965    wc/foo.c
A  +         965    wc/qax.c
Status against revision:    981
[Замечание]Замечание

--show-updates only places an asterisk next to items that are out of date (that is, items that will be updated from the repository if you run svn update). --show-updates does not cause the status listing to reflect the repository's version of the item.

And finally, the most information you can get out of the status subcommand:

$ svn status --show-updates --verbose wc
 M           965       938 sally        wc/bar.c
       *     965       922 harry        wc/foo.c
A  +         965       687 harry        wc/qax.c
             965       687 harry        wc/zig.c
Head revision:   981

For many more examples of svn status, see «svn status».


Название

svn switch — Update working copy to a different URL.

Synopsis

svn switch URL [PATH]
switch --relocate FROM TO [PATH...]

Description

This subcommand updates your working copy to mirror a new URL—usually a URL which shares a common ancestor with your working copy, although not necessarily. This is the Subversion way to move a working copy to a new branch. See «Переключение рабочей копии» for an in-depth look at switching.

Alternate Names

sw

Changes

Working copy

Accesses Repository

Yes

Switches

--revision (-r) REV
--non-recursive (-N)
--quiet (-q)
--diff3-cmd CMD
--relocate FROM TO
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR

Examples

If you're currently inside the directory vendors which was branched to vendors-with-fix and you'd like to switch your working copy to that branch:

$ svn switch http://svn.red-bean.com/repos/branches/vendors-with-fix .
U  myproj/foo.txt
U  myproj/bar.txt
U  myproj/baz.c
U  myproj/qux.c
Updated to revision 31.

And to switch back, just provide the URL to the location in the repository from which you originally checked out your working copy:

$ svn switch http://svn.red-bean.com/repos/trunk/vendors .
U  myproj/foo.txt
U  myproj/bar.txt
U  myproj/baz.c
U  myproj/qux.c
Updated to revision 31.
[Подсказка]Подсказка

You can just switch part of your working copy to a branch if you don't want to switch your entire working copy.

Sometimes an administrator might change the «base location» of your repository—in other words, the contents of the repository doesn't change, but the main URL used to reach the root of the repository does. For example, the hostname may change, the URL scheme, or any part of the URL which leads to the repository itself. Rather than checkout a new working copy, you can have the svn switch command «rewrite» the beginnings of all the URLs in your working copy. Use the --relocate option to do the substitution. No file contents are changed, nor is the repository contacted. It's similar to running a Perl script over your working copy .svn/ directories which runs s/OldRoot/NewRoot/.

$ svn checkout file:///tmp/repos test
A  test/a
A  test/b
…

$ mv repos newlocation
$ cd test/

$ svn update
svn: Unable to open an ra_local session to URL
svn: Unable to open repository 'file:///tmp/repos'

$ svn switch --relocate file:///tmp/repos file:///tmp/newlocation .
$ svn update
At revision 3.
[Внимание]Внимание

Be careful when using the --relocate option. If you mistype the argument, you might end up creating nonsensical URLs within your working copy that render the whole workspace unusable and tricky to fix. It's also important to understand exactly when one should or shouldn't use --relocate. Here's the rule of thumb:

  • If the working copy needs to reflect a new directory within the repository, then use just svn switch.

  • If the working copy still reflects the same repository directory, but the location of the repository itself has changed, then use svn switch --relocate.


Название

svn unlock — Unlock working copy paths or URLs.

Synopsis

svn unlock TARGET...

Description

Unlock each TARGET. If any TARGET is either locked by another user or no valid lock token exists in the working copy, print a warning and continue unlocking the rest of the TARGETs. Use --force to break a lock belonging to another user or working copy.

Alternate Names

None

Changes

Working Copy, Repository

Accesses Repository

Yes

Switches

--targets FILENAME
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR
--force

Examples

Unlock two files in your working copy:


$ svn unlock tree.jpg house.jpg
'tree.jpg' unlocked.
'house.jpg' unlocked.

Unlock a file in your working copy that is currently locked by another user:

$ svn unlock tree.jpg
svn: 'tree.jpg' is not locked in this working copy
$ svn unlock --force tree.jpg
'tree.jpg' unlocked.

Unlock a file without a working copy:

$ svn unlock http://svn.red-bean.com/repos/test/tree.jpg
'tree.jpg unlocked.

For further details, see «Locking».


Название

svn update — Update your working copy.

Synopsis

svn update [PATH...]

Description

svn update brings changes from the repository into your working copy. If no revision given, it brings your working copy up-to-date with the HEAD revision. Otherwise, it synchronizes the working copy to the revision given by the --revision switch. As part of the synchronization, svn update also removes any stale locks (see «svn cleanup») found in the working copy.

For each updated item a line will start with a character reporting the action taken. These characters have the following meaning:

A

Added

D

Deleted

U

Updated

C

Conflict

G

Merged

A character in the first column signifies an update to the actual file, while updates to the file's properties are shown in the second column.

Alternate Names

up

Changes

Working copy

Accesses Repository

Yes

Switches

--revision (-r) REV
--non-recursive (-N)
--quiet (-q)
--diff3-cmd CMD
--username USER
--password PASS
--no-auth-cache
--non-interactive
--config-dir DIR
--ignore-externals

Examples

Pick up repository changes that have happened since your last update:

$ svn update
A  newdir/toggle.c
A  newdir/disclose.c
A  newdir/launch.c
D  newdir/README
Updated to revision 32.

You can also update your working copy to an older revision (Subversion doesn't have the concept of «sticky» files like CVS does; see Приложение B, Subversion для пользователей CVS):

$ svn update -r30
A  newdir/README
D  newdir/toggle.c
D  newdir/disclose.c
D  newdir/launch.c
U  foo.c
Updated to revision 30.
[Подсказка]Подсказка

If you want to examine an older revision of a single file, you may want to use svn cat.

svnadmin

svnadmin is the administrative tool for monitoring and repairing your Subversion repository. For detailed information, see «svnadmin».

Since svnadmin works via direct repository access (and thus can only be used on the machine that holds the repository), it refers to the repository with a path, not a URL.

svnadmin Switches

--bdb-log-keep

(Berkeley DB specific) Disable automatic log removal of database log files.

--bdb-txn-nosync

(Berkeley DB specific) Disables fsync when committing database transactions.

--bypass-hooks

Bypass the repository hook system.

--clean-logs

Removes unused Berkeley DB logs.

--force-uuid

By default, when loading data into repository that already contains revisions, svnadmin will ignore the UUID from the dump stream. This switch will cause the repository's UUID to be set to the UUID from the stream.

--ignore-uuid

By default, when loading an empty repository, svnadmin will use the UUID from the dump stream. This switch will cause that UUID to be ignored.

--incremental

Dump a revision only as a diff against the previous revision, instead of the usual fulltext.

--parent-dir DIR

When loading a dump file, root paths at DIR instead of /.

--revision (-r) ARG

Specify a particular revision to operate on.

--quiet

Do not show normal progress—show only errors.

--use-post-commit-hook

When loading a dump file, run the repository's post-commit hook after finalizing each newly loaded revision.

--use-pre-commit-hook

When loading a dump file, run the repository's pre-commit hook before finalizing each newly loaded revision. If the hook fails, abort the commit and terminate the load process.

svnadmin Subcommands

Название

svnadmin create — Create a new, empty repository.

Synopsis

svnadmin create REPOS_PATH

Description

Create a new, empty repository at the path provided. If the provided directory does not exist, it will be created for you.[57] As of Subversion 1.2, svnadmin creates new repositories with the fsfs filesystem backend by default.

Switches

--bdb-txn-nosync
--bdb-log-keep
--config-dir DIR
--fs-type TYPE

Examples

Creating a new repository is just this easy:

$ svnadmin create /usr/local/svn/repos

In Subversion 1.0, a Berkeley DB repository is always created. In Subversion 1.1, a Berkeley DB repository is the default repository type, but an FSFS repository can be created using the --fs-type option:

$ svnadmin create /usr/local/svn/repos --fs-type fsfs



[57] Remember, svnadmin works only with local paths, not URLs.


Название

svnadmin deltify — Deltify changed paths in a revision range.

Synopsis

svnadmin deltify [-r LOWER[:UPPER]] REPOS_PATH

Description

svnadmin deltify only exists in current versions of Subversion due to historical reasons. This command is deprecated and no longer needed.

It dates from a time when Subversion offered administrators greater control over compression strategies in the repository. This turned out to be a lot of complexity for very little gain, and this «feature» was deprecated.

Switches

--revision (-r) REV
--quiet (-q)

Название

svnadmin dump — Dump the contents of filesystem to stdout.

Synopsis

svnadmin dump REPOS_PATH [-r LOWER[:UPPER]] [--incremental]

Description

Dump the contents of filesystem to stdout in a «dumpfile» portable format, sending feedback to stderr. Dump revisions LOWER rev through UPPER rev. If no revisions are given, dump all revision trees. If only LOWER is given, dump that one revision tree. See «Migrating a Repository» for a practical use.

By default, the Subversion dumpfile stream contains a single revision (the first revision in the requested revision range) in which every file and directory in the repository in that revision is presented as if that whole tree was added at once, followed by other revisions (the remainder of the revisions in the requested range) which contain only the files and directories which were modified in those revisions. For a modified file, the complete fulltext representation of its contents, as well as all of its properties, are presented in the dumpfile; for a directory, all of its properties are presented.

There are a pair of useful options which modify the dumpfile generator's behavior. The first is the --incremental option, which simply causes that first revision in the dumpfile stream to contain only the files and directories modified in that revision, instead of being presented as the addition of a new tree, and in exactly the same way that every other revision in the dumpfile is presented. This is useful for generating a dumpfile that is to be loaded into another repository which already has the files and directories that exist in the original repository.

The second useful option is --deltas. This switch causes svnadmin dump to, instead of emitting fulltext representations of file contents and property lists, emit only deltas of those items against their previous versions. This reduces (in some cases, drastically) the size of the dumpfile that svnadmin dump creates. There are, however, disadvantages to using this option—deltified dumpfiles are more CPU intensive to create, cannot be operated on by svndumpfilter, and tend not to compress as well as their non-deltified counterparts when using third-party tools like gzip and bzip2.

Switches

--revision (-r) REV
--incremental
--quiet (-q)
--deltas

Examples

Dump your whole repository:

$ svnadmin dump /usr/local/svn/repos
SVN-fs-dump-format-version: 1
Revision-number: 0
* Dumped revision 0.
Prop-content-length: 56
Content-length: 56
…

Incrementally dump a single transaction from your repository:

$ svnadmin dump /usr/local/svn/repos -r 21 --incremental
* Dumped revision 21.
SVN-fs-dump-format-version: 1
Revision-number: 21
Prop-content-length: 101
Content-length: 101
…

Название

svnadmin help — Help!

Synopsis

svnadmin help [SUBCOMMAND...]

Description

This subcommand is useful when you're trapped on a desert island with neither a net connection nor a copy of this book.

Alternate Names

?, h


Название

svnadmin hotcopy — Make a hot copy of a repository.

Synopsis

svnadmin hotcopy REPOS_PATH NEW_REPOS_PATH

Description

This subcommand makes a full «hot» backup of your repository, including all hooks, configuration files, and, of course, database files. If you pass the --clean-logs switch, svnadmin will perform a hotcopy of your repository, and then remove unused Berkeley DB logs from the original repository. You can run this command at any time and make a safe copy of the repository, regardless of whether other processes are using the repository.

Switches

--clean-logs

Название

svnadmin list-dblogs — Ask Berkeley DB which log files exist for a given Subversion repository (applies only to repositories using the bdb backend).

Synopsis

svnadmin list-dblogs REPOS_PATH

Description

Berkeley DB creates logs of all changes to the repository, which allow it to recover in the face of catastrophe. Unless you enable DB_LOG_AUTOREMOVE, the log files accumulate, although most are no longer used and can be deleted to reclaim disk space. See «Managing Disk Space» for more information.


Название

svnadmin list-unused-dblogs — Ask Berkeley DB which log files can be safely deleted (applies only to repositories using the bdb backend).

Synopsis

svnadmin list-unused-dblogs REPOS_PATH

Description

Berkeley DB creates logs of all changes to the repository, which allow it to recover in the face of catastrophe. Unless you enable DB_LOG_AUTOREMOVE, the log files accumulate, although most are no longer used and can be deleted to reclaim disk space. See «Managing Disk Space» for more information.

Examples

Remove all unused log files from a repository:

$ svnadmin list-unused-dblogs /path/to/repos
/path/to/repos/log.0000000031
/path/to/repos/log.0000000032
/path/to/repos/log.0000000033

$ svnadmin list-unused-dblogs /path/to/repos | xargs rm
## disk space reclaimed!

Название

svnadmin load — Read a «dumpfile»-formatted stream from stdin.

Synopsis

svnadmin load REPOS_PATH

Description

Read a «dumpfile»-formatted stream from stdin, committing new revisions into the repository's filesystem. Send progress feedback to stdout.

Switches

--quiet (-q)
--ignore-uuid
--force-uuid
--use-pre-commit-hook
--use-post-commit-hook
--parent-dir

Example

This shows the beginning of loading a repository from a backup file (made, of course, with svnadmin dump):

$ svnadmin load /usr/local/svn/restored < repos-backup
<<< Started new txn, based on original revision 1
     * adding path : test ... done.
     * adding path : test/a ... done.
…

Or if you want to load into a subdirectory:

$ svnadmin load --parent-dir new/subdir/for/project /usr/local/svn/restored < repos-backup
<<< Started new txn, based on original revision 1
     * adding path : test ... done.
     * adding path : test/a ... done.
…

Название

svnadmin lslocks — Print descriptions of all locks.

Synopsis

svnadmin lslocks REPOS_PATH

Description

Print descriptions of all locks in a repository.

Switches

None

Example

This lists the one locked file in the repository at /svn/repos

$ svnadmin lslocks /svn/repos
Path: /tree.jpg
UUID Token: opaquelocktoken:ab00ddf0-6afb-0310-9cd0-dda813329753
Owner: harry
Created: 2005-07-08 17:27:36 -0500 (Fri, 08 Jul 2005)
Expires: 
Comment (1 line):
Rework the uppermost branches on the bald cypress in the foreground.

Название

svnadmin lstxns — Print the names of all uncommitted transactions.

Synopsis

svnadmin lstxns REPOS_PATH

Description

Print the names of all uncommitted transactions. See «Repository Cleanup» for information on how uncommitted transactions are created and what you should do with them.

Examples

List all outstanding transactions in a repository.

$ svnadmin lstxns /usr/local/svn/repos/
1w
1x

Название

svnadmin recover — Bring a repository database back into a consistent state (applies only to repositories using the bdb backend). In addition, if repos/conf/passwd does not exist, it will create a default password file .

Synopsis

svnadmin recover REPOS_PATH

Description

Run this command if you get an error indicating that your repository needs to be recovered.

Switches

--wait

Examples

Recover a hung repository:

$ svnadmin recover /usr/local/svn/repos/
Repository lock acquired.
Please wait; recovering the repository may take some time...

Recovery completed.
The latest repos revision is 34.

Recovering the database requires an exclusive lock on the repository. (This is a «database lock»; see Three meanings of «lock».) If another process is accessing the repository, then svnadmin recover will error:

$ svnadmin recover /usr/local/svn/repos
svn: Failed to get exclusive repository access; perhaps another process
such as httpd, svnserve or svn has it open?

$

The --wait option, however, will cause svnadmin recover to wait indefinitely for other processes to disconnect:

$ svnadmin recover /usr/local/svn/repos --wait
Waiting on repository lock; perhaps another process has it open?

### time goes by…

Repository lock acquired.
Please wait; recovering the repository may take some time...

Recovery completed.
The latest repos revision is 34.

Название

svnadmin rmlocks — Unconditionally remove one or more locks from a repository.

Synopsis

svnadmin rmlocks REPOS_PATH LOCKED_PATH...

Description

Remove lock from each LOCKED_PATH.

Switches

None

Example

This deletes the locks on tree.jpg and house.jpg in the repository at /svn/repos

$ svnadmin rmlocks /svn/repos tree.jpg house.jpg
Removed lock on '/tree.jpg.
Removed lock on '/house.jpg.

Название

svnadmin rmtxns — Delete transactions from a repository.

Synopsis

svnadmin rmtxns REPOS_PATH TXN_NAME...

Description

Delete outstanding transactions from a repository. This is covered in detail in «Repository Cleanup».

Switches

--quiet (-q)

Examples

Remove named transactions:

$ svnadmin rmtxns /usr/local/svn/repos/ 1w 1x

Fortunately, the output of lstxns works great as the input for rmtxns:

$ svnadmin rmtxns /usr/local/svn/repos/  `svnadmin lstxns /usr/local/svn/repos/`

Which will remove all uncommitted transactions from your repository.


Название

svnadmin setlog — Set the log-message on a revision.

Synopsis

svnadmin setlog REPOS_PATH -r REVISION FILE

Description

Set the log-message on revision REVISION to the contents of FILE.

This is similar to using svn propset --revprop to set the svn:log property on a revision, except that you can also use the option --bypass-hooks to avoid running any pre- or post-commit hooks, which is useful if the modification of revision properties has not been enabled in the pre-revprop-change hook.

[Внимание]Внимание

Revision properties are not under version control, so this command will permanently overwrite the previous log message.

Switches

--revision (-r) REV
--bypass-hooks

Examples

Set the log message for revision 19 to the contents of the file msg:

$ svnadmin setlog /usr/local/svn/repos/ -r 19 msg

Название

svnadmin verify — Verify the data stored in the repository.

Synopsis

svnadmin verify REPOS_PATH

Description

Run this command if you wish to verify the integrity of your repository. This basically iterates through all revisions in the repository by internally dumping all revisions and discarding the output.

Examples

Verify a hung repository:

$ svnadmin verify /usr/local/svn/repos/
* Verified revision 1729.

svnlook

svnlook is a command-line utility for examining different aspects of a Subversion repository. It does not make any changes to the repository—it's just used for «peeking». svnlook is typically used by the repository hooks, but a repository administrator might find it useful for diagnostic purposes.

Since svnlook works via direct repository access (and thus can only be used on the machine that holds the repository), it refers to the repository with a path, not a URL.

If no revision or transaction is specified, svnlook defaults to the youngest (most recent) revision of the repository.

svnlook Switches

Switches in svnlook are global, just like in svn and svnadmin; however, most switches only apply to one subcommand since the functionality of svnlook is (intentionally) limited in scope.

--no-diff-deleted

Prevents svnlook from printing differences for deleted files. The default behavior when a file is deleted in a transaction/revision is to print the same differences that you would see if you had left the file but removed all the content.

--revision (-r)

Specify a particular revision number that you wish to examine.

--revprop

Operates on a revision property instead of a Subversion property specific to a file or directory. This switch requires that you also pass a revision with the --revision (-r) switch. See «Unversioned Properties» for more details on unversioned properties.

--transaction (-t)

Specify a particular transaction ID that you wish to examine.

--show-ids

Show the filesystem node revision IDs for each path in the filesystem tree.

svnlook

Название

svnlook author — Print the author.

Synopsis

svnlook author REPOS_PATH

Description

Print the author of a revision or transaction in the repository.

Switches

--revision (-r) REV
--transaction (-t)

Examples

svnlook author is handy, but not very exciting:

$ svnlook author -r 40 /usr/local/svn/repos
sally

Название

svnlook cat — Print the contents of a file.

Synopsis

svnlook cat REPOS_PATH PATH_IN_REPOS

Description

Print the contents of a file.

Switches

--revision (-r) REV
--transaction (-t)

Examples

This shows the contents of a file in transaction ax8, located at /trunk/README:

$ svnlook cat -t ax8 /usr/local/svn/repos /trunk/README

               Subversion, a version control system.
               =====================================

$LastChangedDate: 2003-07-17 10:45:25 -0500 (Thu, 17 Jul 2003) $

Contents:

     I. A FEW POINTERS
    II. DOCUMENTATION
   III. PARTICIPATING IN THE SUBVERSION COMMUNITY
…

Название

svnlook changed — Print the paths that were changed.

Synopsis

svnlook changed REPOS_PATH

Description

Print the paths that were changed in a particular revision or transaction, as well as «svn update-style» status letters in the first two columns:

'A '

Item added to repository.

'D '

Item deleted from repository.

'U '

File contents changed.

'_U'

Properties of item changed.

'UU'

File contents and properties changed.

Files and directories can be distinguished, as directory paths are displayed with a trailing '/' character.

Switches

--revision (-r) REV
--transaction (-t)

Examples

This shows a list of all the changed files in revision 39 of a test repository:

$ svnlook changed -r 39 /usr/local/svn/repos
A   trunk/vendors/deli/
A   trunk/vendors/deli/chips.txt
A   trunk/vendors/deli/sandwich.txt
A   trunk/vendors/deli/pickle.txt
U   trunk/vendors/baker/bagel.txt
_U  trunk/vendors/baker/croissant.txt
UU  trunk/vendors/baker/pretzel.txt
D   trunk/vendors/baker/baguette.txt

Название

svnlook date — Print the datestamp.

Synopsis

svnlook date REPOS_PATH

Description

Print the datestamp of a revision or transaction in a repository.

Switches

--revision (-r) REV
--transaction (-t)

Examples

This shows the date of revision 40 of a test repository:

$ svnlook date -r 40 /tmp/repos/
2003-02-22 17:44:49 -0600 (Sat, 22 Feb 2003)

Название

svnlook diff — Print differences of changed files and properties.

Synopsis

svnlook diff REPOS_PATH

Description

Print GNU-style differences of changed files and properties in a repository.

Switches

--revision (-r) REV
--transaction (-t)
--no-diff-added
--no-diff-deleted

Examples

This shows a newly added (empty) file, a deleted file, and a copied file:

$ svnlook diff -r 40 /usr/local/svn/repos/
Copied: egg.txt (from rev 39, trunk/vendors/deli/pickle.txt)

Added: trunk/vendors/deli/soda.txt
==============================================================================

Modified: trunk/vendors/deli/sandwich.txt
==============================================================================
--- trunk/vendors/deli/sandwich.txt (original)
+++ trunk/vendors/deli/sandwich.txt 2003-02-22 17:45:04.000000000 -0600
@@ -0,0 +1 @@
+Don't forget the mayo!

Modified: trunk/vendors/deli/logo.jpg
==============================================================================
(Binary files differ)

Deleted: trunk/vendors/deli/chips.txt
==============================================================================

Deleted: trunk/vendors/deli/pickle.txt
==============================================================================

If a file has a non-textual svn:mime-type property, then the differences are not explicitly shown.


Название

svnlook dirs-changed — Print the directories that were themselves changed.

Synopsis

svnlook dirs-changed REPOS_PATH

Description

Print the directories that were themselves changed (property edits) or whose file children were changed.

Switches

--revision (-r) REV
--transaction (-t)

Examples

This shows the directories that changed in revision 40 in our sample repository:

$ svnlook dirs-changed -r 40 /usr/local/svn/repos
trunk/vendors/deli/

Название

svnlook help — Help!

Synopsis

Also svnlook -h and svnlook -?.

Description

Displays the help message for svnlook. This command, like its brother svn help, is also your friend, even though you never call it anymore and forgot to invite it to your last party.

Alternate Names

?, h


Название

svnlook history — Print information about the history of a path in the repository (or the root directory if no path is supplied).

Synopsis

svnlook history REPOS_PATH [PATH_IN_REPOS]

Description

Print information about the history of a path in the repository (or the root directory if no path is supplied).

Switches

--revision (-r) REV
--show-ids

Examples

This shows the history output for the path /tags/1.0 as of revision 20 in our sample repository.

$ svnlook history -r 20 /usr/local/svn/repos /tags/1.0 --show-ids
REVISION   PATH <ID>
--------   ---------
      19   /tags/1.0 <1.2.12>
      17   /branches/1.0-rc2 <1.1.10>
      16   /branches/1.0-rc2 <1.1.x>
      14   /trunk <1.0.q>
      13   /trunk <1.0.o>
      11   /trunk <1.0.k>
       9   /trunk <1.0.g>
       8   /trunk <1.0.e>
       7   /trunk <1.0.b>
       6   /trunk <1.0.9>
       5   /trunk <1.0.7>
       4   /trunk <1.0.6>
       2   /trunk <1.0.3>
       1   /trunk <1.0.2>

Название

svnlook info — Print the author, datestamp, log message size, and log message.

Synopsis

svnlook info REPOS_PATH

Description

Print the author, datestamp, log message size, and log message.

Switches

--revision (-r) REV
--transaction (-t)

Examples

This shows the info output for revision 40 in our sample repository.

$ svnlook info -r 40 /usr/local/svn/repos
sally
2003-02-22 17:44:49 -0600 (Sat, 22 Feb 2003)
15
Rearrange lunch.

Название

svnlook lock — If a lock exists on a path in the repository, describe it.

Synopsis

svnlook lock REPOS_PATH PATH_IN_REPOS

Description

Print all information available for the lock at PATH_IN_REPOS. If PATH_IN_REPOS is not locked, print nothing.

Switches

None

Examples

This describes the lock on the file tree.jpg.

$ svnlook lock /svn/repos tree.jpg
UUID Token: opaquelocktoken:ab00ddf0-6afb-0310-9cd0-dda813329753
Owner: harry
Created: 2005-07-08 17:27:36 -0500 (Fri, 08 Jul 2005)
Expires: 
Comment (1 line):
Rework the uppermost branches on the bald cypress in the foreground.

Название

svnlook log — Print the log message.

Synopsis

svnlook log REPOS_PATH

Description

Print the log message.

Switches

--revision (-r) REV
--transaction (-t)

Examples

This shows the log output for revision 40 in our sample repository:

$ svnlook log /tmp/repos/
Rearrange lunch.

Название

svnlook propget — Print the raw value of a property on a path in the repository.

Synopsis

svnlook propget REPOS_PATH PROPNAME [PATH_IN_REPOS]

Description

List the value of a property on a path in the repository.

Alternate Names

pg, pget

Switches

--revision (-r) REV
--transaction (-t)
--revprop

Examples

This shows the value of the «seasonings» property on the file /trunk/sandwich in the HEAD revision:

$ svnlook pg /usr/local/svn/repos seasonings /trunk/sandwich
mustard

Название

svnlook proplist — Print the names and values of versioned file and directory properties.

Synopsis

svnlook proplist REPOS_PATH [PATH_IN_REPOS]

Description

List the properties of a path in the repository. With --verbose, show the property values too.

Alternate Names

pl, plist

Switches

--revision (-r) REV
--transaction (-t)
--verbose (-v)
--revprop

Examples

This shows the names of properties set on the file /trunk/README in the HEAD revision:

$ svnlook proplist /usr/local/svn/repos /trunk/README
  original-author
  svn:mime-type

This is the same command as in the previous example, but this time showing the property values as well:

$ svnlook --verbose proplist /usr/local/svn/repos /trunk/README
  original-author : fitz
  svn:mime-type : text/plain

Название

svnlook tree — Print the tree.

Synopsis

svnlook tree REPOS_PATH [PATH_IN_REPOS]

Description

Print the tree, starting at PATH_IN_REPOS (if supplied, at the root of the tree otherwise), optionally showing node revision IDs.

Switches

--revision (-r) REV
--transaction (-t)
--show-ids

Examples

This shows the tree output (with node-IDs) for revision 40 in our sample repository:

$ svnlook tree -r 40 /usr/local/svn/repos --show-ids
/ <0.0.2j>
 trunk/ <p.0.2j>
  vendors/ <q.0.2j>
   deli/ <1g.0.2j>
    egg.txt <1i.e.2j>
    soda.txt <1k.0.2j>
    sandwich.txt <1j.0.2j>

Название

svnlook uuid — Print the repository's UUID.

Synopsis

svnlook uuid REPOS_PATH

Description

Print the UUID for the repository. the UUID is the repository's universal unique identifier. The Subversion client uses this identifier to differentiate between one repository and another.

Examples

$ svnlook uuid /usr/local/svn/repos
e7fe1b91-8cd5-0310-98dd-2f12e793c5e8

Название

svnlook youngest — Print the youngest revision number.

Synopsis

svnlook youngest REPOS_PATH

Description

Print the youngest revision number of a repository.

Examples

This shows the youngest revision of our sample repository:

$ svnlook youngest /tmp/repos/
42

svnserve

svnserve allows access to Subversion repositories using the svn network protocol. You can run svnserve either as a standalone server process, or you can have another process, such as inetd, xinetd or sshd, launch it for you.

Once the client has selected a repository by transmitting its URL, svnserve reads a file named conf/svnserve.conf in the repository directory to determine repository-specific settings such as what authentication database to use and what authorization policies to apply. See «Собственный сервер svnserve» for details of the svnserve.conf file.

svnserve Switches

Unlike the previous commands we've described. svnserve has no subcommands—svnserve is controlled exclusively by switches.

--daemon (-d)

Causes svnserve to run in daemon mode. svnserve backgrounds itself and accepts and serves TCP/IP connections on the svn port (3690, by default).

--listen-port=PORT

Causes svnserve to listen on PORT when run in daemon mode.

--listen-host=HOST

Causes svnserve to listen on the interface specified by HOST, which may be either a hostname or an IP address.

--foreground

When used together with -d, this switch causes svnserve to stay in the foreground. This switch is mainly useful for debugging.

--inetd (-i)

Causes svnserve to use the stdin/stdout file descriptors, as is appropriate for a daemon running out of inetd.

--help (-h)

Displays a usage summary and exits.

--version

Displays version information, a list of repository back-end modules available, and exits.

--root=ROOT (-r=ROOT)

Sets the virtual root for repositories served by svnserve. The pathname in URLs provided by the client will be interpreted relative to this root, and will not be allowed to escape this root.

--tunnel (-t)

Causes svnserve to run in tunnel mode, which is just like the inetd mode of operation (serve one connection over stdin/stdout) except that the connection is considered to be pre-authenticated with the username of the current uid. This flag is selected by the client when running over a tunnel agent such as ssh.

--tunnel-user NAME

Used in conjunction with --tunnel switch; tells svnserve to assume that NAME is the authenticated user, rather than the UID of the svnserve process. Useful for users wishing to share a single system account over SSH, but maintaining separate commit identities.

--threads (-T)

When running in daemon mode, causes svnserve to spawn a thread instead of a process for each connection. The svnserve process still backgrounds itself at startup time.

--listen-once (-X)

Causes svnserve to accept one connection on the svn port, serve it, and exit. This option is mainly useful for debugging.

svnversion

Название

svnversion — Summarize the local revision(s) of a working copy.

Synopsis

svnversion [OPTIONS] [WC_PATH [TRAIL_URL]]

Description

svnversion is a program for summarizing the revision mixture of a working copy. The resultant revision number, or revision range, is written to standard output.

TRAIL_URL, if present, is the trailing portion of the URL used to determine if WC_PATH itself is switched (detection of switches within WC_PATH does not rely on TRAIL_URL).

When WC_PATH is not defined the current directory will be used as the working copy path. TRAIL_URL cannot be defined if WC_PATH is not explicitly given.

Switches

Like svnserve, svnversion has no subcommands, it only has switches.

--no-newline (-n)

Omit the usual trailing newline from the output.

--committed (-c)

Use the last-changed revisions rather than the current (i.e., highest locally available) revisions.

--help (-h)

Print a help summary.

--version

Print the version of svnversion and exit with no error.

Examples

If the working copy is all at the same revision (for example, immediately after an update), then that revision is printed out:

$ svnversion
4168

You can add TRAIL_URL to show that the working copy is not switched from what you expect. Note that the WC_PATH was required in this command:

$ svnversion . /repos/svn/trunk
4168

For a mixed-revision working copy, the range of revisions present is printed:

$ svnversion
4123:4168

If the working copy contains modifications, a trailing "M" is added:

$ svnversion
4168M

If the working copy is switched, a trailing "S" is added:

$ svnversion
4168S

Thus, here is a mixed-revision, switched working copy containing some local modifications:

$ svnversion
4212:4168MS

If invoked on a directory that is not a working copy, svnversion assumes it is an exported working copy and prints "exported":

$ svnversion
exported

mod_dav_svn

Название

mod_dav_svn Configuration Directives — Apache configuration directives for serving Subversion repositories through Apache HTTP Server.

Description

This section briefly describes each of the Subversion Apache configuration directives. For an in-depth description of configuring Apache with Subversion, see «httpd, the Apache HTTP server».)

Directives

DAV svn

This directive must be included in any Directory or Location block for a Subversion repository. It tells httpd to use the Subversion backend for mod_dav to handle all requests.

SVNAutoversioning On

This directive allows write requests from WebDAV clients to result in automatic commits. A generic log message is auto-generated and attached to each revision. If you enable Autoversioning, you'll likely want to set ModMimeUsePathInfo On so that mod_mime can set svn:mime-type to the correct mime-type automatically (as best as mod_mime is able to, of course). For more information, see Приложение C, WebDAV и автоматическое управление версиями

SVNPath

This directive specifies the location in the filesystem for a Subversion repository's files. In a configuration block for a Subversion repository, either this directive or SVNParentPath must be present, but not both.

SVNSpecialURI

Specifies the URI component (namespace) for special Subversion resources. The default is «!svn», and most administrators will never use this directive. Only set this if there is a pressing need to have a file named !svn in your repository. If you change this on a server already in use, it will break all of the outstanding working copies and your users will hunt you down with pitchforks and flaming torches.

SVNReposName

Specifies the name of a Subversion repository for use in HTTP GET requests. This value will be prepended to the title of all directory listings (which are served when you navigate to a Subversion repository with a web browser). This directive is optional.

SVNIndexXSLT

Specifies the URI of an XSL transformation for directory indexes. This directive is optional.

SVNParentPath

Specifies the location in the filesystem of a parent directory whose child directories are Subversion repositories. In a configuration block for a Subversion repository, either this directive or SVNPath must be present, but not both.

SVNPathAuthz

Control path-based authorization by enabling or disabling subrequests. See «Disabling Path-based Checks» for details.

Свойства Subversion

Название

Свойства Subversion — это свойства, которые определяются Subversion для управления ее поведением.

Описание

Subversion позволяет пользователям использовать любые именнованные версионируемые свойства для файлов и каталогов, а так же неверсионируемые для версий. Ограничения накладываются лишь на свойства с префиксом «svn:». Свойства в этом простанстве имен зарезервированы для самой Subversion. Пользователи могут изменять значения таких свойства для управляния поведение Subversion, но они не должны создавать новых «svn:» свойств.

Версионируемые свойства

svn:executable

Наличие такого свойства говорит клиенту пометить такой файл как исполняемый в рабочих копиях на Unix машинах. Смотри «Исполнимость файла».

svn:mime-type

Будучи задано для файла, определяет MIME тип файла. Это позволяет клиенту решить, что он может без опяски использовать построчное слияние при обновлении. Это свойство также влияет на восприятие файла веб браузером. Смотри «Тип содержимого файла».

svn:ignore

Будучи задано для каталога, определяет список шаблонов имен файлов, которые будут игнорироваться svn status и другими подкомандами. Смотри «Пропуск неверсионированных элементов»

svn:keywords

Будучи задано для файла, содержит имена ключевых слов, которые клиент должн разименованы в файле. Смотри «Подстановка ключевых слов».

svn:eol-style

Значение этого свойства, заданного для файла, указывает клиенту механизм обработки символов конца строк в рабочей копии. Смотри «Символы конца строки».

svn:externals

Будучи задано для каталога, определяет многострочный список других частей и URL-ов кой клиент также должен включить в рабочую копию. Смотри «Внешние зависимости».

svn:special

Наличие этого свойства у файла указывает на то, что он не является обычным файлом. Это может быть символическая ссылка или любой другой специальный объект.

svn:needs-lock

Наличие этого свойства у файла, указывает клиенту пометить его в рабочей копии доступным только для чтения, как напоминание о необходимости заблокировать файл перед его редактированием. Смотри «Lock Communication».

Unversioned Properties

svn:author

If present, contains the authenticated username of the person who created the revision. (If not present, then the revision was committed anonymously.)

svn:date

Contains the UTC time the revision was created, in ISO format. The value comes from the server machine's clock.

svn:log

Contains the log message describing the revision.

svn:autoversioned

If present, the revision was created via the autoversioning feature. See «Autoversioning».




[56] Да, да, вам не нужна подкоманда что бы задействовать параметра командной строки --version, но мы вернемся к этому уже через минуту.

[57] Remember, svnadmin works only with local paths, not URLs.

Приложение A. Быстрый старт в Subversion

Некоторые испытывают трудности поглощения новой технологии читая приближение «сверху вниз», предлагаемое этой книгой. Этот раздел представляет собой очень короткое введение в Subversion и предназначен для того, что бы помочь изучающим «снизу вверх». Если вы из тех, кто предпочитает учиться на экспериментах то последующая демонстрация поможет вам начать. По ходу дела мы даем ссылки на соответствующие главы книги.

Если вы не совсем знакомы с концепциями контроля версий или моделью «копирование-изменение-слияние», используемой как CVS так и Subversion, перед тем как идти дальше, вам нужно прочитать Глава 1, Фундаментальные понятия.

Установка Subversion

Subversion построена на слое переносимости под названием APR (the Apache Portable Runtime library). Библиотека APR предоставляет все интерфейсы, необходимые для функционирования Subversion под управлением различных операционных систем: доступ к жесткому диску, доступ к сети, управление памятью, и тому подобное. Не смотря на то, что Subversion может использовать Apache как сервер, ее зависимость от Apache не означает того, что Apache является необходимым компонентом. APR представляет собой отдельную библиотеку, которую может использовать любое приложение. Кроме прочего, это означает, что как и Apache, Subversion клиенты и серверы работают на любой операционной системе на которой работает httpd сервер Apache: Windows, Linux, все разновидности BSD, MacOS X, Netware и другие.

Наиболее простой способ получить Subversion - скачать бинарный пакет, собранный для вашей операционной системы. Как правило, эти пакеты присланные волонтерами, доступны для загрузки с веб-сайта Subversion (http://subversion.tigris.org). Сайт обычно содержит графический инсталлятор для пользователей операционных систем Microsoft. Если вы используете Unix-подобную ОС то для получения Subversion вы можете использовать пакетную систему, специфичную для вашей системы (RPM, DEB, ports tree и т. д.).

В качестве альтернативного варианта вы можете построить Subversion прямо из исходного кода. Закачайте с web-сайта Subversion последний релиз исходного кода. После его распаковки для его сборки следуйте инструкциям в файле INSTALL. Обратите внимание, что такой пакет содержит все необходимое для сборки клиента командной строки, способного работать с удаленным хранилищем (обычно это библиотеки apr, apr-util и neon). Однако некоторые опциональные части Subversion имеют много других зависимостей, таких как Berkeley DB и возможно Apache httpd. Если вы хотите выполнить полную сборку, убедитесь, что у вас есть все пакеты, указанные в файле INSTALL.

Если вы один из тех, кто предпочитает использовать максимально современное програмное обеспечение, вы можете получить исходники Subversion прямо из репозитория Subversion. Само собой, чтобы сделать это, необходимо чтобы у вас уже был клиент Subversion. Затем вы можете создать рабочую копию репозитория исходного кода Subversion из http://svn.collab.net/repos/svn/trunk/: [58]

$ svn checkout http://svn.collab.net/repos/svn/trunk subversion
A    subversion/HACKING
A    subversion/INSTALL
A    subversion/README
A    subversion/autogen.sh
A    subversion/build.conf
…

Приведенная выше команда создаст последнюю версию исходного кода Subversion в поддиректории subversion вашей рабочей директории. Очевидно, вы можете скорректировать последний аргумент так как вам нужно. Хотя независимо от того как вы назовете директорию с новой рабочей копией, после того как эта операция завершится, у вас будут исходики Subversion. Конечно, вам все еще необходимо получить несколько вспомогательных библиотек (apr, apr-util, и так далее.) —Чтобы узнать детали, обратитесь к файлу INSTALL каталоге верхнего уровня вашей рабочей копии.

Быстрый старт в Subversion

«Пожалуйста, удостоверьтесь что ваши посадочные места находятся в верткальном положении, а ваши столики закреплены. Бортпроводникам приготовиться к взлету.….»

Это очень поверхностное руководство, которое покажет вам основы конфигурации и работы с Subversion. К тому времени как вы закончите читать это руководство, у вас должно быть понимание типичного использования Subversion.

[Замечание]Замечание

Примеры, используемые в этом приложении предполагают наличие у вас работающих Subversion клиента для командной строки svn и инструмента администрирования svnadmin. Кроме этого он рассчитан на то, что вы используете Subversion версии 1.2 или более поздней (для того, чтобы это проверить, выполните svn --version).

Subversion хранит всю версионированную информацию в центральном хранилище. Для начала, создадим новое хранилище:

$ svnadmin create /path/to/repos
$ ls /path/to/repos
conf/  dav/  db/  format  hooks/  locks/  README.txt

Эта команда создает новую директорию /path/to/repos содержащую Subversion хранилище. Убедитесь, что эта директория находится на локальном диске, не на сетевой шаре. Преимущественно в эта новая директория (кроме прочего) содержит набор файлов базы данных. Вы не увидите своих версионированных файлов если вы загляните внутрь. Больше информации о создании и поддержке хранилища ищите в Глава 5, Администрирование хранилища.

У Subversion нет понятия «проект». Хранилище является просто виртуальной версионированной файловой системой, большое дерево файлов, которое может содержать все, что угодно. Одни администраторы предпочитают держать в хранилище только один проект, другие держать в хранилище множество проектов, размещая их в отдельных директориях. Достоинства каждого из подходов рассмотрены в «Choosing a Repository Layout». В любом случае, хранилище управляет только файлами и директориями, оставляя за человеком право интерпретировать отдельные директории как «проекты». Поэтому, если в тексте книги вы встретите упоминание проекта, помните, что имеется в виду просто директория (или несколько директорий) хранилища.

В этом примере мы подразумеваем наличие у вас какого то проекта (набора файлов или директорий), который вы хотите импортировать в только что созданное Subversion хранилище. Начните с объединения их в отдельной директории названой myproject (или как-то иначе). По причинам, которые будут ясны позже (см. Глава 4, Ветвление и слияние), ваше дерево проекта должно содержать три директории верхнего уровня с названиями branches, tags и trunk. Вся ваша информация должна находиться в директории trunk, а директории branches и tags должны быть пустыми:

/tmp/myproject/branches/
/tmp/myproject/tags/
/tmp/myproject/trunk/
                     foo.c
                     bar.c
                     Makefile
                     …

Использовать поддиректории branches, tags и trunk не обязательно. Просто такой подход чаще всего используется и вероятнее всего в дальнейшем вы будете использовать именно его.

Как только вы получите готовое дерево данных, импортируйте его в хранилище при помощи команды svn import (см. «svn import»):

$ svn import /tmp/myproject file:///path/to/repos/myproject -m "initial import"
Adding         /tmp/myproject/branches
Adding         /tmp/myproject/tags
Adding         /tmp/myproject/trunk
Adding         /tmp/myproject/trunk/foo.c
Adding         /tmp/myproject/trunk/bar.c
Adding         /tmp/myproject/trunk/Makefile
…
Committed revision 1.
$

Теперь в хранилище находится это дерево данных. Как было отмечено ранее, вы не увидите своих файлов если загляните в хранилище напрямую; все хранится в базе данных. Однако сейчас воображаемая файловая системы хранилища имеет директорию верхнего уровня с названием myproject которая содержит вашу информацию.

Обратите внимание на то, что первоначальная директория /tmp/project остается без изменений; Subversion о ней не знает. (Фактически, при желании, вы можете даже удалить этот каталог.) Чтобы начать работать с информацией хранилища вам нужно создать новую «рабочую копию» информации, своего рода частное рабочее пространство. Попросите Subversion создать рабочую копию директории myproject/trunk хранилища:

$ svn checkout file:///path/to/repos/myproject/trunk myproject
A  myproject/foo.c
A  myproject/bar.c
A  myproject/Makefile
…
Checked out revision 1.

Сейчас у вас в новой директории myproject есть личная копия части хранилища. В рабочей копии вы можете редактировать файлы, а затем зафиксировать внесенные изменения в хранилище.

  • Откройте свою рабочую копию и отредактируйте содержимое файлов.

  • Выполните svn diff чтобы увидеть объединенный diff внесенных изменений.

  • Выполните svn commit для фиксации новой версии ваших файлов в хранилище.

  • Выполните svn update для приведения рабочей копии в «актуальное» состояние по отношению к хранилищу.

Для получения полного списка возможных действий с рабочей копией прочтите Глава 2, Экскурсия по Subversion.

После этого вы можете сделать ваше хранилище доступным для других через сеть. См. Глава 6, Настройка сервера для знакомства с различными типами доступных серверных процессов и методами их настройки.

### TODO: Let's make this into a full tutorial, rather than simply referring off to other sections. ###




[58] Обратите внимание, что URL в указаном примере окнчивается не директорией svn, а поддиректорией trunk. Смотрите обсуждение модели ветвления и меток Subversion, для выяснения причин этого.

Приложение B. Subversion для пользователей CVS

This appendix is a guide for CVS users new to Subversion. It's essentially a list of differences between the two systems as «viewed from 10,000 feet». For each section, we provide backreferences to relevant chapters when possible.

Although the goal of Subversion is to take over the current and future CVS user base, some new features and design changes were required to fix certain «broken» behaviors that CVS had. This means that, as a CVS user, you may need to break habits—ones that you forgot were odd to begin with.

Revision Numbers Are Different Now

In CVS, revision numbers are per-file. This is because CVS stores its data in RCS files; each file has a corresponding RCS file in the repository, and the repository is roughly laid out according to the structure of your project tree.

In Subversion, the repository looks like a single filesystem. Each commit results in an entirely new filesystem tree; in essence, the repository is an array of trees. Each of these trees is labeled with a single revision number. When someone talks about «revision 54», they're talking about a particular tree (and indirectly, the way the filesystem looked after the 54th commit).

Technically, it's not valid to talk about «revision 5 of foo.c». Instead, one would say «foo.c as it appears in revision 5». Also, be careful when making assumptions about the evolution of a file. In CVS, revisions 5 and 6 of foo.c are always different. In Subversion, it's most likely that foo.c did not change between revisions 5 and 6.

For more details on this topic, see «Правки».

Directory Versions

Subversion tracks tree structures, not just file contents. It's one of the biggest reasons Subversion was written to replace CVS.

Here's what this means to you, as a former CVS user:

  • The svn add and svn delete commands work on directories now, just as they work on files. So do svn copy and svn move. However, these commands do not cause any kind of immediate change in the repository. Instead, the working items are simply «scheduled» for addition or deletion. No repository changes happen until you run svn commit.

  • Directories aren't dumb containers anymore; they have revision numbers like files. (Or more properly, it's correct to talk about «directory foo/ in revision 5».)

Let's talk more about that last point. Directory versioning is a hard problem; because we want to allow mixed-revision working copies, there are some limitations on how far we can abuse this model.

From a theoretical point of view, we define «revision 5 of directory foo» to mean a specific collection of directory-entries and properties. Now suppose we start adding and removing files from foo, and then commit. It would be a lie to say that we still have revision 5 of foo. However, if we bumped foo's revision number after the commit, that would be a lie too; there may be other changes to foo we haven't yet received, because we haven't updated yet.

Subversion deals with this problem by quietly tracking committed adds and deletes in the .svn area. When you eventually run svn update, all accounts are settled with the repository, and the directory's new revision number is set correctly. Therefore, only after an update is it truly safe to say that you have a «perfect» revision of a directory. Most of the time, your working copy will contain «imperfect» directory revisions.

Similarly, a problem arises if you attempt to commit property changes on a directory. Normally, the commit would bump the working directory's local revision number. But again, that would be a lie, because there may be adds or deletes that the directory doesn't yet have, because no update has happened. Therefore, you are not allowed to commit property-changes on a directory unless the directory is up-to-date.

For more discussion about the limitations of directory versioning, see «Смешивание правок в рабочих копиях».

More Disconnected Operations

In recent years, disk space has become outrageously cheap and abundant, but network bandwidth has not. Therefore, the Subversion working copy has been optimized around the scarcer resource.

The .svn administrative directory serves the same purpose as the CVS directory, except that it also stores read-only, «pristine» copies of your files. This allows you to do many things off-line:

svn status

Shows you any local changes you've made (see «svn status»)

svn diff

Shows you the details of your changes (see «svn diff»)

svn revert

Removes your local changes (see «svn revert»)

Also, the cached pristine files allow the Subversion client to send differences when committing, which CVS cannot do.

The last subcommand in the list is new; it will not only remove local changes, but it will un-schedule operations such as adds and deletes. It's the preferred way to revert a file; running rm file; svn update will still work, but it blurs the purpose of updating. And, while we're on this subject…

Distinction Between Status and Update

In Subversion, we've tried to erase a lot of the confusion between the cvs status and cvs update commands.

The cvs status command has two purposes: first, to show the user any local modifications in the working copy, and second, to show the user which files are out-of-date. Unfortunately, because of CVS's hard-to-read status output, many CVS users don't take advantage of this command at all. Instead, they've developed a habit of running cvs update or cvs -n update to quickly see their changes. If users forget to use the -n option, this has the side effect of merging repository changes they may not be ready to deal with.

With Subversion, we've tried to remove this muddle by making the output of svn status easy to read for both humans and parsers. Also, svn update only prints information about files that are updated, not local modifications.

Status

svn status prints all files that have local modifications. By default, the repository is not contacted. While this subcommand accepts a fair number of options, the following are the most commonly used ones:

-u

Contact the repository to determine, and then display, out-of-dateness information.

-v

Show all entries under version control.

-N

Run non-recursively (do not descend into subdirectories).

The status command has two output formats. In the default «short» format, local modifications look like this:

$ svn status
M      foo.c
M      bar/baz.c

If you specify the --show-updates (-u) switch, a longer output format is used:

$ svn status -u
M            1047   foo.c
       *     1045   faces.html
       *            bloo.png
M            1050   bar/baz.c
Status against revision:   1066

In this case, two new columns appear. The second column contains an asterisk if the file or directory is out-of-date. The third column shows the working-copy's revision number of the item. In the example above, the asterisk indicates that faces.html would be patched if we updated, and that bloo.png is a newly added file in the repository. (The absence of any revision number next to bloo.png means that it doesn't yet exist in the working copy.)

Lastly, here's a quick summary of the most common status codes that you may see:

A    Resource is scheduled for Addition
D    Resource is scheduled for Deletion
M    Resource has local Modifications
C    Resource has Conflicts (changes have not been completely merged
       between the repository and working copy version)
X    Resource is eXternal to this working copy (may come from another
       repository).  See «Внешние зависимости»
?    Resource is not under version control
!    Resource is missing or incomplete (removed by another tool than
       Subversion)

For a more detailed discussion of svn status, see «svn status».

Update

svn update updates your working copy, and only prints information about files that it updates.

Subversion has combined the CVS P and U codes into just U. When a merge or conflict occurs, Subversion simply prints G or C, rather than a whole sentence about it.

For a more detailed discussion of svn update, see «Обновление рабочей копии».

Branches and Tags

Subversion doesn't distinguish between filesystem space and «branch» space; branches and tags are ordinary directories within the filesystem. This is probably the single biggest mental hurdle a CVS user will need to climb. Read all about it in Глава 4, Ветвление и слияние.

[Внимание]Внимание

Since Subversion treats branches and tags as ordinary directories, always remember to check out the trunk (http://svn.example.com/repos/calc/trunk/) of your project, and not the project itself (http://svn.example.com/repos/calc/). If you make the mistake of checking out the project itself, you'll wind up with a working copy that contains a copy of your project for every branch and tag you have.[59]

Metadata Properties

A new feature of Subversion is that you can attach arbitrary metadata (or «properties») to files and directories. Properties are arbitrary name/value pairs associated with files and directories in your working copy.

To set or get a property name, use the svn propset and svn propget subcommands. To list all properties on an object, use svn proplist.

For more information, see «Свойства».

Conflict Resolution

CVS marks conflicts with in-line «conflict markers», and prints a C during an update. Historically, this has caused problems, because CVS isn't doing enough. Many users forget about (or don't see) the C after it whizzes by on their terminal. They often forget that the conflict-markers are even present, and then accidentally commit files containing conflict-markers.

Subversion solves this problem by making conflicts more tangible. It remembers that a file is in a state of conflict, and won't allow you to commit your changes until you run svn resolved. See «Разрешение конфликтов (при слиянии с чужими изменениями)» for more details.

Binary Files and Translation

In the most general sense, Subversion handles binary files more gracefully than CVS does. Because CVS uses RCS, it can only store successive full copies of a changing binary file. Subversion, however, expresses differences between files using a binary-differencing algorithm, regardless of whether they contain textual or binary data. That means that all files are stored differentially (compressed) in the repository.

CVS users have to mark binary files with -kb flags, to prevent data from being garbled (due to keyword expansion and line-ending translations). They sometimes forget to do this.

Subversion takes the more paranoid route—first, it never performs any kind of keyword or line-ending translation unless you explicitly ask it do so (see «Подстановка ключевых слов» and «Символы конца строки» for more details). By default, Subversion treats all file data as literal byte strings, and files are always stored in the repository in an untranslated state.

Second, Subversion maintains an internal notion of whether a file is «text» or «binary» data, but this notion is only extant in the working copy. During an svn update, Subversion will perform contextual merges on locally modified text files, but will not attempt to do so for binary files.

To determine whether a contextual merge is possible, Subversion examines the svn:mime-type property. If the file has no svn:mime-type property, or has a mime-type that is textual (e.g. text/*), Subversion assumes it is text. Otherwise, Subversion assumes the file is binary. Subversion also helps users by running a binary-detection algorithm in the svn import and svn add commands. These commands will make a good guess and then (possibly) set a binary svn:mime-type property on the file being added. (If Subversion guesses wrong, the user can always remove or hand-edit the property.)

Versioned Modules

Unlike CVS, a Subversion working copy is aware that it has checked out a module. That means that if somebody changes the definition of a module (e.g. adds or removes components), then a call to svn update will update the working copy appropriately, adding and removing components.

Subversion defines modules as a list of directories within a directory property: see «Внешние зависимости».

Authentication

With CVS's pserver, you are required to «login» to the server before any read or write operation—you even have to login for anonymous operations. With a Subversion repository using Apache httpd or svnserve as the server, you don't provide any authentication credentials at the outset—if an operation that you perform requires authentication, the server will challenge you for your credentials (whether those credentials are username and password, a client certificate, or even both). So if your repository is world-readable, you will not be required to authenticate at all for read operations.

As with CVS, Subversion still caches your credentials on disk (in your ~/.subversion/auth/ directory) unless you tell it not to by using the --no-auth-cache switch.

The exception to this behavior, however, is in the case of accessing an svnserve server over an SSH tunnel, using the svn+ssh:// URL schema. In that case, the ssh program unconditionally demands authentication just to start the tunnel.

Converting a Repository from CVS to Subversion

Perhaps the most important way to familiarize CVS users with Subversion is to let them continue to work on their projects using the new system. And while that can be somewhat accomplished using a flat import into a Subversion repository of an exported CVS repository, the more thorough solution involves transferring not just the latest snapshot of their data, but all the history behind it as well, from one system to another. This is an extremely difficult problem to solve that involves deducing changesets in the absence of atomicity, and translating between the systems' completely orthogonal branching policies, among other complications. Still, there are a handful of tools claiming to at least partially support the ability to convert existing CVS repositories into Subversion ones.

One such tool is cvs2svn (http://cvs2svn.tigris.org/), a Python script originally created by members of Subversion's own development community. Others include Lev Serebryakov's RefineCVS (http://lev.serebryakov.spb.ru/refinecvs/). These tools have various levels of completeness, and may make entirely different decisions about how to handle your CVS repository history. Whichever tool you decide to use, be sure to perform as much verification as you can stand on the conversion results—after all, you've worked hard to build that history!

For an updated collection of links to known converter tools, visit the Links page of the Subversion website (http://subversion.tigris.org/project_links.html).




[59] That is, providing you don't run out of disk space before your checkout finishes.

Приложение C. WebDAV и автоматическое управление версиями

WebDAV is an extension to HTTP, and is growing more and more popular as a standard for file-sharing. Today's operating systems are becoming extremely Web-aware, and many now have built-in support for mounting «shares» exported by WebDAV servers.

If you use Apache/mod_dav_svn as your Subversion network server, then to some extent, you are also running a WebDAV server. This appendix gives some background on the nature of this protocol, how Subversion uses it, and how well Subversion interoperates with other software that is WebDAV-aware.

Basic WebDAV Concepts

This section provides a very brief, very general overview to the ideas behind WebDAV. It should lay the foundation for understanding WebDAV compatibility issues between clients and servers.

Original WebDAV

RFC 2518 defines a set of concepts and accompanying extension methods to HTTP 1.1 that make the web into a more universal read/write medium. The basic idea is that a WebDAV-compliant web server can act like a generic file server; clients can mount shared folders that behave much like NFS or SMB filesystems.

The tragedy, though, is that the RFC 2518 WebDAV specification does not provide any sort of model for version control, despite the «V» in DAV. Basic WebDAV clients and servers assume only one version of each file or directory exists, and can be repeatedly overwritten.

Here are the concepts and terms introduced in basic WebDAV:

Resources

WebDAV lingo refers to any server-side object (that can be described with a URI) as a resource.

New write methods

Beyond the standard HTTP PUT method (which creates or overwrites a web resource), WebDAV defines new COPY and MOVE methods for duplicating or rearranging resources.

Collections

A collection is the WebDAV term for a grouping of resources. In most cases, it is analogous to a directory. Whereas file resources can be written or created with a PUT method, collection resources are created with the new MKCOL method.

Properties

This is the same idea present in Subversion—metadata attached to files and collections. A client can list or retrieve properties attached to a resource with the new PROPFIND method, and can change them with the PROPPATCH method. Some properties are wholly created and controlled by users (e.g. a property called «color»), and others are wholly created and controlled by the WebDAV server (e.g. a property that contains the last modification time of a file). The former kind are called dead properties, and the latter kind are called live properties.

Locking

A WebDAV server may decide to offer a locking feature to clients—this part of the specification is optional, although most WebDAV servers do offer the feature. If present, then clients can use the new LOCK and UNLOCK methods to mediate access to a resource. In most cases these methods are used to create exclusive write locks (as discussed in «Модель Блокирование-Изменение-Разблокирование»), although shared write locks are also possible in some server implementations.

Access control

A more recent specification (RFC 3744) defines a system for defining access control lists (ACLs) on WebDAV resources. Some clients and servers have begun to implement this feature.

DeltaV Extensions

Because RFC 2518 left out versioning concepts, another committee was left with the responsibility of writing RFC 3253, which adds versioning to WebDAV, a.k.a. «DeltaV». WebDAV/DeltaV clients and servers are often called just «DeltaV» programs, since DeltaV implies the existence of basic WebDAV.

DeltaV introduces a whole slew of new acronyms, but don't be intimidated. The ideas are fairly straightforward:

Per-resource versioning

Like CVS and other version-control systems, DeltaV assumes that each resource has a potentially infinite number of states. A client begins by placing a resource under version control using the new VERSION-CONTROL method.

Server-side working-copy model

Some DeltaV servers support the ability to create a virtual workspace on the server, where all of your work is performed. Clients use the MKWORKSPACE method to create a private area, then indicate they want to change specific resources by «checking them out» into the workspace, editing them, and «checking them in» again. In HTTP terms, the sequence of methods would be CHECKOUT, PUT, CHECKIN.

Client-side working-copy model

Some DeltaV servers also support the idea that the client may have a private working copy on local disk. When the client wants to commit changes to the server, it begins by creating a temporary server transaction (called an activity) with the MKACTIVITY method. The client then performs a CHECKOUT on each resource it wishes to change and sends PUT requests. Finally, the client performs a CHECKIN resource, or sends a MERGE request to check in all resources at once.

Configurations

DeltaV allows you define flexible collections of resources called «configurations», which don't necessarily correspond to particular directories. A configuration can be made to point to specific versions of files, and then a «baseline» snapshot can be made, much like a tag.

Extensibility

DeltaV defines a new method, REPORT, which allows the client and server to perform customized data exchanges. While DeltaV defines a number of standardized history reports that a client can request, the server is also free to define custom reports. The client sends a REPORT request with a properly-labeled XML body full of custom data; assuming the server understands the specific report-type, it responds with an equally custom XML body. This technique is very similar to XML-RPC.

Subversion and DeltaV

The original WebDAV standard has been widely successful. Every modern computer operating system has a general WebDAV client built-in (details to follow), and a number of popular standalone applications are also able to speak WebDAV — Microsoft Office, Dreamweaver, and Photoshop to name a few. On the server end, the Apache webserver has been able to provide WebDAV services since 1998 and is considered the de-facto open-source standard. There are several other commercial WebDAV servers available, including Microsoft's own IIS.

DeltaV, unfortunately, has not been so successful. It's very difficult to find any DeltaV clients or servers. The few that do exist are relatively unknown commercial products, and thus it's very difficult to test interoperability. It's not entirely clear as to why DeltaV has remained stagnant. Some argue that the specification is just too complex, others argue that while WebDAV's features have mass appeal (even the least technical users appreciate network file-sharing), version control features aren't interesting or necessary for most users. Finally, some have argued that DeltaV remains unpopular because there's still no open-source server product which implements it.

When Subversion was still in its design phase, it seemed like a great idea to use Apache httpd as the main network server. It already had a module to provide WebDAV services. DeltaV was a relatively new specification. The hope was that the Subversion server module (mod_dav_svn) would eventually evolve into an open-source DeltaV reference implementation. Unfortunately, DeltaV has a very specific versioning model that doesn't quite line up with Subversion's model. Some concepts were mappable, others were not.

The upshot is that

  1. The Subversion client is not a fully-implemented DeltaV client.

    The client needs certain things from the server that DeltaV cannot provide, and thus is largely dependent on a number of Subversion-specific REPORT requests that only mod_dav_svn understands.

  2. mod_dav_svn is not a fully-implemented DeltaV server.

    Many portions of the DeltaV specification were irrelevant to Subversion, and thus left unimplemented.

There is still some debate in the developer community as to whether or not it's worthwhile to remedy either of these situations. It's fairly unrealistic to change Subversion's design to match DeltaV, so there's probably no way the client can ever learn to get everything it needs from a general DeltaV server. On the other hand, mod_dav_svn could be further developed to implement all of DeltaV, but it's hard to find motivation to do so—there are almost no DeltaV clients to interoperate with.

Autoversioning

While the Subversion client is not a full DeltaV client, nor the Subversion server a full DeltaV server, there's still a glimmer of WebDAV interoperability to be happy about: it's called autoversioning.

Autoversioning is an optional feature defined in the DeltaV standard. A typical DeltaV server will reject an ignorant WebDAV client attempting to do a PUT to a file that's under version control. To change a version-controlled file, the server expects a series proper versioning requests: something like MKACTIVITY, CHECKOUT, PUT, CHECKIN. But if the DeltaV server supports autoversioning, then write-requests from basic WebDAV clients are accepted. The server behaves as if the client had issued the proper series of versioning requests, performing a commit under the hood. In other words, it allows a DeltaV server to interoperate with ordinary WebDAV clients that don't understand versioning.

Because so many operating systems already have integrated WebDAV clients, the use case for this feature borders on fantastical: imagine an office of ordinary users running Microsoft Windows or Mac OS. Each user «mounts» the Subversion repository, which appears to be an ordinary network folder. They use the shared folder as they always do: open files, edit them, save them. Meanwhile, the server is automatically versioning everything. Any administrator (or knowledgeable user) can still use a Subversion client to search history and retrieve older versions of data.

This scenario isn't fiction: it's real and it works, as of Subversion 1.2 and later. To activate autoversioning in mod_dav_svn, use the SVNAutoversioning directive within the httpd.conf Location block, like so:

<Location /repos>
  DAV svn
  SVNPath /path/to/repository
  SVNAutoversioning on
</Location>

When SVNAutoversioning is active, write requests from WebDAV clients result in automatic commits. A generic log message is auto-generated and attached to each revision.

Before activating this feature, however, understand what you're getting into. WebDAV clients tend to do many write requests, resulting in a huge number of automatically committed revisions. For example, when saving data, many clients will do a PUT of a 0-byte file (as a way of reserving a name) followed by another PUT with the real filedata. The single file-write results in two separate commits. Also consider that many applications auto-save every few minutes, resulting in even more commits.

If you have a post-commit hook program that sends email, you may want to disable email generation either altogether, or on certain sections of the repository; it depends on whether you think the influx of emails will still prove to be valuable notifications or not. Also, a smart post-commit hook program can distinguish between a transaction created via autoversioning and one created through a normal svn commit. The trick is to look for a revision property named svn:autoversioned. If present, the commit was made by a generic WebDAV client.

Another feature that may be a useful complement for SVNAutoversioning comes from Apache's mod_mime module. If a generic WebDAV client adds a new file to the repository, there's no opportunity for the user to set the the svn:mime-type property. This might cause the file to appear as «generic» icon when viewed within a WebDAV shared folder, not having an association with any application. One remedy is to have a sysadmin (or other Subversion-knowledgable person) check out a working copy and manually set the svn:mime-type property on necessary files. But there's potentially no end to such cleanup tasks. Instead, you can use the ModMimeUsePathInfo directive in your Subversion <Location> block:

<Location /repos>
  DAV svn
  SVNPath /path/to/repository
  SVNAutoversioning on

  ModMimeUsePathInfo on

</Location>

This directive allows mod_mime to attempt automatic deduction of the mime-type on new files that enter the repository via autoversioning. The module looks at the file's named extension and possibly the contents as well; if the file matches some common patterns, then the the file's svn:mime-type property will be set automatically.

Client Interoperability

All WebDAV clients fall into one of three categories—standalone applications, file-explorer extensions, or filesystem implementations. These categories broadly define the types of WebDAV functionality available to users. Таблица C.1, «Common WebDAV Clients» gives our categorization and a quick description of some common pieces of WebDAV-enabled software. More details about these software offerings, as well as their general category, can be found in the sections that follow.

Таблица C.1. Common WebDAV Clients

SoftwareCategoryDescription
Adobe PhotoshopStandalone WebDAV applicationsImage editing software, allowing direct opening from, and writing to, WebDAV URLs
CadaverStandalone WebDAV applicationsCommand-line WebDAV client supporting file transfer, tree, and locking operations
DAV ExplorerStandalone WebDAV applicationsGUI tool for exploring WebDAV shares
davfs2WebDAV filesystem implementationLinux file system driver that allows you to mount a WebDAV share
GNOME NautilusFile-explorer WebDAV extensionsGUI file explorer able to perform tree operations on a WebDAV share
KDE KonquerorFile-explorer WebDAV extensionsGUI file explorer able to perform tree operations on a WebDAV share
Mac OS XWebDAV filesystem implementationOperating system with built-in support for mounting WebDAV shares locally
Macromedia DreamweaverStandalone WebDAV applicationsWeb production software able to directly read from and write to WebDAV URLs
Microsoft OfficeStandalone WebDAV applicationsOffice productivity suite with several components able to directly read from and write to WebDAV URLs
Microsoft Web FoldersFile-explorer WebDAV extensionsGUI file explorer program able to perform tree operations on a WebDAV share
Novell NetDriveWebDAV filesystem implementationDrive-mapping program for assigning Windows drive letters to a mounted remote WebDAV share
SRT WebDriveWebDAV filesystem implementationFile transfer software which, among other things, allows the assignment of Windows drive letters to a mounted remote WebDAV share


Standalone WebDAV applications

A WebDAV application is a program which contains built-in functionality for speaking WebDAV protocols with a WebDAV server. We'll cover some of the most popular programs with this kind of WebDAV support.

Microsoft Office, Dreamweaver, Photoshop

On Windows, there are several well-known applications that contain integrated WebDAV client functionality, such as Microsoft's Office, [60] Adobe's Photoshop, and Macromedia's Dreamweaver programs. They're able to directly open and save to URLs, and tend to make heavy use of WebDAV locks when editing a file.

Note that while many of these programs also exist for the Mac OS X, they do not appear to support WebDAV directly on that platform. In fact, on Mac OS X, the File->Open dialog box doesn't allow one to type a path or URL at all. It's likely that the WebDAV features were deliberately left out of Macintosh versions of these programs, since OS X already provides such excellent low-level filesystem support for WebDAV.

Cadaver, DAV Explorer

Cadaver is a bare-bones Unix commandline program for browsing and changing WebDAV shares. Like the Subversion client, it uses the neon HTTP library—not surprisingly, both neon and cadaver are written by the same author. Cadaver is free software (GPL license) and is available at http://www.webdav.org/cadaver/.

Using cadaver is similar to using a commandline FTP program, and thus it's extremely useful for basic WebDAV debugging. It can be used to upload or download files in a pinch, and also to examine properties, copy, move, lock or unlock files:

$ cadaver http://host/repos
dav:/repos/> ls
Listing collection `/repos/': succeeded.
Coll: > foobar                                 0  May 10 16:19
      > playwright.el                       2864  May  4 16:18
      > proofbypoem.txt                     1461  May  5 15:09
      > westcoast.jpg                      66737  May  5 15:09

dav:/repos/> put README
Uploading README to `/repos/README':
Progress: [=============================>] 100.0% of 357 bytes succeeded.

dav:/repos/> get proofbypoem.txt
Downloading `/repos/proofbypoem.txt' to proofbypoem.txt:
Progress: [=============================>] 100.0% of 1461 bytes succeeded.

DAV Explorer is another standalone WebDAV client, written in Java. It's under a free Apache-like license and is available at http://www.ics.uci.edu/~webdav/. DAV Explorer does everything cadaver does, but has the advantages of being portable and being a more user-friendly GUI application. It's also one of the first clients to support the new WebDAV Access Control Protocol (RFC 3744).

Of course, DAV Explorer's ACL support is useless in this case, since mod_dav_svn doesn't support it. The fact that both Cadaver and DAV Explorer support some limited DeltaV commands isn't particularly useful either, since they don't allow MKACTIVITY requests. But it's not relevant anyway; we're assuming all of these clients are operating against an autoversioning repository.

File-explorer WebDAV extensions

Some popular file explorer GUI programs support WebDAV extensions which allow a user to browse a DAV share as if it was just another directory on the local computer, and allowing basic tree editing operations on the items in that share. For example, Windows Explorer is able to browse a WebDAV server as a «network place». Users can drag files to and from the desktop, or can rename, copy, or delete files in the usual way. But because it's only a feature of the file-explorer, the DAV share isn't visible to ordinary applications. All DAV interaction must happen through the explorer interface.

Microsoft Web Folders

Microsoft was one of the original backers of the WebDAV specification, and first started shipping a client in Windows 98, known as «Web Folders». This client was also shipped in Windows NT4 and 2000.

The original Web Folders client was an extension to Explorer, the main GUI program used to browse filesystems. It works well enough. In Windows 98, the feature might need to be explicitly installed if Web Folders aren't already visible inside «My Computer». In Windows 2000, simply add a new «network place», enter the URL, and the WebDAV share will pop up for browsing.

With the release of Windows XP, Microsoft started shipping a new implementation of Web Folders, known as the «WebDAV mini-redirector». The new implementation is a filesystem-level client, allowing WebDAV shares to be mounted as drive letters. Unfortunately, this implementation is incredibly buggy. The client usually tries to convert http URLs (http://host/repos) into UNC share notation (\\host\repos); it also often tries to use Windows Domain authentication to respond to basic-auth HTTP challenges, sending usernames as HOST\username. These interoperability problems are severe and documented in numerous places around the web, to the frustration of many users. Even Greg Stein, the original author of Apache's WebDAV module, recommends against trying to use XP Web Folders against an Apache server.

It turns out that the original «Explorer-only» Web Folders implementation isn't dead in XP, it's just buried. It's still possible to find it by using this technique:

  1. Go to 'Network Places'.

  2. Add a new network place.

  3. When prompted, enter the URL of the repository, but include a port number in the URL. For example, http://host/repos would be entered as http://host:80/repos instead.

  4. Respond to any authentication prompts.

There are a number of other rumored workarounds to the problems, but none of them seem to work on all versions and patchlevels of Windows XP. In our tests, only the previous algorithm seems to work consistently on every system. The general consensus of the WebDAV community is that you should avoid the new Web Folders implementation and use the old one instead, and that if you need a real filesystem-level client for Windows XP, then use a third-party program like WebDrive or NetDrive.

A final tip: if you're attempting to use XP Web Folders, make sure you have the absolute latest version from Microsoft. For example, Microsoft released a bug-fixed version in January 2005, available at http://support.microsoft.com/?kbid=892211. In particular, this release is known to fix a bug whereby browsing a DAV share shows an unexpected infinite recursion.

Nautilus, Konqueror

Nautilus is the official file manager/browser for the GNOME desktop (http://www.gnome.org), and Konqueror is the manager/browser for the KDE desktop (http://www.kde.org). Both of these applications have an explorer-level WebDAV client built-in, and operate just fine against an autoversioning repository.

In GNOME's Nautilus, from the File menu, select Open location and enter the URL. The repository should then be displayed like any other filesystem.

In KDE's Konqueror, you need to use the webdav:// scheme when entering the URL in the location bar. If you enter an http:// URL, Konqueror will behave like an ordinary web browser. You'll likely see the generic HTML directory listing produced by mod_dav_svn. By entering webdav://host/repos instead of http://host/repos, Konqueror becomes a WebDAV client and displays the repository as a filesystem.

WebDAV filesystem implementation

The WebDAV filesystem implementation is arguably the best sort of WebDAV client. It's implemented as a low-level filesystem module, typically within the operating system's kernel. This means that the DAV share is mounted like any other network filesystem, similar to mounting an NFS share on Unix, or attaching an SMB share as drive-letter in Windows. As a result, this sort of client provides completely transparent read/write WebDAV access to all programs. Applications aren't even aware that WebDAV requests are happening.

WebDrive, NetDrive

Both WebDrive and NetDrive are excellent commercial products which allow a WebDAV share to be attached as drive letters in Windows. We've had nothing but success with these products. At the time of writing, WebDrive can be purchased from South River Technologies (http://www.southrivertech.com). NetDrive ships with Netware, is free of charge, and can be found by searching the web for «netdrive.exe». Though it is freely available online, users are required to have a Netware license. (If any of that sounds odd to you, you're not alone. See this page on Novell's website: http://www.novell.com/coolsolutions/qna/999.html)

Mac OS X

Apple's OS X operating system has an integrated filesystem-level WebDAV client. From the Finder, select the Connect to Server item from the Go menu. Enter a WebDAV URL, and it appears as a disk on the desktop, just like any other mounted volume. You can also mount a WebDAV share from the Darwin terminal by using the webdav filesystem type with the mount command:

$ mount -t webdav http://svn.example.com/repos/project /some/mountpoint
$

Note that if your mod_dav_svn is older than version 1.2, OS X will refuse to mount the share as read-write; it will appear as read-only. This is because OS X insists on locking support for read-write shares, and the ability to lock files first appeared in Subversion 1.2.

One more word of warning: OS X's WebDAV client can sometimes be overly sensitive to HTTP redirects. If OS X is unable to mount the repository at all, you may need to enable the BrowserMatch directive in the Apache server's httpd.conf:

BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully

Linux davfs2

Linux davfs2 is a filesystem module for the Linux kernel, whose development is located at http://dav.sourceforge.net/. Once installed, a WebDAV network share can be mounted with the usual Linux mount command:

$ mount.davfs http://host/repos /mnt/dav



[60] WebDAV support was removed from Microsoft Access for some reason, but exists in the rest of the Office suite.

Приложение D. Инструменты от сторонних разработчиков

Модульная архитектура Subversion (рассмотренная в разделе «Layered Library Design») и наличие надстроек для различных языков программирования (см. раздел «Using Languages Other than C and C++») делает её перспективным кандидатом в качестве дополнения или бекенда для других программ. На странице Ссылки веб-сайта Subversion http://subversion.tigris.org/project_links.html есть перечень большого количества программ от сторонних разработчиков, использующих возможности Subversion «под капотом».

Приложение E. Copyright


Copyright (c) 2002-2006
Ben Collins-Sussman, Brian W. Fitzpatrick, C. Michael Pilato.  

This work is licensed under the Creative Commons Attribution License.
To view a copy of this license, visit
http://creativecommons.org/licenses/by/2.0/ or send a letter to
Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305,
USA.

A summary of the license is given below, followed by the full legal
text.

--------------------------------------------------------------------

You are free:

    * to copy, distribute, display, and perform the work
    * to make derivative works
    * to make commercial use of the work

Under the following conditions:
	
Attribution. You must give the original author credit.

    * For any reuse or distribution, you must make clear to others the
      license terms of this work.

    * Any of these conditions can be waived if you get permission from
      the author.

Your fair use and other rights are in no way affected by the above.

The above is a summary of the full license below.

====================================================================

Creative Commons Legal Code
Attribution 2.0

CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR
DAMAGES RESULTING FROM ITS USE.

License

THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS
CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS
PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE
WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS
PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND
AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS
YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF
SUCH TERMS AND CONDITIONS.

1. Definitions

   a. "Collective Work" means a work, such as a periodical issue,
      anthology or encyclopedia, in which the Work in its entirety in
      unmodified form, along with a number of other contributions,
      constituting separate and independent works in themselves, are
      assembled into a collective whole. A work that constitutes a
      Collective Work will not be considered a Derivative Work (as
      defined below) for the purposes of this License.

   b. "Derivative Work" means a work based upon the Work or upon the
      Work and other pre-existing works, such as a translation,
      musical arrangement, dramatization, fictionalization, motion
      picture version, sound recording, art reproduction, abridgment,
      condensation, or any other form in which the Work may be recast,
      transformed, or adapted, except that a work that constitutes a
      Collective Work will not be considered a Derivative Work for the
      purpose of this License. For the avoidance of doubt, where the
      Work is a musical composition or sound recording, the
      synchronization of the Work in timed-relation with a moving
      image ("synching") will be considered a Derivative Work for the
      purpose of this License.

   c. "Licensor" means the individual or entity that offers the Work
      under the terms of this License.

   d. "Original Author" means the individual or entity who created the Work.

   e. "Work" means the copyrightable work of authorship offered under
      the terms of this License.

   f. "You" means an individual or entity exercising rights under this
      License who has not previously violated the terms of this
      License with respect to the Work, or who has received express
      permission from the Licensor to exercise rights under this
      License despite a previous violation.

2. Fair Use Rights. Nothing in this license is intended to reduce,
   limit, or restrict any rights arising from fair use, first sale or
   other limitations on the exclusive rights of the copyright owner
   under copyright law or other applicable laws.

3. License Grant. Subject to the terms and conditions of this License,
   Licensor hereby grants You a worldwide, royalty-free,
   non-exclusive, perpetual (for the duration of the applicable
   copyright) license to exercise the rights in the Work as stated
   below:

   a. to reproduce the Work, to incorporate the Work into one or more
      Collective Works, and to reproduce the Work as incorporated in
      the Collective Works;

   b. to create and reproduce Derivative Works;

   c. to distribute copies or phonorecords of, display publicly,
      perform publicly, and perform publicly by means of a digital
      audio transmission the Work including as incorporated in
      Collective Works;

   d. to distribute copies or phonorecords of, display publicly,
      perform publicly, and perform publicly by means of a digital
      audio transmission Derivative Works.

   e.

      For the avoidance of doubt, where the work is a musical composition:

         i. Performance Royalties Under Blanket Licenses. Licensor
            waives the exclusive right to collect, whether
            individually or via a performance rights society
            (e.g. ASCAP, BMI, SESAC), royalties for the public
            performance or public digital performance (e.g. webcast)
            of the Work.

        ii. Mechanical Rights and Statutory Royalties. Licensor waives
            the exclusive right to collect, whether individually or
            via a music rights agency or designated agent (e.g. Harry
            Fox Agency), royalties for any phonorecord You create from
            the Work ("cover version") and distribute, subject to the
            compulsory license created by 17 USC Section 115 of the US
            Copyright Act (or the equivalent in other jurisdictions).

   f. Webcasting Rights and Statutory Royalties. For the avoidance of
      doubt, where the Work is a sound recording, Licensor waives the
      exclusive right to collect, whether individually or via a
      performance-rights society (e.g. SoundExchange), royalties for
      the public digital performance (e.g. webcast) of the Work,
      subject to the compulsory license created by 17 USC Section 114
      of the US Copyright Act (or the equivalent in other
      jurisdictions).

The above rights may be exercised in all media and formats whether now
known or hereafter devised. The above rights include the right to make
such modifications as are technically necessary to exercise the rights
in other media and formats. All rights not expressly granted by
Licensor are hereby reserved.

4. Restrictions.The license granted in Section 3 above is expressly
   made subject to and limited by the following restrictions:

   a. You may distribute, publicly display, publicly perform, or
      publicly digitally perform the Work only under the terms of this
      License, and You must include a copy of, or the Uniform Resource
      Identifier for, this License with every copy or phonorecord of
      the Work You distribute, publicly display, publicly perform, or
      publicly digitally perform. You may not offer or impose any
      terms on the Work that alter or restrict the terms of this
      License or the recipients' exercise of the rights granted
      hereunder. You may not sublicense the Work. You must keep intact
      all notices that refer to this License and to the disclaimer of
      warranties. You may not distribute, publicly display, publicly
      perform, or publicly digitally perform the Work with any
      technological measures that control access or use of the Work in
      a manner inconsistent with the terms of this License
      Agreement. The above applies to the Work as incorporated in a
      Collective Work, but this does not require the Collective Work
      apart from the Work itself to be made subject to the terms of
      this License. If You create a Collective Work, upon notice from
      any Licensor You must, to the extent practicable, remove from
      the Collective Work any reference to such Licensor or the
      Original Author, as requested. If You create a Derivative Work,
      upon notice from any Licensor You must, to the extent
      practicable, remove from the Derivative Work any reference to
      such Licensor or the Original Author, as requested.

   b. If you distribute, publicly display, publicly perform, or
      publicly digitally perform the Work or any Derivative Works or
      Collective Works, You must keep intact all copyright notices for
      the Work and give the Original Author credit reasonable to the
      medium or means You are utilizing by conveying the name (or
      pseudonym if applicable) of the Original Author if supplied; the
      title of the Work if supplied; to the extent reasonably
      practicable, the Uniform Resource Identifier, if any, that
      Licensor specifies to be associated with the Work, unless such
      URI does not refer to the copyright notice or licensing
      information for the Work; and in the case of a Derivative Work,
      a credit identifying the use of the Work in the Derivative Work
      (e.g., "French translation of the Work by Original Author," or
      "Screenplay based on original Work by Original Author"). Such
      credit may be implemented in any reasonable manner; provided,
      however, that in the case of a Derivative Work or Collective
      Work, at a minimum such credit will appear where any other
      comparable authorship credit appears and in a manner at least as
      prominent as such other comparable authorship credit.

5. Representations, Warranties and Disclaimer

UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING,
LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR
WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED,
STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF
TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE,
NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY,
OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT
DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED
WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY
   APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY
   LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE
   OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE
   WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
   DAMAGES.

7. Termination

   a. This License and the rights granted hereunder will terminate
      automatically upon any breach by You of the terms of this
      License. Individuals or entities who have received Derivative
      Works or Collective Works from You under this License, however,
      will not have their licenses terminated provided such
      individuals or entities remain in full compliance with those
      licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any
      termination of this License.

   b. Subject to the above terms and conditions, the license granted
      here is perpetual (for the duration of the applicable copyright
      in the Work). Notwithstanding the above, Licensor reserves the
      right to release the Work under different license terms or to
      stop distributing the Work at any time; provided, however that
      any such election will not serve to withdraw this License (or
      any other license that has been, or is required to be, granted
      under the terms of this License), and this License will continue
      in full force and effect unless terminated as stated above.

8. Miscellaneous

   a. Each time You distribute or publicly digitally perform the Work
      or a Collective Work, the Licensor offers to the recipient a
      license to the Work on the same terms and conditions as the
      license granted to You under this License.

   b. Each time You distribute or publicly digitally perform a
      Derivative Work, Licensor offers to the recipient a license to
      the original Work on the same terms and conditions as the
      license granted to You under this License.

   c. If any provision of this License is invalid or unenforceable
      under applicable law, it shall not affect the validity or
      enforceability of the remainder of the terms of this License,
      and without further action by the parties to this agreement,
      such provision shall be reformed to the minimum extent necessary
      to make such provision valid and enforceable.

   d. No term or provision of this License shall be deemed waived and
      no breach consented to unless such waiver or consent shall be in
      writing and signed by the party to be charged with such waiver
      or consent.

   e. This License constitutes the entire agreement between the
      parties with respect to the Work licensed here. There are no
      understandings, agreements or representations with respect to
      the Work not specified here. Licensor shall not be bound by any
      additional provisions that may appear in any communication from
      You. This License may not be modified without the mutual written
      agreement of the Licensor and You.

Creative Commons is not a party to this License, and makes no warranty
whatsoever in connection with the Work. Creative Commons will not be
liable to You or any party on any legal theory for any damages
whatsoever, including without limitation any general, special,
incidental or consequential damages arising in connection to this
license. Notwithstanding the foregoing two (2) sentences, if Creative
Commons has expressly identified itself as the Licensor hereunder, it
shall have all rights and obligations of Licensor.

Except for the limited purpose of indicating to the public that the
Work is licensed under the CCPL, neither party will use the trademark
"Creative Commons" or any related trademark or logo of Creative
Commons without the prior written consent of Creative Commons. Any
permitted use will be in compliance with Creative Commons'
then-current trademark usage guidelines, as may be published on its
website or otherwise made available upon request from time to time.

Creative Commons may be contacted at http://creativecommons.org/.

====================================================================

Предметный указатель

Symbols

###
TODO: More indexterms!, Об этой книге

C

Concurrent Versions System (CVS), Об этой книге

S

Subversion
history of, История Subversion
svn
subcommands
add, svn add
blame, svn blame
cat, svn cat
checkout, svn checkout
cleanup, svn cleanup
commit, svn commit
copy, svn copy
delete, svn delete
diff, svn diff
export, svn export
help, svn help
import, svn import
info, svn info
list, svn list
lock, svn lock
log, svn log
merge, svn merge
mkdir, svn mkdir
move, svn move
propdel, svn propdel
propedit, svn propedit
propget, svn propget
proplist, svn proplist
propset, svn propset
resolved, svn resolved
revert, svn revert
status, svn status
switch, svn switch
unlock, svn unlock
update, svn update
svnadmin
subcommands
create, svnadmin create
deltify, svnadmin deltify
dump, svnadmin dump
help, svnadmin help
hotcopy, svnadmin hotcopy
list-dblogs, svnadmin list-dblogs
list-unused-dblogs, svnadmin list-unused-dblogs
load, svnadmin load
lslocks, svnadmin lslocks
lstxns, svnadmin lstxns
recover, svnadmin recover
rmlocks, svnadmin rmlocks
rmtxns, svnadmin rmtxns
setlog, svnadmin setlog
verify, svnadmin verify
svnlook
subcommands
author, svnlook author
cat, svnlook cat
changed, svnlook changed
date, svnlook date
diff, svnlook diff
dirs-changed, svnlook dirs-changed
help, svnlook help
history, svnlook history
info, svnlook info
lock, svnlook lock
log, svnlook log
propget, svnlook propget
proplist, svnlook proplist
tree, svnlook tree
uuid, svnlook uuid
youngest, svnlook youngest
svnversion, svnversion

Русский глоссарий

Переводятся единожды

Concurrent Versions System

система параллельного управления версиями

Перевод даётся в сноске при первом употреблении. Далее используется сокращённое английское название (акроним).
Application Program Interface

интерфейс прикладного программирования

Перевод даётся в сноске при первом употреблении. Далее используется сокращённое английское название (акроним).

Не переводятся

Windows
Не переводится
Unix
Не переводится
Subversion
Не переводится
Cygwin
Не переводится
Apache
Не переводится
Apache Portable Runtime
Не переводится
Java Runtime Environment
Не переводится
Internationalized Resource Identifiers
Не переводится
Uniform Resource Identifiers
Не переводится
Uniform Resource Locator
Не переводится

A

access

доступ

local ~

локальный доступ

См. также access.

anonymous ~

анонимный доступ

См. также access.

atomic

атомарный

~ commit

атомарная фиксация

См. также atomic, commit.

~ transaction

атомарная операция

См. также atomic.

autoversioning

автоматическое управление версиями

architecture

архитектура

authentication

установление личности

authorization

проверка прав доступа

B

binary

бинарный

~ package

бинарный пакет

См. также binary.

blame

ответственное лицо

branch

ветвь

~ing

ветвление

См. также branch.

C

change

изменение

~set

набор изменений

См. также change.

tracking ~s

отслеживание изменений

См. также change.

check in

публиковать, публикация изменений

См. также check out.

check out

создавать рабочую копию

См. также check in.

client

клиент

~ program

программа-клиент

См. также client, program.

code

код

source ~

исходный код [программы]

См. также code.

command

команда

sub~

подкоманда

См. также command.

command line

командная строка

~ interface

интерфейс командной строки

См. также command line, interface.

~ tool

программа, предназначенная для командной строки

уточнить по контексту

См. также command.

commit

фиксация

См. также repository.

community

сообщество

configure

настраивать

configuration

настройки

См. также configure.

conflict

противоречие

~ resolution

разрешение противоречий

См. также conflict.

convention

соглашение

copy

копия

копировать

working ~

рабочая копия

См. также copy.

copy-modify-merge

"скопировал-изменил-слил"

См. также copy, merge.

current

текущий

D

demon

демон

~ process

процесс-демон

См. также demon.

data

данные

meta~

метаданные

См. также data.

database

база данных

developer

разработчик

См. также ~mer.

directory

каталог

administrative ~

служебный каталог

См. также directory.

diff

различие

unified ~

единый формат записи различий

См. также diff.

disconnected operation

операция, не требующая подключения к серверу

dowload

загрузка

drive

диск

~ name

имя диска

См. также drive.

E

email

электронная почта

environment

рабочая среда

emulation ~

среда эмуляции

См. также environment.

~ variable

переменная рабочей среды

См. также environment.

external definition

внешняя зависимость

F

feature

особенность

file

файл

~-sharing

совместный доступ к файлам

См. также file.

filter

фильтр

фильтрация

G

Graphical User Interface

графический интерфейс пользователя

Перевод даётся в сноске при первом употреблении. Далее используется сокращённое английское название.
Global Revision Number

глобальный номер правки

H

history

история

I

icon

значок (на экране)

символ (в тексте)

import

вносить, заносить

interface

интерфейс

install

установка (программного обеспечения)

~ method

способ установки

См. также install.

~er

программа установки

См. также install.

K

key

имя (переменной)

L

library

библиотека

lightweight

легкий

local

местный

lock

блокировать

~ing

блокировка

См. также lock.

lock-modify-unlock

"заблокировал-изменил-разблокировал"

См. также lock.

log

сообщения истории изменений

См. также log message.

M

mail

почта

module

модуль

plug-in ~

подключаемый модуль расширения

Например, https модуль для Apache

См. также module.

merge

слияние

message

сообщение

log message

сообщение истории изменений

См. также log.

commit message

сообщение истории изменений

пояснение изменений

пояснение фиксируемых изменений

См. также commit.

mount

монтировать

to ~ share

монтировать совместно используемый ресурс

См. также mount.

N

network

сеть

~ layer

сетевой уровень

См. также network.

O

offline

автономный

~ operation

автономная операция

См. также offline.

option

настройка

опция

configuration option

настройка конфигурации

См. также option.

out-of-date

устаревший

overlap

наложение (при описании состояния)

~ing

пересекающийся

См. также overlap.

перекрытие (при описании процесса)

См. также overlap.

P

patch

"заплатка"

path

путь

port

порт

program

программа

программировать

~mer

программист

См. также program.

~ing

программирование

См. также program.

property

свойство

~ support

поддержка свойств

unversioned properties

неверсионное свойство

protocol

протокол

public

открытый

доступный

~ API

открытый API

См. также public, Application Program Interface.

R

read

чтение

read-only

только для чтения

repository

хранилище

central ~

центральное хранилище

См. также repository.

remote ~

удаленное хранилище

См. также remote, repository.

~ location

место размещения хранилища

См. также repository.

snapshot of ~

снимок хранилища

См. также repository.

remote

удаленный

request

запрос

revert

возврат к прежнему состоянию

вернуть прежнее состояние

revision

правка

версия

~ number

номер правки

номер версии

См. также revision.

mixed ~

смешанная правка

См. также revision.

runtime

среда исполнения

~ option

настройка среды исполнения

См. также runtime.

~ variable

переменная среды исполнения

См. также runtime.

S

separator

символ-разделитель

path ~

символ-разделитель компонентов путевого имени

См. также separator.

serialization

сериализация

server

сервер

file ~

файл-сервер

См. также server.

share

совместно используемый ресурс

DAV ~

совместно используемый ресурс DAV

См. также share.

network ~

совместно используемый сетевой ресурс

См. также share, network.

slash

символ косой черты

backward ~

символ обратной косой черты

См. также slash.

forward ~

См. slash.

software

программное обеспечение

collaboration ~

программное обеспечение для совместной работы

См. также software.

open-source ~

программное обеспечение с открытым исходным кодом

См. также software.

free ~

свободно распространяемое программное обеспечение

См. также software.

Software Configuration Management

система управления конфигурацией программного обеспечения

См. также software.

standalone

самостоятельный

status

статус

состояние

status listing

список состояния файлов

См. также status.

style

стиль

programming ~

стиль программирования

См. также style.

subdirectory

вложенный каталог

подкаталог

См. также directory.

support

поддержка

switch

параметр командной строки

sysadmin

системный администратор

T

tag

метка

~ging

назначение метки

См. также tag.

timestamp

отметка времени

top-level

верхний уровень

верхнего уровня

относящийся к верхнему уровню
tree

дерево

external ~

внешнее дерево

См. также tag.

troubleshooting

поиск и исправление неисправностей

tunnel

тоннель

прокладывать тоннель

~ing

туннелирование

U

unblock

разблокировать

Unix-like

Unix-подобный

URL schema

схема URL

update

обновление

обновлять

up-to-date

обновленный

актуальный

V

value

значение

vendor

поставщик

~ branch

ветвь поставщика

version

версия

~ control

управление версиями

См. также version.

~ing model

модель управления версиями

См. также version.

~ed directory

версионированный каталог

См. также version.

directory ~ing

версионирование каталогов

См. также version.

~ed metadata

версионированные метаданные

См. также version, meta~.

~ed data

версионированные данные

См. также version.

W

write

запись

U

undo

отмена

to ~ changes

отменять внесенные изменения

См. также undo.

user

пользователь

advanced ~

продвинутый пользователь