Мы уже рассмотрели как Subversion сохраняет и получает разные версии файлов и директорий из хранилища. Целые главы были посвящены этой самой фундаментальной части функциональных возможностей этого инструмента. И если поддержка версионирования этим ограничится, Subversion все равно останется полноценным инструментом с точки зрения управления версиями. Однако версионирование этим не ограничивается.
Дополнительно к версионированнию директорий и файлов, Subversion предоставляет для каждой версионированной директории и файла интерфейс для добавления, изменения и удаления версионированных метаданных. К этим метаданным мы обращаемся как к свойствам, присоединенным к каждому элементу рабочей копии, которые можно представить в виде таблицы с двумя столбцами, которая сопоставляет имена свойств соответствующим значениям. Вообще, имена и значения свойств могут быть тем, чем вы хотите чтобы они были, за исключением того, что имена должны быть читаемым текстом. И лучшим из всего является то, что они тоже версионированы также как и текстовое содержимое файлов. Можно также просто как и для текстовых изменений изменять, фиксировать и отменять изменения свойств. При обновлении рабочей копии также получаются и изменения свойств.
В этом разделе мы рассмотрим полезность — как для пользователя, так и для самой Subversion — поддержки свойств. Вы узнаете о командах svn, относящихся к свойствам и том как модификация свойств влияет на привычный рабочий цикл. Надеемся, вы убедитесь в том, что свойства в Subversion расширяют возможности контроля версий.
Свойства могут быть очень полезной добавкой к рабочей копии. Фактически, сама Subversion использует свойства для хранения служебной информации и определения того, какие действия необходимо выполнить. Подобным образом и вы можете использовать свойства для своих целей. Конечно, все для чего можно использовать свойства можно делать, используя обычные версионированные файлы, однако обратите внимание на приведенный ниже пример использования Subversion-свойств.
Скажем, вы хотите разработать веб-сайт, содержащий много
цифровых фотографий и показывающий их с подписью и датой.
Набор этих фотографий постоянно изменяется и вы захотите
по возможности максимально автоматизировать этот сайт. Фотографии
могут быть большого размера и как обычно делают на таких
сайтах, для своих посетителей вам будет необходимо показывать
миниатюры изображений. Сделать это вы можете с помощью обычных
файлов. То есть рядом, в директории, вы можете иметь файлы
image123.jpg
и
image123-thumbnail.jpg
. Подобным образом,
отдельно от графического файла, можно хранить и дату. В результате
ваше дерево файлов будет захламлено и будет многократно увеличиваться
при каждом добавлении на сайт фотографии.
Представим эту же ситуацию при использовании Subversion-свойств
файлов. Допустим, имеется файл image123.jpg
и у этого файла установлено свойство
caption
, datestamp
и даже
thumbnail
. В этом случае рабочая копия выглядит
гораздо более управляемо — фактически она будет выглядеть
так, как-будто она ничего кроме графических файлов не содержит.
Однако ваш скрипт автоматизации знает больше. Он знает, что может
воспользоваться svn (а еще лучше языковой обвязкой
Subversion — см. «Using Languages Other than C and C++») для получения
дополнительной, необходимой для показа на сайте информации,
не занимаясь чтением индексного файла или играми с путями
файлов.
Как (и для чего) использовать Subversion-свойства вы решаете самостоятельно. Как уже говорилось, Subversion имеет свои применения свойств, которые мы рассмотрим в этой главе немного позже. А с начала давйте поговорим как работать со свойствами используя программу svn.
Команда svn предоставляет несколько способов добавления или изменения свойств файлов и директорий. Свойства с короткими, читаемыми значениями, наверное проще всего добавить указав имя и значение свойства в командной строке подкоманды propset.
$ svn propset copyright '(c) 2003 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' $
Для имен свойств существует ряд ограничений. Имя свойства должно
начинаться с буквы, двоеточия (:
) или подчеркивания
(_
); дальше можно использовать цифры, тире
(-
) и точки (.
).
[35]
Дополнительно к команде 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) 2002 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) 2003 Red-Bean Software
Существует даже вариант команды proplist,
который перечисляет как имена, так и значения свойств. Просто
добавьте параметр --verbose
(-v
).
$ svn proplist --verbose calc/button.c Properties on 'calc/button.c': copyright : (c) 2003 Red-Bean Software license : ================================================================ Copyright (c) 2003 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) 2003 Red-Bean Software license : $
Для полного удаления свойств необходимо использовать команду propdel. Ее синтаксис такой же как и у других команд работы со свойствами:
$ svn propdel license calc/button.c property 'license' deleted from ''. $ svn proplist --verbose calc/button.c Properties on 'calc/button.c': copyright : (c) 2003 Red-Bean Software $
Теперь, когда вы познакомились со всеми 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) 2003 Red-Bean Software $
Обратите внимание на то, что подкоманда status
показывает M
не в первой, а во второй колонке.
Это потому, что в calc/button.c
изменились
свойства, а текстовое содержимое нет. Если бы мы изменили и то и
другое, в первой колонке то же была бы буква M
(см. «svn status»).
Кроме того нужно помнить о нестандартном подходе, используемом Subversion при выводе различий для свойств. Безусловно, можно запустить svn diff перенправить вывод, для создания работоспособного файла отличий. Програма patch будет просто игнорировать различия свойств — как правило, она игнорирует любой мусор, который неможет обработать. К сожалению, это значит, что для полного применения отличий, сгенерированных svn diff, изменения свойств нужно вносить в ручную.
Как видите, наличие измененных свойств никак не отражается на привычном рабочем цикле. Операции обновления рабочей копии, проверки статуса файлов и директорий, вывод сообщений о сделанных изменениях и фиксация этих измениий в хранилище никак не зависят от наличия или отсутствия свойств. У svn просто имеется несколько дополнительных подкоманд для внесения изменений в свойства однако это просто достойное внимания отличие.
У Subversion нет каких то отдельных правил для свойств
— использовать их можно как угодно. Единственно
что Subversion требует от вас не использовать в названиях
свойств префикс svn:
. Потому, что это
пространство имен для ее личного использования. Subversion
выделяет несколько свойств, имеющих особый магический эффект
для файлов и директорий, для которых они установлены.
В этом разделе мы раскроем тайну и расскажем, как эти
специальные свойства делают жизнь немного проще.
Свойство svn:executable
для версионированного
файла контролирует в полуавтоматическом режиме бит файловой
системы, разрешающий исполнение. Это свойство не имеет определенного
значения — просто его наличие говорит о необходимости для
Subversion выставлять бит разрешения выполнения. Удаление этого
свойства востанавливает полный контроль операционной системы над
битом выполнения.
На многих операционных системах возможность выполнения файла
как команды определяется битом разрешения выполнения. Обычно по
умолчанию этот бит не установлен и для файлов которым это
необходимо, он должен быть явно установлен пользователем.
Файлы в рабочей копии при обновлении создаются каждый раз
заново если во время обновления получается новая версия.
Это значит, что вы можете установить бит разрешения выполнения,
а если при выполнении обновления обновился и этот файл,
бит разрешения выполнения может оказаться опять сброшеным.
Для таких случаев Subversion и предлагает использовать
свойство svn:executable
, как способ сохранения
бита разрешения выполнения.
Это свойство не имеет ни какой силы на таких файловых
системах, как FAT32 и NTFS, не имеющих понятия бита разрешения
выполнения[37]. Кроме того,
так как оно не имеет определенного значения, при его установке
Subversion принудительно устанавливает значение
*
. Наконец, это свойство действительно только
для файлов, не для директорий.
Свойство svn:mime-type
имеет в Subversion
несколько значений. Кроме общего назначения хранения информации о
файле согласно Универсальному Расширению Интернет Почты (MIME),
значение этого свойства определяет некоторые правила поведения самой
Subversion.
Например, если у файла свойство svn:mime-type
имеет не текстовый MIME-тип (проще говоря, кроме некоторых
исключений, не начинается с чего то вроде text/
)
Subversion предпологает бинарное — не читаемое —
содержимое файла. Одной из положительных характеристик, предлагаемых
Subversion, является контекстное, построчное объединение изменений,
полученых с сервера при обновлении, с рабочим файлом. Однако файлы,
считающиеся бинарными, не имеют понятия «строка».
Следовательно для таких файлов, при обновлении, Subversion не
пытается выполнить контекстное объединение. Вместо этого, при
локально измененной рабочей копии бинарного файла, для которого
выполняется обновление, файл рабочей копии переименовывается
добавлением расширения .orig
, после чего,
под первоначальным именем, Subversion сохраняет новую рабочую копию,
содержащую изменения, полученные при обновлении и не содержащую ваших
собственных изменений. Такой подход используется для того, чтобы защитить
пользователя от попыток контекстного объединения файлов, которые просто
не могут быть контекстно объединены.
Кроме того, если уствновлено свойство svn:mime-type
,
Apache-модуль будет использовать это значение при заполнении HTTP
заголовка Content-type:
при ответе на GET-запросы.
Это имеет ключевой значение при определении того, как показывать файл
при просмотре хранилища используя web-браузер.
The svn:ignore
property contains a
list of file patterns which certain Subversion operations
will ignore. Perhaps the most commonly used special
property, it works in conjunction with the
global-ignores
run-time configuration
option (see «Config») to
filter unversioned files and directories out of commands
svn status, svn
add, and svn import.
The rationale behind the svn:ignore
property is easily explained. Subversion does not assume
that every file or subdirectory in a working copy directory
is intended for version control. Resources must be
explicitly placed under Subversion's management using the
svn add or svn import
commands. As a result, there are often many resources in a
working copy that are not versioned.
Now, the svn status command displays
as part of its output every unversioned file or subdirectory
in a working copy that is not already filtered out by the
global-ignores
option (or its built-in
default value). This is done so that users can see if
perhaps they've forgotten to add a resource to version
control.
But Subversion cannot possibly guess the names of every resource that should be ignored. Also, quite often there are things that should be ignored in every working copy of a particular repository. To force every user of that repository to add patterns for those resources to their run-time configuration areas would be not just a burden, but has the potential to clash with the configuration needs of other working copies that the user has checked out.
The solution is to store ignore patterns that are unique to the resources likely to appear in a given directory with the directory itself. Common examples of unversioned resources that are basically unique to a directory, yet likely to appear there, include output from program compilations. Or—to use an example more appropriate to this book—the HTML, PDF, or PostScript files generated as the result of a conversion of some source DocBook XML files to a more legible output format.
For this purpose, the svn:ignore
property is the solution. Its value is a multi-line
collection of file patterns, one pattern per line. The
property is set on the directory in which you wish the
patterns to be applied.
[38]
For example, say you have the following output from
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
In this example, you have made some property
modifications to button.c
, but in your
working copy you also have some unversioned files:
the latest calculator
program
that you've compiled from your source code, a source file
named data.c
, and a set of debugging
output log files. Now, you know that your build system
always results in the calculator
program being generated.
[39]
And you know that your test suite always leaves those
debugging log files lying around. These facts are true for
all working copies, not just your own. And you know that
you aren't interested in seeing those things every time you
run svn status. So you use svn
propedit svn:ignore calc to add some ignore
patterns to the calc
directory. For
example, you might add this as the new value of the
svn:ignore
property:
calculator debug_log*
After you've added this property, you will now have a
local property modification on the calc
directory. But notice what else is different about your
svn status output:
$ svn status M calc M calc/button.c ? calc/data.c
Now, all the cruft is missing from the output! Of course, those files are still in your working copy. Subversion is simply not reminding you that they are present and unversioned. And now with all the trivial noise removed from the display, you are left with more interesting items—such as that source code file that you probably forgot to add to version control.
If you want to see the ignored files, you can pass the
--no-ignore
option to Subversion:
$ svn status --no-ignore 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
The list of patterns to ignore is also used by svn add and svn import. Both of these operations involve asking Subversion to begin managing some set of files and directories. Rather than force the user to pick and choose which files in a tree she wishes to start versioning, Subversion uses the ignore patterns to determine which files should not be swept into the version control system as part of a larger recursive addition or import operation.
Subversion has the ability to substitute keywords—pieces of useful, dynamic information about a versioned file—into the contents of the file itself. Keywords generally describe information about the last time the file was known to be modified. Because this information changes each time the file changes, and more importantly, just after the file changes, it is a hassle for any process except the version control system to keep the data completely up-to-date. Left to human authors, the information would inevitably grow stale.
For example, say you have a document in which you would
like to display the last date on which it was modified. You
could burden every author of that document to, just before
committing their changes, also tweak the part of the
document that describes when it was last changed. But
sooner or later, someone would forget to do that. Instead
simply ask Subversion to perform keyword substitution on the
LastChangedDate
keyword. You control
where the keyword is inserted into your document by placing
a keyword anchor at the desired
location in the file. This anchor is just a string of text
formatted as
$
KeywordName
$
.
All keywords are case-sensitive where they appear as
anchors in files: you must use the correct capitalization in
order for the keyword to be expanded. You should consider the
value of the svn:keywords
property to be
case-sensitive too—certain keyword names will be recognized
regardless of case, but this behavior is deprecated.
Subversion defines the list of keywords available for substitution. That list contains the following five keywords, some of which have aliases that you can also use:
Date
This keyword describes the last time the file was
known to have been changed in the repository, and
looks something like $Date:
2002-07-22 21:42:37 -0700 (Mon, 22 Jul 2002)
$
. It may also be specified as
LastChangedDate
.
Revision
This keyword describes the last known revision in
which this file changed in the repository, and looks
something like $Revision: 144 $
.
It may also be specified as
LastChangedRevision
or
Rev
.
Author
This keyword describes the last known user to
change this file in the repository, and looks
something like $Author: harry $
.
It may also be specified as
LastChangedBy
.
HeadURL
This keyword describes the full URL to the latest
version of the file in the repository, and looks
something like $HeadURL:
http://svn.collab.net/repos/trunk/README $
.
It may be abbreviated as
URL
.
Id
This keyword is a compressed combination of the
other keywords. Its substitution looks something like
$Id: calc.c 148 2002-07-28 21:30:43Z sally
$
, and is interpreted to mean that the file
calc.c
was last changed in revision
148 on the evening of July 28, 2002 by the user
sally
.
Simply adding keyword anchor text to your file does nothing special. Subversion will never attempt to perform textual substitutions on your file contents unless explicitly asked to do so. After all, you might be writing a document [40] about how to use keywords, and you don't want Subversion to substitute your beautiful examples of un-substituted keyword anchors!
To tell Subversion whether or not to substitute keywords
on a particular file, we again turn to the property-related
subcommands. The svn:keywords
property,
when set on a versioned file, controls which keywords will
be substituted on that file. The value is a space-delimited
list of the keyword names or aliases found in the previous
table.
For example, say you have a versioned file named
weather.txt
that looks like
this:
Here is the latest report from the front lines. $LastChangedDate$ $Rev$ Cumulus clouds are appearing more frequently as summer approaches.
With no svn:keywords
property set on
that file, Subversion will do nothing special. Now, let's
enable substitution of the
LastChangedDate
keyword.
$ svn propset svn:keywords "Date Author" weather.txt property 'svn:keywords' set on 'weather.txt' $
Now you have made a local property modification on the
weather.txt
file. You will see no
changes to the file's contents (unless you made some of your
own prior to setting the property). Notice that the file
contained a keyword anchor for the Rev
keyword, yet we did not include that keyword in the property
value we set. Subversion will happily ignore requests to
substitute keywords that are not present in the file, and
will not substitute keywords that are not present in the
svn:keywords
property value.
Immediately after you commit this property change,
Subversion will update your working file with the new
substitute text. Instead of seeing your keyword anchor
$LastChangedDate$
, you'll see its
substituted result. That result also contains the name of
the keyword, and continues to be bounded by the dollar sign
($
) characters. And as we predicted, the
Rev
keyword was not substituted because
we didn't ask for it to be.
Note also that we set the svn:keywords
property to «Date Author» yet the keyword
anchor used the alias $LastChangedDate$
and still expanded correctly.
Here is the latest report from the front lines. $LastChangedDate: 2002-07-22 21:42:37 -0700 (Mon, 22 Jul 2002) $ $Rev$ Cumulus clouds are appearing more frequently as summer approaches.
If someone else now commits a change to
weather.txt
, your copy of that file
will continue to display the same substituted keyword value
as before—until you update your working copy. At that
time the keywords in your weather.txt
file will be re-substituted with information that
reflects the most recent known commit to that file.
Unless otherwise noted using a versioned file's
svn:mime-type
property, Subversion
assumes the file contains human-readable data. Generally
speaking, Subversion only uses this knowledge to determine
if contextual difference reports for that file are
possible. Otherwise, to Subversion, bytes are bytes.
This means that by default, Subversion doesn't pay any
attention to the type of end-of-line (EOL)
markers used in your files. Unfortunately,
different operating system use different tokens to represent
the end of a line of text in a file. For example, the usual
line ending token used by software on the Windows platform
is a pair of ASCII control characters—carriage return
(CR
) and line feed
(LF
). Unix software, however, just uses
the LF
character to denote the end of a
line.
Not all of the various tools on these operating systems
are prepared to understand files that contain line endings
in a format that differs from the native line
ending style of the operating system on which
they are running. Common results are that Unix programs
treat the CR
character present in Windows
files as a regular character (usually rendered as
^M
), and that Windows programs combine
all of the lines of a Unix file into one giant line because
no carriage return-linefeed (or CRLF
)
character combination was found to denote the end of
line.
This sensitivity to foreign EOL markers can become frustrating for folks who share a file across different operating systems. For example, consider a source code file, and developers that edit this file on both Windows and Unix systems. If all the developers always use tools which preserve the line ending style of the file, no problems occur.
But in practice, many common tools either fail to properly read a file with foreign EOL markers, or they convert the file's line endings to the native style when the file is saved. If the former is true for a developer, he has to use an external conversion utility (such as dos2unix or its companion, unix2dos) to prepare the file for editing. The latter case requires no extra preparation. But both cases result in a file that differs from the original quite literally on every line! Prior to committing his changes, the user has two choices. Either he can use a conversion utility to restore the modified file to the same line ending style that it was in before his edits were made. Or, he can simply commit the file—new EOL markers and all.
The result of scenarios like these include wasted time and unnecessary modifications to committed files. Wasted time is painful enough. But when commits change every line in a file, this complicates the job of determining which of those lines were changed in a non-trivial way. Where was that bug really fixed? On what line was a syntax error introduced?
The solution to this problem is the
svn:eol-style
property. When this
property is set to a valid value, Subversion uses it to
determine what special processing to perform on the file so
that the file's line ending style isn't flip-flopping with
every commit that comes from a different operating
system. The valid values are:
native
This causes the file to contain the EOL markers
that are native to the operating system on which
Subversion was run. In other words, if a user on a
Windows machine checks out a working copy that
contains a file with an
svn:eol-style
property set to
native
, that file will contain
CRLF
EOL markers. A Unix user
checking out a working copy which contains the same
file will see LF
EOL markers in his
copy of the file.
Note that Subversion will actually store the file
in the repository using normalized
LF
EOL markers regardless of the
operating system. This is basically transparent to
the user, though.
CRLF
This causes the file to contain
CRLF
sequences for EOL markers,
regardless of the operating system in use.
LF
This causes the file to contain
LF
characters for EOL markers,
regardless of the operating system in use.
CR
This causes the file to contain
CR
characters for EOL markers,
regardless of the operating system in use. This line
ending style is not very common. It was used on older
Macintosh platforms (on which Subversion doesn't even
run).
The svn:externals
property contains
instructions for Subversion to populate a versioned
directory with one or more other checked-out Subversion
working copies. For more information on this keyword and
its use, see «Externals Definitions».
The svn:special
property is the only
svn:
property that isn't meant to be
directly set or modified by users. Subversion automatically
sets this property whenever a «special» object
is scheduled for addition, such as a symbolic link. The
repository stores an svn:special
object as
an ordinary file. However, when a client sees this property
during checkouts or updates, it interprets the contents of
the file and translates the item back into the special type
of object. In versions of Subversion current at the time of
writing, only versioned symbolic links have this property
attached, but in future versions of Subversion other special
types of nodes will probably use this property as
well.
Note: Windows clients don't have symbolic links, and
thus ignore any svn:special
files coming
from a repository that claim to be symbolic links. On
Windows, the user ends up with an ordinary versioned file in
the working copy.
This property is used to signify that the file it's
attached to ought to be locked before editing. The value of
the property is irrelevant; Subversion will normalize its
value to *
. When present, the file will
be read-only unless 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.
To learn more about how, when, and why this property should be used, see «Lock Communication».
Properties are a powerful feature of Subversion, acting as key components of many Subversion features discussed elsewhere in this and other chapters—textual diff and merge support, keyword substitution, newline translation, etc. But to get the full benefit of properties, they must be set on the right files and directories. Unfortunately, that can be a step easily forgotten in the routine of things, especially since failing to set a property doesn't usually result in an obvious error condition (at least compared to, say, failing to add a file to version control). To help your properties get applied to the places that need them, Subversion provides a couple of simple but useful features.
Whenever you introduce a file to version control using the
svn add or svn import
commands, Subversion runs a very basic heuristic to determine
if that file consists of human-readable or non-human-readable
content. If the latter is the decision made, Subversion will
automatically set the svn:mime-type
property on that file to
application/octet-stream
(the generic
«this is a collection of bytes» MIME type). Of
course, if Subversion guesses incorrectly, or if you wish to
set the svn:mime-type
property to something
more precise—perhaps image/png
or
application/x-shockwave-flash
—you can
always remove or edit that property.
Subversion also provides the auto-props feature, which
allows you to create mappings of filename patterns to property
names and values. These mappings are made in your runtime
configuration area. They again affect adds and imports, and
not only can override any default MIME type decision made by
Subversion during those operations, they can also set
additional Subversion or custom properties, too. For example,
you might create a mapping that says that any time you add
JPEG files—ones that match the pattern
*.jpg
—Subversion should automatically
set the svn:mime-type
property on those
files to image/jpeg
. Or perhaps any files
that match *.cpp
should have
svn:eol-style
set to
native
, and svn:keywords
set to Id
. Auto-prop support is perhaps
the handiest property related tool in the Subversion toolbox.
See «Config» for more about
configuring that support.
[35] Если вы знакомы с XML, то синтаксис XML "Name" использует практически тот же ASCII набор.
[36] Исправление в лог сообщениях орфографических, грамматических
ошибок, «просто ошибочных» записей, наверно,
самые распространенные случаи использования параметра
--revprop
.
[37] Для определения исполняемых файлов,
файловая система Windows использует расширения файлов (такие, как
.EXE
, .BAT
и
.COM
).
[38] The patterns are strictly for that directory—they do not carry recursively into subdirectories.
[39] Isn't that the whole point of a build system?
[40] … or maybe even a section of a book …