【问题标题】:How can I prevent users from committing binaries into subversion?如何防止用户将二进制文件提交到颠覆?
【发布时间】:2010-01-29 22:42:57
【问题描述】:

我有一个任性的用户,他固执地坚持将他的二进制文件(可执行文件、DLL)提交到我们的 subversion 存储库中。我会进去并删除它们,但当然没有真正从颠覆中删除。

虽然有时我们需要提交二进制文件,但我不希望用户将其作为例行公事。我可以设置一个忽略属性,但这不会阻止用户提交二进制文件,如果他们真的确定的话。我想做的是能够逐个目录地控制提交指定文件类型的能力,尤其是 .exe 和 .dll 文件。

有没有办法在 SVN 中做到这一点?如果有什么不同,我们使用的是 VisualSVN 服务器和 TortoiseSVN。

【问题讨论】:

  • 嗯,三个答案如此快速且无法选择,我确信示例脚本将确保“已接受”状态:)
  • 如何约束你的用户?不是每个解决方案都是技术性的,你知道吗?
  • @Lasse:我同意,但实际上我发现这是一种有用的方法,可以防止 myself 意外 将二进制文件放入 SVN 存储库(即在新机器上设置 Tortoise 并忘记添加“bin”和“obj”异常)
  • 不幸的是,在志愿者的努力中,不存在约束用户的问题。他的贡献对项目太有价值了,不能冒完全失去他的风险,所以我首选的解决方案是默默地忽略大多数二进制文件。
  • 我同意这一点。我个人使用 VisualSVN,当我用它添加一个项目到 Subversion 时,它会自动为我添加这些忽略,以及其他一些很好的措施。但是请注意,如果您正在与一个愚蠢的用户打交道(阅读:愚蠢),无论您做什么,他都能够做到。他的下一步可能是尝试以某种方式伪装文件。

标签: svn permissions visualsvn


【解决方案1】:

蒂姆:

你可以试试这个 python 钩子脚本。它(松散地)基于上面的那个,但允许拒绝路径的正则表达式模式,并允许通过有一个开始的行来覆盖检查

覆盖:

在日志消息中。它使用新的 python 打印语法,因此需要相当新的 python 版本(2.6+?)。

from __future__ import print_function

import sys,os
import subprocess 
import re

#this is a list of illegal patterns:
illegal_patterns = [
    '\.exe$',
    '\.dll$',
    '[\^|/]bin/',
    '[\^|/]obj/',
]

# Path to svnlook command:
cmdSVNLOOK=r"{}bin\svnlook.exe".format(os.environ["VISUALSVN_SERVER"])

print(illegal_patterns, file=sys.stderr)

print("cmdSVNLook={}".format(cmdSVNLOOK), file=sys.stderr)

def runSVNLook(subCmd, transact, repoPath):
    svninfo =  subprocess.Popen([cmdSVNLOOK, subCmd, '-t', transact, repoPath], 
                          stdout = subprocess.PIPE, stderr=subprocess.PIPE)
    (stdout, stderr) = svninfo.communicate()

    if len(stderr) > 0:
        print("svnlook generated stderr: " + stderr, file=sys.stderr)
        sys.exit(1)

    return [ line.strip() for line in stdout.split("\n") ]

def findIllegalPattern(fileName):
    for pattern in illegal_patterns:
        if re.search(pattern, fileName):
            print("pattern: {} matched filename:{}".format(pattern, fileName))
            return pattern
    return None

def containsOverRide(logOutput):
    retVal = False
    for line in logOutput:
        print("log line: {}".format(line), file=sys.stderr)
        if re.match("^override:", line.lower()):
            retVal = True
            break
    print("contiansOverRide={}".format(retVal), file=sys.stderr)
    return retVal

def findIllegalNames(changeOutput):
    illegalNames = []
    prog = re.compile('(^[ACUDRM_])[ACUDRM]*\s+(.+)')  # regex for svnlook output
    for line in changeOutput:
        print("processing:{}".format(line), file=sys.stderr)
        if (line != ""):
            match=re.search(prog, line.strip())
            if match:
                mode = match.group(1) 
                ptFilename = match.group(2)
                if mode == 'A':
                  pattern = findIllegalPattern(ptFilename)
                  if pattern:
                      illegalNames.append((pattern, ptFilename))
            else:
                print("svnlook output parsing failed!", file=sys.stderr)
                sys.exit(1)
    return illegalNames

######### main program ################
def main(args):
    repopath = args[1]
    transact = args[2]

    retVal = 0

    overRidden = containsOverRide(runSVNLook("log", transact, repopath))
    illegalFiles = findIllegalNames(runSVNLook("changed", transact, repopath))

    if len(illegalFiles):
        msg = "****************************************************************************\n"

        if len(illegalFiles) == 1:
            msg += "* This commit contains a file which matches a forbidden pattern            *\n"
        else:
            msg += "* This commit contains files which match a forbidden pattern               *\n"

        if overRidden:
            msg += "* and contains an Override line so the checkin will be allowed            *\n"
        else:
            retVal = 1

            msg += "* and is being rejected.                                                   *\n"
            msg += "*                                                                          *\n"
            msg += "* Files which match these patterns are genreraly created by the            *\n"
            msg += "* built process and should not be added to svn.                            *\n"
            msg += "*                                                                          *\n"
            msg += "* If you intended to add this file to the svn repository, you neeed to     *\n"
            msg += "* modify your commit message to include a line that looks like:            *\n"
            msg += "*                                                                          *\n"
            msg += "* OverRide: <reason for override>                                          *\n"
            msg += "*                                                                          *\n"
        msg +=  "****************************************************************************\n"

        print(msg, file=sys.stderr)

        if len(illegalFiles) == 1:
            print("The file and the pattern it matched are:", file=sys.stderr)
        else:
            print("The files and the patterns they matched are:", file=sys.stderr)

        for (pattern, fileName) in illegalFiles:
              print('\t{}\t{}'.format(fileName, str(pattern)), file=sys.stderr)

    return retVal

if __name__ == "__main__":
    ret = main(sys.argv)
    sys.exit(ret)

【讨论】:

  • 这是完美的。我在服务器上有 IronPython,这个脚本非常适合我的需要。我喜欢让用户能够覆盖钩子脚本的概念。 VisualSVN 需要一个批处理文件,所以我必须创建一个单行代码来调用 Python 脚本。
【解决方案2】:

这是一个小钩子脚本,它正在做你想做的事情: 你必须配置两件事:

  • illegal_suffixes:一个包含所有应该中止提交的后缀的 python 列表
  • cmdSVNLOOK:svnlook程序的路径

import sys
import subprocess 
import re

#this is a list of illegal suffixes:
illegal_suffixes = ['.exe','.dll']

# Path to svnlook command:
cmdSVNLOOK="/usr/bin/svnlook";

def isIllegalSuffix(progname):
    for suffix in illegal_suffixes:
        if (ptFilename.endswith(suffix)):
            return True
    return False

######### main program ################
repopath = sys.argv[1]
transact = sys.argv[2]

retVal = 0
svninfo = subprocess.Popen([cmdSVNLOOK, 'changed', '-t', transact, repopath], 
                                                        stdout = subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = svninfo.communicate();

prog = re.compile('(^[ACUDRM_])[ACUDRM]*\s+(.+)')  # regex for svnlook output
for line in stdout.split("\n"):
    if (line.strip()!=""):
        match=re.search(prog, line.strip())
        if match:
            mode = match.group(1) 
            ptFilename = match.group(2)
            if mode == 'A' and isIllegalSuffix(ptFilename): 
              retVal = 1
              sys.stderr.write("Please do not add the following ")
              sys.stderr.write("filetypes to repository:\n")
              sys.stderr.write(str(illegal_suffixes)+"\n")
              break
        else:
            sys.stderr.write("svnlook output parsing failed!\n")
            retVal = 1
            break
    else:
        # an empty line is fine!
        retVal = 0
sys.exit(retVal)

【讨论】:

  • 谢谢,感谢您抽出宝贵时间发布该内容 - 不幸的是,我们使用的是在 Windows 上运行的 VisualSVN 服务器。我需要VBScript、JScript 或DOS 批处理文件。不过,为发布脚本 +1。
  • windows下可以用python,svnlook可以用visual svn:visualsvn.com/support/svnbook/ref/svnlook
  • 我是在windwos 下开发的 ;-) 它在linux 和windows 上测试过。你当然可以使用 python 作为钩子,svnlook 是 VisualSVN 的一部分,否则你可以(并且应该)安装 svn-commandline
  • 我接受了这个答案,因为发帖人花时间提供了示例代码。这实际上并没有解决我的问题,因为我们是一家 Windows 商店并在 Windows Server 上运行 VisualSVN,而且我们真的仅限于 VBScript(啊!)。尽管如此,逻辑是合理的,我相信我可以翻译它。
【解决方案3】:

编写一个预提交挂钩,检查添加的文件是否符合您的条件。

您可以使用pre-commit-check.py 作为起点。

【讨论】:

  • 你会如何建议我在每个目录的基础上控制它?我需要一些目录允许签入二进制文件,而其他目录则不允许。我宁愿不必将此信息硬编码到脚本中。
  • 您的脚本可以从文件中读取允许的路径列表(您可能希望将文件存储在服务器上,而不是存储库中,以便用户无法更改它)如果您想存储存储库中的信息,您可以使用目录上的属性。这使得信息更加本地化,​​它会自动处理新的分支/标签。
【解决方案4】:

在 TortoiseSVN 上,您可以让用户将 .dll、.exe 等添加到忽略列表中。这样,他们的用户就不会意外签入。有关更多信息,请参见此处:

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-ignore.html

在服务器端,正如其他人所说,您可以使用挂钩脚本。

【讨论】:

  • 好吧,我在这里处理的是一个任性的用户。他多次被要求不要提交二进制文件,但仍然这样做。我不认为这是一个记住的问题。这就是为什么我需要执行该政策。
  • 坦率地说,执行此问题的一种方法是解雇他。我并不是说这是你处理它的第一种方法,但如果事态严重,非团队玩家在团队中没有位置。
  • 您也可以拒绝任何提交访问。所以他只能将他的差异作为补丁发送给他的同事。这是 Subversion 本身限制其对其存储库的写入访问的方式:您必须通过将补丁发送到邮件列表来证明您编写了正确的代码
  • @Lasse - 这是志愿者的努力,我真的不能考虑“解雇”一个做得很好的志愿者。我们确实需要他对项目的贡献。我只需要阻止他提交二进制文件。如果这不是自愿的,并且假设我是经理,那么我显然会处于更有利的位置。
  • 关键是,他可能不知道不签入。他只是在目录中添加所有内容并提交。通过让他的乌龟忽略它们,问题可能会消失。
【解决方案5】:

您可以使用pre-commit 挂钩。您必须编写一个简单的程序(使用任何语言),如果文件是二进制文件,则返回一个非零值。

请参阅here 了解关于存储库挂钩的通用文档,以及here 了解来自 Apache 的 Python 示例。

您可以查看文件名,或使用file 查看它们的类型。

【讨论】:

  • 这 -- 通常你可能还想检查 .dll、.exe 等文件名,因为这个用户的顽固坚持。
【解决方案6】:

您可以使用 svnlook 命令。这是一个完成这项工作的python类:

    SVNTransactionParser(object):
        def __init__(self, repos, txn):
            self.repos = repos
            self.txn = txn
            self.ms = magic.open(magic.MAGIC_NONE)
            self.ms.load()

        def tx_files(self):
            files_to_analyze = list()
            for l in self.__svnlook('changed')[0].readlines():
                l = l.replace('\n', '');
                if not l.endswith('/') and l[0] in ['A', 'U']:
                    files_to_analyze.append(l.split(' ')[-1:][0])

            files = dict()        
            for file_to_analyze in files_to_analyze:
                files[file_to_analyze] = {
                                'size': self.__svnlook('filesize', file_to_analyze)[0].readlines()[0].replace('\n', ''),
                                'type': self.ms.buffer(self.__svnlook('cat', file_to_analyze)[0].readline(4096)),
                                'extension': os.path.splitext(file_to_analyze)[1]}

            return files

        def __svnlook(self, command, extra_args=""):
            cmd = '%s %s %s -t "%s" %s' % (SVNLOOK, command, self.repos, self.txn, extra_args)
            out = popen2.popen3(cmd)
            return (out[0], out[2])

tx_files() 方法返回带有如下信息的地图:

{ 
    '/path/to/file1.txt': {'size': 10, 'type': 'ASCII', 'extension': '.txt'}, 
    '/path/to/file2.pdf': {'size': 10134, 'type': 'PDF', 'extension': '.dpf'}, 
}

您将需要库 python-magic (https://github.com/ahupp/python-magic)

【讨论】:

    【解决方案7】:

    您可以使用预提交挂钩脚本来检查文件是二进制文件还是文本文件。

    【讨论】:

    • 坏主意,例如,您不能为网站添加图片。扩展检查要好得多
    猜你喜欢
    • 2011-10-13
    • 2015-01-04
    • 2010-09-16
    • 2011-07-27
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多