SVN:Python预提交脚本总是失败

2 投票
1 回答
2153 浏览
提问于 2025-04-16 18:17

我找到一个示例的Python脚本,并对它进行了修改,以便在提交之前检查评论内容。我的问题是,Python解析出来的评论文本总是为空。

  • 环境:Windows XP
  • SVN版本:svn,版本1.5.6(r36142),编译于2009年3月6日,14:54:47
  • Python 2.7

pre-commit.bat

C:\Python27\python %1\hooks\pre-commit.py %1 %2

pre-commit.py

import sys, os, string, re

SVNLOOK='C:\\SVN\\bin\\svnlook.exe'


# return true or false if this passed string is a valid comment
def check(comment):
    #define regular expression
    print comment
    p = re.match("[bB][uU][gG]\s([0-9]+|NONE)+", comment)
    print p
    return (p != None) #returns false if doesn't match

def result(r, txn, repos, log_msg, log_cmd):
    if r == 1:
        sys.stderr.write ("File: " + repos + " Comment: " + txn + "\n" +\
                          "Log Msg: " + log_msg + "\n" +\
                          "Log Cmd: " + log_cmd + "\n" +\
                            "Comments must have the format of \n'Bug X' \n" +\
                          "'Comment text' where X is the issue number.\n" +\
                          "Use comma to separatemultiple bug id's\n" +\
                          "Example:\nBug 1234, 1235\nComment: Fixed things\n" +\
                          "Use 'NONE' if there is no bug ID")
        sys.exit(r)

def main(repos, txn):
    log_cmd = '%s log %s -t %s' % (SVNLOOK, txn, repos)
    log_msg = os.popen(log_cmd, 'r').readline().rstrip('\n')

    if check(log_msg):
        result(0, txn, repos, log_msg, log_cmd)
    else:
        result(1, txn, repos, log_msg, log_cmd)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        sys.stderr.write("Usage: %s REPOS TXN\n" % (sys.argv[0]))
    else:
        main(sys.argv[1], sys.argv[2])

我在错误信息中添加了变量的打印输出,以便于调试。

让我感到烦恼的是,如果我使用批处理文件的命令,事情似乎就能正常工作:

这个pre-commit.bat文件只检查提交信息是否为空:

@echo off  
:: Stops commits that have empty log messages.        
@echo off  

setlocal  

rem Subversion sends through the path to the repository and transaction id  
set REPOS=%1  
set TXN=%2           


rem line below ensures at least one character ".", 5 characters require change to "....."
C:\SVN\bin\svnlook.exe log %REPOS% -t %TXN% | findstr . > nul  
if %errorlevel% gtr 0 (goto err) else exit 0  

:err  
echo. 1>&2  
echo Your commit has been blocked because you didn't enter a comment. 1>&2  
echo Write a log message describing the changes made and try again. 1>&2
echo Thanks 1>&2
exit 1

我到底哪里做错了呢?

1 个回答

3

当你在Python中运行这个程序时,Python设置的错误代码在批处理文件中会被忽略;你需要这样做:

C:\Python27\python %1\hooks\pre-commit.py %1 %2
exit %ERRORLEVEL%

同时,把你的值用引号括起来也是个好主意,这样可以确保它们完整地传递给Python:

C:\Python27\python "%1\hooks\pre-commit.py" "%1" "%2"
exit %ERRORLEVEL%

撰写回答