49

我们已经将 VisualSVN 服务器设置为 Windows 上的 Subversion 服务器,并且我们使用 Ankhsvn + TortoiseSVN 作为工作站上的客户端。

如何配置服务器以要求提交消息为非空?

4

10 回答 10

65

我很高兴你问了这个问题。这是我们用常见的Windows Batch编写的预提交钩子脚本。如果日志消息少于 6 个字符,则拒绝提交。只需将pre-commit.bat 放入您的 hooks 目录即可。

预提交.bat

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
于 2009-08-12T14:18:56.210 回答
37

VisualSVN Server 3.9 提供了VisualSVNServerHooks.exe check-logmessagepre-commit 钩子,可以帮助您拒绝带有空或短日志消息的提交。有关说明,请参阅文章KB140:验证 VisualSVN 服务器中的提交日志消息。

除了内置的VisualSVNServerHooks.exe,VisualSVN Server 和 SVN 通常使用许多钩子来完成这样的任务。

  • start-commit— 在提交事务开始之前运行,可用于进行特殊权限检查
  • pre-commit— 在事务结束时运行,但在提交之前。通常用于验证诸如非零长度日志消息之类的内容。
  • post-commit— 在事务提交后运行。可用于发送电子邮件或备份存储库。
  • pre-revprop-change— 在修订属性更改之前运行。可用于检查权限。
  • post-revprop-change— 在修订属性更改后运行。可用于通过电子邮件发送或备份这些更改。

你需要使用pre-commit钩子。您可以用您的平台支持的几乎任何语言自己编写它,但网络上有许多脚本。谷歌搜索“svn precommit hook to require comment”我发现一对看起来很符合要求的夫妇:

于 2008-10-29T18:36:45.093 回答
17

您的问题的技术答案已经给出。我想添加社交答案,即:“通过与您的团队建立提交消息标准并让他们同意(或接受)需要表达性提交消息的原因”

我见过很多提交信息,上面写着“patch”、“typo”、“fix”或类似的东西,我已经记不清了。

真的 - 让每个人都清楚你为什么需要它们。

原因示例如下:

  • 生成的变更说明(嗯 - 如果我知道它们将(以我的名字)公开可见 - 如果只对团队来说,这实际上会成为一个很好的自动工具来强制执行好的消息)
  • 许可证问题:您以后可能需要知道代码的来源,例如,如果您想更改代码的许可证(有些组织甚至有提交消息格式的标准 - 好吧,您可以自动检查这一点,但您会不一定会得到好的提交消息)
  • 与其他工具的互操作性,例如与您的版本控制交互并从提交消息中提取信息的错误跟踪器/问题管理系统。

除了关于预提交钩子的技术答案之外,希望对您有所帮助。

于 2008-10-29T18:46:58.037 回答
6

这是一个两部分示例Batch + PowerShell预提交钩子,它拒绝提交少于 25 个字符的日志消息。

将两者都pre-commit.bat放入pre-commit.ps1您的存储库hooks文件夹中,例如C:\Repositories\repository\hooks\

预提交.ps1

# Store hook arguments into variables with mnemonic names
$repos    = $args[0]
$txn      = $args[1]

# Build path to svnlook.exe
$svnlook = "$env:VISUALSVN_SERVER\bin\svnlook.exe"

# Get the commit log message
$log = (&"$svnlook" log -t $txn $repos)

# Check the log message contains non-empty string
$datalines = ($log | where {$_.trim() -ne ""})
if ($datalines.length -lt 25)
{
  # Log message is empty. Show the error.
  [Console]::Error.WriteLine("Commit with empty log message is prohibited.")
  exit 3
}

exit 0

预提交.bat

@echo off
set PWSH=%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
%PWSH% -command $input ^| %1\hooks\pre-commit.ps1 %1 %2
if errorlevel 1 exit %errorlevel%

注1:pre-commit.bat是唯一可以被VisualSVN调用的,然后pre-commit.ps1是被调用的pre-commit.bat

注2:pre-commit.bat也可命名pre-commit.cmd

注意 3:如果您尝试使用一些重音字符和输出进行编码问题,则在.[Console]::Error.WriteLine之后添加例如下一行。chcp 1252pre-commit.bat@echo off

于 2012-07-19T12:08:25.650 回答
4

VisualSVN 为您提供作为钩子输入的是“Windows NT 命令脚本”,它们基本上是批处理文件。

在批处理文件中编写 if-then-else 非常难看,而且可能很难调试。

它看起来像下面这样(搜索 pre-commit.bat)(未测试):

SVNLOOK.exe log -t "%2" "%1" | grep.exe "[a-zA-Z0-9]" > nul || GOTO ERROR
GOTO OK
:ERROR
ECHO "Please enter comment and then retry commit!"
exit 1
:OK
exit 0 

您需要一个 grep.exe 在路径上,%1 是此存储库的路径,%2 是即将提交的 txn 的名称。还可以查看存储库 hooks 目录中的 pre-commit.tmpl。

于 2008-10-30T09:01:38.467 回答
4

我们将优秀的CS-Script工具用于我们的预提交钩子,以便我们可以用我们正在开发的语言编写脚本。这是一个确保提交消息长度超过 10 个字符的示例,并确保 .suo 和.user 文件未签入。您还可以测试制表符/空格缩进,或在签入时执行小代码标准,但要小心让您的脚本做太多,因为您不想减慢提交速度.

// 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) {
  }
}
于 2012-10-11T21:32:31.167 回答
3

在 Windows 上使用此预提交挂钩。它是用 Windows Batch 编写的,并使用grep命令行实用程序来检查提交长度。

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 副本,我推荐使用gnu 工具版本

于 2009-02-20T18:42:06.803 回答
3

这是一个 Windows Shell JScript,您可以通过将钩子指定为:

%SystemRoot%\System32\CScript.exe //nologo <..path..to..script> %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);
于 2009-08-04T15:15:02.477 回答
3

注意:这只适用于 TortoiseSVN

只需右键单击存储库的顶层。在上下文菜单中选择 TortoiseSVN,然后选择属性,以查看此对话框:

在此处输入图像描述

单击右下角附近的新建按钮,然后选择日志大小。输入您希望提交和锁定所需的字符数(在下面的示例中为 10)。

在此处输入图像描述

从您刚刚修改的顶级目录执行 Commit。现在,您的存储库要求所有用户在提交更改之前进行评论。

于 2014-04-27T02:39:31.450 回答
2

在向我的服务器添加提交挂钩之前,我只是将 svnprops 分发给 TortoiseSVN 客户端。

因此,作为替代方案:

在 TortoiseSVN -> Properties 属性名称中 -tsvn:logminsize适当地添加/设置。

这当然不能保证在服务器上,因为客户端/用户可以选择不这样做,但如果你愿意,你可以分发 svnprops 文件。这样,用户不必设置自己的值 - 您可以将它们提供给所有用户。

这也适用于 bugtraq:设置以链接日志中的问题跟踪内容。

于 2008-12-19T14:20:20.163 回答