- post-commit-hook.bat (Windows+VisualSVN Server +Trac 0.12) close ticket from commit
- 2 Answers 2
- Subversion Post-Commit Hooks
- 5 Answers 5
- Additional Comments
- SVN hooks: изменение комментария к ревизии
- Что такое hook.
- Изменение комментария к ревизии
- Хук справа.
- Хук слева.
- SVN Post Commit Hook Batch Windows
- 4 Answers 4
- How do I implement the Post Commit Hook with Trac & SVN in a Windows Environment?
- 6 Answers 6
post-commit-hook.bat (Windows+VisualSVN Server +Trac 0.12) close ticket from commit
Windows + VisualSVN Server + Trac 0.12
I want, that tickets automatic close, when commit text have «close #2» (or other command, all the same)
2 Answers 2
Well my friend you are in luck becuase I finally figured out how to do this. I have the same configuration as you, Windows + VisualSVN + Trac. This is what I have gathered and put together from a bunch of places on the net and my experience. Here we go.
Create (import. ) your repository. Just make sure it is there and working properly with VisualSVN. We will call your project TheProject. And say it is located in PathToSVN. Which means if project is in C:\SVN\TheProject. Then PathToSVN is C:\SVN
Make sure you have at least one user if you use Subversion authentication.
Download VisualSVN Trac add-on from: http://www.visualsvn.com/files/VisualSVN-Server-2.5.4.28066-Trac-0.12.3.zip.
N.B. Check http://www.visualsvn.com/server/trac/ if there is a newer version but come back and follow the instructions here. Not the ones there.
Unzip it to %VISUALSVN_SERVER% folder (your VisualSVN installation folder)
Create a folder somewhere for you Trac. e.g. C:\Trac or D:\Trac. We will call it PathToTrac\
Allow «Full Control» access to PathToTrac\ folder for built-in Network Service account (or other account that is used to run VisualSVN Server’s service).
Open the command prompt and execute the command
«%VISUALSVN_SERVER%trac\trac-admin.bat» PathToTrac\TheProject initenv
Use the default settings. Just press enter for all questions.
Execute the following command to add TheProject Subversion repository to the Trac:
«%VISUALSVN_SERVER%trac\trac-admin.bat» PathToTrac\TheProject repository add TheProject PathToSVN\Project svn
If you don’t have python already, Add system variable: PYTHONHOME=%VISUALSVN_SERVER%trac\python
Just make sure PYTHONHOME points to somewhere where we can find python. And look out for spaces at the end of the path. Windows doesn’t like it.
Add the following text to file %VISUALSVN_SERVER%conf\httpd-custom.conf if you use Subversion authentication:
or this text if you use Windows authentication:
MAKE SURE to replace PathToSVN and PathToTrac with the proper paths. In the texts
Restart VisualSVN server. Note down the port where the server is listening at.
Open «http://localhost:port/trac/» If you can see the Trac for your repository you are almost done. Otherwise go back and check if you have missed anything.
Go to your SVN directory and then to your project. PathToSVN\TheProject. e.g. C:\SVN\FirstProject. And you will find a folder name hooks. And in that folder you will find a file name post-commit.cmd. If it is not there then create it.
Add this to post-commit.cmd (just open it with a text editor) and save it.
Download the trac-post-commit-hook file from http://trac.edgewall.org/attachment/wiki/TracMultipleProjects/ComprehensiveSolution/trac-post-commit-hook. Just go to the bottom of the page and click download original. Save it in PathToSVN\TheProject\hooks directory. It should be named trac-post-commit-hook no extension.
Now go to PathToTrac\TheProject\conf directory and open the file trac.ini. Search for repository_dir. Add tht path to your repository as it’s value e.g.
You are Done.
Now you can close or reference tickets directly from your commits like, fixes #1, closes #1 . Read the comments in the trac-post-commit-hook file
Subversion Post-Commit Hooks
I am having some issues getting post-commit hooks to work. Subversion doesn’t appear to be triggering my post-commit hook when I commit a changed file to my repository.
I am using TortoiseSVN and VisualSVN with Subversion, I was able to go into the VisualSVN user interface and create a hook within there that worked however what I would like to do is use the post-commit executable hook in the hooks folder of my installation to execute my hook.
I have changed the name from post-commit.tmpl to post-commit.bat in the /hooks folder of my repository and am just doing a simple update within the batch file:
When I run the batch file on its own it updates my working folder so I am thinking it is not being triggered when I commit for some reason. It doesn’t appear to be a permissions issue since everything is being done locally on my machine however I have set it to run as a network service but still experience the same problem. any suggestions?
5 Answers 5
First of all, all hooks are executed on the SERVER and not on the various client machines. Is that C:\mypath\myworkingcopy on the server? If not, it’s not going to get updated.
Second of all, it’s bad form to do anything in a hook that might take too much time. If your hook needs something more than svnlook , chances are you’re doing it wrong. For example, how long could it take to update that working copy? 10 seconds? 30 seconds? a minute? That’s the added time a developer has to sit and wait for their Subversion commit to complete.
It is much, much better to use something that can respond to commit events and have that do things like working copy updates or deployments to web servers outside of a post-commit hook. I highly recommend Jenkins for this job. Jenkins has several nice features:
- It’s cost effective (you can’t beat free)
- It’s well supported (post a question on Stackoverflow and get a quick response).
- It’s a snap to setup and use.
Now back to your question:
First make sure the hook is running. Add to the bottom of the batch script this one line:
That will make Subversion think the post-commit hook has failed and you should get an error message on commit. If not, your post-commit script isn’t running. Make sure the script is executable by the account that’s running the Subversion server.
If you do get an error message, the script is running. However, the svn command may not be returning an error that’s getting picked up by the post-commit process. I normally don’t recommend writing hooks in Windows batch programming language because of its limitations. Use Python or Perl or PowerShell. These are better at detecting error conditions and you can exit out of your script when detected.
Then again, things are working perfectly, but you’re looking at the wrong working copy (the one on your machine and not the one on the server). When you run hooks outside of the subversion server for testing, run them on the server as the Subversion user running the server process.
Try these things and see if that corrects your problem.
Additional Comments
I created a repository with svnadmin create and ran it using svnserve . I updated svnserve.conf to allow me to checkout and commit code.
I went into the hooks directory, renamed pre-commit.tmpl to pre-commit.bat and set it as:
When I attempted to commit my changes, I got:
The hook is supposed to remove the environment (including the PATH), but I guess that’s only on Unix and not Windows. You can see PATHEXT defined.
I then renamed pre-commit.bat to pre-commit.tmpl and created a post-commit.bat` that looks like this:
During a commit, I got the following:
It looks like everything is working as planned. I’m not using VisualSVN, and I’m not running as a service. I wonder if there might be an issue with your PATHEXT environment variable.
Maybe take a look how it is set on your account that’s running the Subversion server and see if .BAT is in there.
I can’t think of anything else right off hand.
SVN hooks: изменение комментария к ревизии
Не секрет, что по умолчанию изменение текста комментария к ревизии в SVN не разрешено. Пост предназначен для тех, кто хочет сделать это возможным, но не знает как.
Для начала немного освежим память
Что такое hook.
Нет, это не фильм Спилберга, мы же на хабре. Это крючок, на который поймали событие 🙂 Просто програмка, которая запускается при возникновении определенного события в системе версионного контроля. Поддерживаются они не только SVN, поэтому можете поиграться с хуками например в GIT.
Если в корне вашего репозитория есть папка hooks, знайте — это и есть гнездо хуков. В этой папке могут храниться шаблоны хуков, названия которых соответствуют отслеживаемым событиям.
Это означает, что на базе этих шаблонов вы можете сделать свой хук. Как вы уже догадались pre-хуки срабатывают перед событием. post-хуки — после события.
* start-commit — запускается до начала транзакции, может быть использован для проверки прав.
* pre-commit — запускается в конце транзакции, но до commit, часто используется для валидации данных, например для проверки не пустых лог-сообщений.
* post-commit — запускается после транзакции, может быть использовано для отправки e-mail или для резервирования хранилища.
* pre-revprop-change — запускается до изменений в ревизии, могут быть использованы для проверки доступа.
* post-revprop-change — запускается после изменений в ревизии, могут быть использованы для отправки e-mail.
* post-lock, post-unlock, pre-lock, pre-unlock — запускаются, когда репозиторий работает с блокировками
Не лишним будет упомянуть, что у юзера, который подключается к репозиторию, а значит и запускает хуки, должны быть права на исполнение.
Изменение комментария к ревизии
Перейдем к решению нашей задачи. Воспользуемся pre-revprop-change хуком, для того, чтобы ввести дополнительный контроль. Кроме того, следует помнить, что в хук передаются следующие параметры
1. Путь к репозиторию
2. Ревизия, свойства которой будут изменяться
3. Имя пользователя, который будет производить изменения
4. Название изменяемого свойства
5. Код действия: A (добавлено), D (удалено), или M (модифицировано)
Хук справа.
В *nix системах достаточно создать в папке hooks соответствующий файл без расширения, например pre-revprop-change
Хук слева.
В Windows файл в папке hooks должен быть исполняемым, например pre-revprop-change.bat
Если вы используете VisualSVN сервер, батник по умолчанию работать не будет. И папку hooks создавать не надо. Надо просто открыть VisualSVN Server Manager, зайти в свойства репозитория, для которого хотите создать хук, выбрать вкладку Hooks. Дважды кликните на Pre-revision property change hook и просто скопируйте туда код батника.
Дополнение: при активации хука в VisualSVN Server Manager, сервер сам создаст папку hooks и породит там стандартные шаблоны.
За наводку спасибо chemodax
SVN Post Commit Hook Batch Windows
I have a Windows Server running Visual SVN Server to store our repositories. Also on that server is our test copy.
I’m trying to set up a simple SVN post-commit hook so it updates that test copy automatically every time I commit something
In Visual SVN in the post-commit hooks I’ve set up like this
Then that batch file has a simple update like this
If I run the batch file in the server by double clicking on it or from command line works fine. When committing something from my laptop it freezes and doesn’t give me any error and locks the test copy so then I need to go in and run a clean up.
Visual SVN service is running as network service and this aacount has full access to the bin folder and the test copy on the server.
Any idea how to set up a simple svn update post commit hook anyone?
4 Answers 4
I had a similar problem and it turned out to be that SVN likes paths to use forward slashes instead of backslashes.
You’re running the svn update command. Exactly what working copy are you trying to update?
The parameter being passed is the Repository’s path. This points not to a working directory, but to the directory that contains the Subversion master repository. This is the same directory where your post commit hook is stored.
Subversion hooks do not have access to the user’s working directory, so you can’t manipulate the user’s files. Hook scripts usually should be using svnlook and not svn . By doing this, you prevent yourself from getting into any sort of trouble.
It is possible to update a Subversion working copy on the server, if you know the location:
However, I wouldn’t recommend this because it ties up Subversion. The user who did the commit would have to wait until the update is complete before Subversion returns the control of the prompt back to the user.
How do I implement the Post Commit Hook with Trac & SVN in a Windows Environment?
I’m running in a windows environment with Trac / SVN and I want commits to the repository to integrate to Trac and close the bugs that were noted in the SVN Comment.
I know there’s some post commit hooks to do that, but there’s not much information about how to do it on windows.
Anyone done it successfully? And what were the steps you followed to achive it?
Here’s the hook I need to put in place in SVN, but I’m not exactly sure how to do this in the Windows environment.
6 Answers 6
Benjamin’s answer is close, but on Windows you need to give the hook script files an executable extension, such as .bat or .cmd. I use .cmd. You can take the template scripts, which are unix shell scripts, shell scripts and convert them to .bat/.cmd syntax.
But to answer the question of integrating with Trac, follow these steps.
Ensure that Python.exe is on the system path. This will make your life easier.
Create post-commit.cmd in \hooks folder. This is the actual hook script that Subversion will execute on the post-commit event.
Create trac-post-commit.cmd in \hooks folder:
Create trac-post-commit-resolve-ticket-ref.py in \hooks folder. I used the same script from EdgeWall, only I renamed it to better clarify its purpose.
Alright, now that I’ve got some time to post my experience after figuring this all out, and thanks to Craig for getting me on the right track. Here’s what you need to do (at least with SVN v1.4 and Trac v0.10.3):
- Locate your SVN repository that you want to enable the Post Commit Hook for.
- inside the SVN repository there’s a directory called hooks, this is where you’ll be placing the post commit hook.
- create a file post-commit.bat (this is the batch file that’s automatically called by SVN post commit).
- Place the following code inside the post-commit.bat file ( this will call your post commit cmd file passing in the parameters that SVN automatically passes %1 is the repository, %2 is the revision that was committed.
dp0\trac-post-commit-hook.cmd %1 %2
- Now create the trac-post-commit-hook.cmd file as follows:
@ECHO OFF
::
:: Trac post-commit-hook script for Windows
::
:: Contributed by markus, modified by cboos.
:: Usage:
::
:: 1) Insert the following line in your post-commit.bat script
::
:: call %
dp0\trac-post-commit-hook.cmd %1 %2
::
:: 2) Check the ‘Modify paths’ section below, be sure to set at least TRAC_ENV
:: — this one must be set
SET TRAC_ENV=C:\trac\MySpecialProject
:: — set if Python is not in the system path
:: SET PYTHON_PATH=
:: — set to the folder containing trac/ if installed in a non-standard location
:: SET TRAC_PATH=
:: ———————————————————-
:: Do not execute hook if trac environment does not exist
IF NOT EXIST %TRAC_ENV% GOTO :EOF
set PATH=%PYTHON_PATH%;%PATH%
set PYTHONPATH=%TRAC_PATH%;%PYTHONPATH%
:: GET THE AUTHOR AND THE LOG MESSAGE
for /F %%A in (‘svnlook author -r %REV% %1’) do set AUTHOR=%%A
for /F «delims==» %%B in (‘svnlook log -r %REV% %1’) do set LOG=%%B
:: CALL THE PYTHON SCRIPT
Python «%
dp0\trac-post-commit-hook» -p «%TRAC_ENV%» -r «%REV%» -u «%AUTHOR%» -m «%LOG%»
The most important parts here are to set your TRAC_ENV which is the path to the repository root (SET TRAC_ENV=C:\trac\MySpecialProject)
The next MAJORLY IMPORTANT THING in this script is to do the following:
:: GET THE AUTHOR AND THE LOG MESSAGE
for /F %%A in (‘svnlook author -r %REV% %1’) do set AUTHOR=%%A
for /F «delims==» %%B in (‘svnlook log -r %REV% %1’) do set LOG=%%B
if you see in the script file above I’m using svnlook (which is a command line utility with SVN) to get the LOG message and the author that made the commit to the repository.
Then, the next line of the script is actually calling the Python code to perform the closing of the tickets and parse the log message. I had to modify this to pass in the Log message and the author (which the usernames I use in Trac match the usernames in SVN so that was easy).
dp0\trac-post-commit-hook» -p «%TRAC_ENV%» -r «%REV%» -u «%AUTHOR%» -m «%LOG%»
The above line in the script will pass into the python script the Trac Environment, the revision, the person that made the commit, and their comment.
Here’s the Python script that I used. One thing that I did additional to the regular script is we use a custom field (fixed_in_ver) which is used by our QA team to tell if the fix they’re validating is in the version of code that they’re testing in QA. So, I modified the code in the python script to update that field on the ticket. You can remove that code as you won’t need it, but it’s a good example of what you can do to update custom fields in Trac if you also want to do that.
I did that by having the users optionally include in their comment something like:
I then use the same technique that the python script uses with regular expressions to get the information out. It wasn’t too bad.
Anyway, here’s the python script I used, Hopefully this is a good tutorial on exactly what I did to get it to work in the windows world so you all can leverage this in your own shop.
If you don’t want to deal with my additional code for updating the custom field, get the base script from this location as mentioned by Craig above (Script From Edgewall)