如何在VisualSVN服务器中要求提交消息?
我们已将VisualSVN服务器设置为Windows上的Subversion服务器,并在工作站上使用Ankhsvn+TortoiseSVN作为客户端如何在VisualSVN服务器中要求提交消息?,svn,notifications,hook,visualsvn-server,svn-hooks,Svn,Notifications,Hook,Visualsvn Server,Svn Hooks,我们已将VisualSVN服务器设置为Windows上的Subversion服务器,并在工作站上使用Ankhsvn+TortoiseSVN作为客户端 如何配置服务器以要求提交消息为非空?VisualSVN server 3.9提供了VisualSVNServerHooks.exe check logmessagepre-commit钩子,可帮助您拒绝带有空或短日志消息的提交。有关说明,请参阅本文 除了内置的VisualSVNServerHooks.exe,VisualSVN服务器和SVN通常使用
如何配置服务器以要求提交消息为非空?VisualSVN server 3.9提供了
VisualSVNServerHooks.exe check logmessage
pre-commit钩子,可帮助您拒绝带有空或短日志消息的提交。有关说明,请参阅本文
除了内置的VisualSVNServerHooks.exe
,VisualSVN服务器和SVN通常使用a来完成这样的任务
- -在提交事务开始之前运行,可用于执行特殊权限检查
- -在事务结束时但在提交之前运行。通常用于验证非零长度日志消息等内容
- -在提交事务后运行。可用于发送电子邮件或备份存储库
- -在修订属性更改之前运行。可用于检查权限
- -在修订属性更改后运行。可用于通过电子邮件发送或备份这些更改
预提交
钩子。您可以自己用平台支持的任何语言编写,但web上有许多脚本。在谷歌搜索“svn precommit hook to require comment”时,我发现一对夫妇看起来符合条件:
- 生成的变更通知(这实际上是一个很好的自动工具,可以强制执行好的消息,如果我知道它们(用我的名字)在公共场合可见的话——如果只对团队而言)
- 许可证问题:您以后可能需要知道代码的来源,例如,如果您想将许可证更改为您的代码(一些组织甚至有提交消息格式的标准-您可以自动检查此问题,但您不一定能获得良好的提交消息)
- 与其他工具的互操作性,例如与版本控制接口并从提交消息中提取信息的错误跟踪程序/问题管理系统
除了关于预提交挂钩的技术解答之外,希望这对您有所帮助。VisualSVN为您提供的作为挂钩输入的内容是“Windows NT命令脚本”,基本上是批处理文件 在批处理文件中编写if-then-else非常难看,而且可能很难调试 它的外观如下(搜索pre-commit.bat)(未测试): 路径上需要一个grep.exe,%1是此存储库的路径,%2是要提交的txn的名称。
还可以查看存储库hooks目录中的pre-commit.tmpl。在将提交钩子添加到我的服务器之前,我刚刚将svnprops分发到TortoiseSVN客户端 因此,作为替代方案: 在TortoiseSVN->Properties property name中,适当添加/设置
tsvn:logminsize
当然,这在服务器上并不能保证,因为客户端/用户可以选择不这样做,但如果愿意,您可以分发svnprops文件。这样,用户就不必设置自己的值——您可以将它们提供给所有用户
这也适用于bugtraq:设置,以链接日志中的问题跟踪内容。在Windows上使用此预提交挂钩。它是在Windows批处理中编写的,并使用命令行实用程序检查提交长度
svnlook log -t "%2" "%1" | c:\tools\grep -c "[a-zA-z0-9]" > nul
if %ERRORLEVEL% NEQ 1 exit 0
echo Please enter a check-in comment 1>&2
exit 1
请记住,您需要一份grep,我建议使用。这里有一个Windows Shell JScript,您可以通过将钩子指定为:
%SystemRoot%\System32\CScript.exe //nologo <..path..to..script> %1 %2
%SystemRoot%\System32\CScript.exe//nologo%1%2
它很容易阅读,所以继续做一个实验吧
顺便说一句,在JScript中这样做的原因是它不依赖于要安装的任何其他工具(Perl、CygWin等)
if (WScript.Arguments.Length < 2)
{
WScript.StdErr.WriteLine("Repository Hook Error: Missing parameters. Should be REPOS_PATH then TXN_NAME, e.g. %1 %2 in pre-commit hook");
WScript.Quit(-1);
}
var oShell = new ActiveXObject("WScript.Shell");
var oFSO = new ActiveXObject("Scripting.FileSystemObject");
var preCommitStdOut = oShell.ExpandEnvironmentStrings("%TEMP%\\PRE-COMMIT." + WScript.Arguments(1) + ".stdout");
var preCommitStdErr = oShell.ExpandEnvironmentStrings("%TEMP%\\PRE-COMMIT." + WScript.Arguments(1) + ".stderr");
var commandLine = "%COMSPEC% /C \"C:\\Program Files\\VisualSVN Server\\bin\\SVNLook.exe\" log -t ";
commandLine += WScript.Arguments(1);
commandLine += " ";
commandLine += WScript.Arguments(0);
commandLine += "> " + preCommitStdOut + " 2> " + preCommitStdErr;
// Run Synchronously, don't show a window
// WScript.Echo("About to run: " + commandLine);
var exitCode = oShell.Run(commandLine, 0, true);
var fsOUT = oFSO.GetFile(preCommitStdOut).OpenAsTextStream(1);
var fsERR = oFSO.GetFile(preCommitStdErr).OpenAsTextStream(1);
var stdout = fsOUT && !fsOUT.AtEndOfStream ? fsOUT.ReadAll() : "";
var stderr = fsERR && !fsERR.AtEndOfStream ? fsERR.ReadAll() : "";
if (stderr.length > 0)
{
WScript.StdErr.WriteLine("Error with SVNLook: " + stderr);
WScript.Quit(-2);
}
// To catch naught commiters who write 'blah' as their commit message
if (stdout.length < 5)
{
WScript.StdErr.WriteLine("Please provide a commit message that describes why you've made these changes.");
WScript.Quit(-3);
}
WScript.Quit(0);
if(WScript.Arguments.Length<2)
{
WScript.StdErr.WriteLine(“存储库钩子错误:缺少参数。应该是REPOS_路径,然后是TXN_名称,例如预提交钩子中的%1%2”);
WScript.Quit(-1);
}
var oShell=newActiveXObject(“WScript.Shell”);
var of so=newActiveXObject(“Scripting.FileSystemObject”);
var preCommitStdOut=oShell.ExpandEnvironmentStrings(“%TEMP%\\PRE-COMMIT.”+WScript.Arguments(1)+“.stdout”);
var preCommitStdErr=oShell.ExpandEnvironmentStrings(“%TEMP%\\PRE-COMMIT.”+WScript.Arguments(1)+“.stderr”);
var commandLine=“%COMSPEC%/C\”C:\\Program Files\\VisualSVN Server\\bin\\SVNLook.exe\“log-t”;
commandLine+=WScript.Arguments(1);
命令行+=“”;
commandLine+=WScript.Arguments(0);
命令行+=“>”+预调试输出+“2>”+预调试错误;
//同步运行,不显示窗口
//Echo(“即将运行:+commandLine”);
var exitCode=oShell.Run(命令行,0,true);
var fsOUT=oFSO.GetFile(preCommitStdOut).OpenAsTextStream(1);
var fsERR=oFSO.GetFile(preCommitStdErr).OpenAsTextStream(1);
var stdout=fsOUT&!fsOUT.AtEndOfStream?fsOUT.ReadAll():“”;
var stderr=fsERR&&!fsERR.AtEndOfStream?fsERR.ReadAll():“”;
如果(标准长度>0)
{
WScript.StdErr.WriteLine(“SVNLook错误:+StdErr”);
WScript.Quit(-2);
}
//捕获那些将“废话”作为提交消息的提交者
如果(标准长度<5)
{
WScript.StdErr.WriteLine(“请提供一条提交消息,描述您进行这些更改的原因。”);
WScript.Quit(-3);
}
WScript.Quit(0);
很高兴你问我
if (WScript.Arguments.Length < 2)
{
WScript.StdErr.WriteLine("Repository Hook Error: Missing parameters. Should be REPOS_PATH then TXN_NAME, e.g. %1 %2 in pre-commit hook");
WScript.Quit(-1);
}
var oShell = new ActiveXObject("WScript.Shell");
var oFSO = new ActiveXObject("Scripting.FileSystemObject");
var preCommitStdOut = oShell.ExpandEnvironmentStrings("%TEMP%\\PRE-COMMIT." + WScript.Arguments(1) + ".stdout");
var preCommitStdErr = oShell.ExpandEnvironmentStrings("%TEMP%\\PRE-COMMIT." + WScript.Arguments(1) + ".stderr");
var commandLine = "%COMSPEC% /C \"C:\\Program Files\\VisualSVN Server\\bin\\SVNLook.exe\" log -t ";
commandLine += WScript.Arguments(1);
commandLine += " ";
commandLine += WScript.Arguments(0);
commandLine += "> " + preCommitStdOut + " 2> " + preCommitStdErr;
// Run Synchronously, don't show a window
// WScript.Echo("About to run: " + commandLine);
var exitCode = oShell.Run(commandLine, 0, true);
var fsOUT = oFSO.GetFile(preCommitStdOut).OpenAsTextStream(1);
var fsERR = oFSO.GetFile(preCommitStdErr).OpenAsTextStream(1);
var stdout = fsOUT && !fsOUT.AtEndOfStream ? fsOUT.ReadAll() : "";
var stderr = fsERR && !fsERR.AtEndOfStream ? fsERR.ReadAll() : "";
if (stderr.length > 0)
{
WScript.StdErr.WriteLine("Error with SVNLook: " + stderr);
WScript.Quit(-2);
}
// To catch naught commiters who write 'blah' as their commit message
if (stdout.length < 5)
{
WScript.StdErr.WriteLine("Please provide a commit message that describes why you've made these changes.");
WScript.Quit(-3);
}
WScript.Quit(0);
setlocal enabledelayedexpansion
set REPOS=%1
set TXN=%2
set SVNLOOK="%VISUALSVN_SERVER%\bin\svnlook.exe"
SET M=
REM Concatenate all the lines in the commit message
FOR /F "usebackq delims==" %%g IN (`%SVNLOOK% log -t %TXN% %REPOS%`) DO SET M=!M!%%g
REM Make sure M is defined
SET M=0%M%
REM Here the 6 is the length we require
IF NOT "%M:~6,1%"=="" goto NORMAL_EXIT
:ERROR_TOO_SHORT
echo "Commit note must be at least 6 letters" >&2
goto ERROR_EXIT
:ERROR_EXIT
exit /b 1
REM All checks passed, so allow the commit.
:NORMAL_EXIT
exit 0
// run from pre-commit.cmd like so:
// css.exe /nl /c C:\SVN\Scripts\PreCommit.cs %1 %2
using System;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
class PreCommitCS {
/// <summary>Controls the procedure flow of this script</summary>
public static int Main(string[] args) {
if (args.Length < 2) {
Console.WriteLine("usage: PreCommit.cs repository-path svn-transaction");
Environment.Exit(2);
}
try {
var proc = new PreCommitCS(args[0], args[1]);
proc.RunChecks();
if (proc.MessageBuffer.ToString().Length > 0) {
throw new CommitException(String.Format("Pre-commit hook violation\r\n{0}", proc.MessageBuffer.ToString()));
}
}
catch (CommitException ex) {
Console.WriteLine(ex.Message);
Console.Error.WriteLine(ex.Message);
throw ex;
}
catch (Exception ex) {
var message = String.Format("SCRIPT ERROR! : {1}{0}{2}", "\r\n", ex.Message, ex.StackTrace.ToString());
Console.WriteLine(message);
Console.Error.WriteLine(message);
throw ex;
}
// return success if we didn't throw
return 0;
}
public string RepoPath { get; set; }
public string SvnTx { get; set; }
public StringBuilder MessageBuffer { get; set; }
/// <summary>Constructor</summary>
public PreCommitCS(string repoPath, string svnTx) {
this.RepoPath = repoPath;
this.SvnTx = svnTx;
this.MessageBuffer = new StringBuilder();
}
/// <summary>Main logic controller</summary>
public void RunChecks() {
CheckCommitMessageLength(10);
// Uncomment for indent checks
/*
string[] changedFiles = GetCommitFiles(
new string[] { "A", "U" },
new string[] { "*.cs", "*.vb", "*.xml", "*.config", "*.vbhtml", "*.cshtml", "*.as?x" },
new string[] { "*.designer.*", "*.generated.*" }
);
EnsureTabIndents(changedFiles);
*/
CheckForIllegalFileCommits(new string[] {"*.suo", "*.user"});
}
private void CheckForIllegalFileCommits(string[] filesToExclude) {
string[] illegalFiles = GetCommitFiles(
new string[] { "A", "U" },
filesToExclude,
new string[] {}
);
if (illegalFiles.Length > 0) {
Echo(String.Format("You cannot commit the following files: {0}", String.Join(",", illegalFiles)));
}
}
private void EnsureTabIndents(string[] filesToCheck) {
foreach (string fileName in filesToCheck) {
string contents = GetFileContents(fileName);
string[] lines = contents.Replace("\r\n", "\n").Replace("\r", "\n").Split(new string[] { "\n" }, StringSplitOptions.None);
var linesWithSpaceIndents =
Enumerable.Range(0, lines.Length)
.Where(i => lines[i].StartsWith(" "))
.Select(i => i + 1)
.Take(11)
.ToList();
if (linesWithSpaceIndents.Count > 0) {
var message = String.Format("{0} has spaces for indents on line(s): {1}", fileName, String.Join(",", linesWithSpaceIndents));
if (linesWithSpaceIndents.Count > 10) message += "...";
Echo(message);
}
}
}
private string GetFileContents(string fileName) {
string args = GetSvnLookCommandArgs("cat") + " \"" + fileName + "\"";
string svnlookResults = ExecCmd("svnlook", args);
return svnlookResults;
}
private void CheckCommitMessageLength(int minLength) {
string args = GetSvnLookCommandArgs("log");
string svnlookResults = ExecCmd("svnlook", args);
svnlookResults = (svnlookResults ?? "").Trim();
if (svnlookResults.Length < minLength) {
if (svnlookResults.Length > 0) {
Echo("Your commit message was too short.");
}
Echo("Please describe the changes you've made in a commit message in order to successfully commit. Include support ticket number if relevant.");
}
}
private string[] GetCommitFiles(string[] changedIds, string[] includedFiles, string[] exclusions) {
string args = GetSvnLookCommandArgs("changed");
string svnlookResults = ExecCmd("svnlook", args);
string[] lines = svnlookResults.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
var includedPatterns = (from a in includedFiles select ConvertWildcardPatternToRegex(a)).ToArray();
var excludedPatterns = (from a in exclusions select ConvertWildcardPatternToRegex(a)).ToArray();
var opts = RegexOptions.IgnoreCase;
var results =
from line in lines
let fileName = line.Substring(1).Trim()
let changeId = line.Substring(0, 1).ToUpper()
where changedIds.Any(x => x.ToUpper() == changeId)
&& includedPatterns.Any(x => Regex.IsMatch(fileName, x, opts))
&& !excludedPatterns.Any(x => Regex.IsMatch(fileName, x, opts))
select fileName;
return results.ToArray();
}
private string GetSvnLookCommandArgs(string cmdType) {
string args = String.Format("{0} -t {1} \"{2}\"", cmdType, this.SvnTx, this.RepoPath);
return args;
}
/// <summary>
/// Executes a command line call and returns the output from stdout.
/// Raises an error is stderr has any output.
/// </summary>
private string ExecCmd(string command, string args) {
Process proc = new Process();
proc.StartInfo.FileName = command;
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
var stdOut = proc.StandardOutput.ReadToEnd();
var stdErr = proc.StandardError.ReadToEnd();
proc.WaitForExit(); // Do after ReadToEnd() call per: http://chrfalch.blogspot.com/2008/08/processwaitforexit-never-completes.html
if (!string.IsNullOrWhiteSpace(stdErr)) {
throw new Exception(string.Format("Error: {0}", stdErr));
}
return stdOut;
}
/// <summary>
/// Writes the string provided to the Message Buffer - this fails
/// the commit and this message is presented to the comitter.
/// </summary>
private void Echo(object s) {
this.MessageBuffer.AppendLine((s == null ? "" : s.ToString()));
}
/// <summary>
/// Takes a wildcard pattern (like *.bat) and converts it to the equivalent RegEx pattern
/// </summary>
/// <param name="wildcardPattern">The wildcard pattern to convert. Syntax similar to VB's Like operator with the addition of pipe ("|") delimited patterns.</param>
/// <returns>A regex pattern that is equivalent to the wildcard pattern supplied</returns>
private string ConvertWildcardPatternToRegex(string wildcardPattern) {
if (string.IsNullOrEmpty(wildcardPattern)) return "";
// Split on pipe
string[] patternParts = wildcardPattern.Split('|');
// Turn into regex pattern that will match the whole string with ^$
StringBuilder patternBuilder = new StringBuilder();
bool firstPass = true;
patternBuilder.Append("^");
foreach (string part in patternParts) {
string rePattern = Regex.Escape(part);
// add support for ?, #, *, [...], and [!...]
rePattern = rePattern.Replace("\\[!", "[^");
rePattern = rePattern.Replace("\\[", "[");
rePattern = rePattern.Replace("\\]", "]");
rePattern = rePattern.Replace("\\?", ".");
rePattern = rePattern.Replace("\\*", ".*");
rePattern = rePattern.Replace("\\#", "\\d");
if (firstPass) {
firstPass = false;
}
else {
patternBuilder.Append("|");
}
patternBuilder.Append("(");
patternBuilder.Append(rePattern);
patternBuilder.Append(")");
}
patternBuilder.Append("$");
string result = patternBuilder.ToString();
if (!IsValidRegexPattern(result)) {
throw new ArgumentException(string.Format("Invalid pattern: {0}", wildcardPattern));
}
return result;
}
private bool IsValidRegexPattern(string pattern) {
bool result = true;
try {
new Regex(pattern);
}
catch {
result = false;
}
return result;
}
}
public class CommitException : Exception {
public CommitException(string message) : base(message) {
}
}