Пятница, 19.04.2024, 21:21
Админка
Приветствую Вас Гость | RSS
Главная Каталог статей Регистрация Вход
Меню сайта

Категории раздела
Subversion [3]

Поиск

Статистика

Онлайн всего: 1
Гостей: 1
Пользователей: 0

Главная » Статьи » Системы управления версиями » Subversion

Установка и настройка VisualSVN Server под Windows Server 2003 Enterprise. Часть 2

Далее Рассмотрим, как можно сформировать новый путь расположения корневого репозитория. На Рисунке ниже, в процессе инсталляции VisualSVN сервера, мы по умолчанию согласились, что корень репозитория будет находиться в C:\Repositories. Чтобы его поменять, необходимо запустить консоль VisualSVN Manager и произвести следующие действия. Изменить путь C:\Repositories на другой к примеру C:\Repos (можно выбрать другой физический диск), далее перенесите все ваши репозитории из C:\Repositories в C:\Repos, рестартуйте из консоли VisualSVN сервис. После рестартинга сервиса, автоматически подхватит содержимое корня репозитория. Как видите - всё просто.



1. Генерация своего сертификата для работы с репозиториями по защищенному каналу.

В VisualSVN Manager выберите правой кнопкой мыши Properties (Свойства), далее вкладка выберите  Certificate и Change Certificate






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



Выбираем Create New self-signed certificate











Результатом будет наш готовый сертификат. Сертификат выдается на 1 год.



2. Управление Хуками.

До и после каждого события (commit, lock, unlock) Subversion выполняет так называемые скрипты-зацепки (hook-scripts). Они располагаются в каталоге имя_репозитория/hooks. Скрипты, выполняющиеся до действия, имеют префикс «pre», а после – соответственно «post-». Так, скрипт, запускающийся перед процессом коммита, будет иметь название «pre-commit», а скрипт, вызывающийся после завершения процедуры коммита – «post-commit» и служат для рассылки сообщений о проведенных в проекте изменениях.

Каждый репозиторий проекта имеет свои скрипты, которые располагаются по путям: C:\Наш_корневой_репозиторий\Имя_Репозитория_проекта\hooks. В нем как правило имеются следующие дефолтные скрипты:

post-commit.tmpl  
post-lock.tmpl  
post-revprop-change.tmpl 
post-unlock.tmpl   
pre-commit.tmpl   
pre-lock.tmpl  
pre-revprop-change.tmpl
pre-unlock.tmpl  
start-commit.tmpl


сюда ожно класть свои хуки, например, шаблон меняется на свой .bat или .exe файл с именем post-commit.bat или post-commit.exe, который и будет запускаться после каждого commit.

Назначение дефолтных скриптов следующее:

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.


Для управления ими используется все тот же VisualSVN Manager.



В VisualSVN Manager'е можно сразу редактировать скрипты.



В составе с VisualSVN Server идет утилита VisualSVNServerHooks.exe для работы с Hook.Формат командной строки утилиты следующий:

VisualSVNServerHooks SUBCOMMAND [ARGS & OPTIONS ...]

Доступные subcommands:

   case-insensitive
   commit-notification
   help (?, h)

пример:

"%VISUALSVN_SERVER%\bin\VisualSVNServerHooks.exe" commit-notification "%1" -r %2 ^
    --from <from-email> --to <to-email> ^
    --smtp-server <smtp-server>

Опции команды commit-notification  следующие:
 
-r [--revision] ARG    Номер ревизии      
--from ARG    E-Mail адрес от кого будут высылать уведомления      
--to ARG    E-MAIL кому TO адрес назначения уведомления      
--smtp-server ARG    Имя SMTP  сервера      
--smtp-port ARG     порт SMTP. По умолчанию используется 25порт      
--smtp-user ARG    Имя SMTP пользователя для авторизации (если такова используется)      
--smtp-password <password>    Пароль для авторизации пользователя через SMTP сервер      
--smtp-ssl    Разрешить использовать защищенную авторизацию SSL       
--encoding <encoding>    Specifies encoding that is used to store text files (commit notifications e-mails will be sent in UTF-8). For example --encoding ISO-8859-1. Current locale settings will be used by default.

Например, отредактируем наш скрипт post-commit.cmd:

VisualSVNServerHooks.exe commit-notification -r %2 --from SBPR1@mydomain.ru --to groupUS1@mydomain.ru --smtp-server 192.168.2.1 "%1"

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

Например, отредактируем наш скрипт pre-commit.cmd (Скрипт проверяющий, что был введен коментарий):

rem file: pre-commit.bat
rem autor: -red-
rem ATTENTION! Before use, setup next 3 strokes for your system
chcp 1251
SET ERRORMSG="ОШИБКА! Введите коментарий!"
SET SVNLOOK="%ProgramFiles%\VisualSVN Server\bin\svnlook.exe"
for /f "tokens=*" %%a in ('%SVNLOOK% log -t %2 %1') do set C=%%a
if defined C (GOTO FINE) else ( echo %ERRORMSG%>&2 )
exit 1
:FINE
exit 0
или

"c:\Program Files\VisualSVN Server\bin\svnlook.exe" log -t %2 %1 | FindStr [a-zA-Z0-9]
IF %ERRORLEVEL% EQU 0 GOTO OK
echo "Commit Comments are Required" >&2
exit 1
:OK
exit 0


Скрипты можно писать на любых языках программирования.

Примеры скриптов можно посмотреть в самих файлах и настроить под свои нужды.
Категория: Subversion | Добавил: Inhibitz (18.05.2009)
Просмотров: 15799 | Рейтинг: 5.0/2 |
Всего комментариев: 0
Добавлять комментарии могут только зарегистрированные пользователи.
[ Регистрация | Вход ]
При копировании статей просьба указывать источник inhibitz.ucoz.ru © 2024