2011-12-02 114 views
1

我想在Linux Bash中编写SVN预先提交钩子脚本,如果文件不能被解析为UTF-8,它将拒绝提交。如何检查提交给SVN的文件是否使用UTF-8编码并具有预提交挂钩?

到目前为止,我已经写了这个剧本:

REPOS="$1" 
TXN="$2" 

SVNLOOK=/usr/bin/svnlook 
ICONV=/usr/bin/iconv 

# Make sure that all files to be committed are encoded in UTF-8 

for FILE in $($SVNLOOK changed -t "$TXN" "$REPOS"); do 
    if [$ICONV -f UTF-8 $FILE -o /dev/null]; then 
     echo "Only UTF-8 files can be committed ("$FILE")" 1>&2 
     exit 1 
    fi 

# All checks passed, so allow the commit. 
exit 0 

的问题是,需要的iconv的路径提交的文件(或一些其他形式的文字),我不知道怎么弄它。

任何人都可以帮忙吗?

回答

1

使用svnlook cat从事务得到一个文件的内容:

$SVNLOOK cat -t "$TXN" "$REPOS" "$FILE" 
0

基于在原来的问题和this answer脚本,这里有一个预提交钩子,把所有的这一起:

#!/bin/bash 

REPOS="$1" 
TXN="$2" 

SVNLOOK=/usr/bin/svnlook 
ICONV=/usr/bin/iconv 

# Make sure that all files to be committed are encoded in UTF-8. 
$SVNLOOK changed -t "$TXN" "$REPOS" | while read changeline; do 

    # Get just the file (not the add/update/etc. status). 
    file=${changeline:4} 

    # Only check source files. 
    if [[ $file == *.cpp || $file == *.hpp || $file == *.c || $file == *.h ]] ; then 
     $SVNLOOK cat -t "$TXN" "$REPOS" "$file" 2>&1 | iconv -f UTF-8 -t UTF-8 >& /dev/null 
     if [ $? -ne 0 ] ; then 
      echo "Only UTF-8 files can be committed ("$file")" 1>&2 
      exit 1 
     fi 
    fi 
done 

# All checks passed, so allow the commit. 
exit 0 
3

顺便说一句,在这个answer有一个问题! 您需要测试$ SVNLOOK命令($?)的结果,因为指令“exit 1”在子进程中,因此脚本永远不会阻止提交:

#!/bin/bash 

REPOS="$1" 
TXN="$2" 
SVNLOOK=/usr/bin/svnlook 
ICONV=/usr/bin/iconv 

# Make sure that all files to be committed are encoded in UTF-8. 
$SVNLOOK changed -t "$TXN" "$REPOS" | while read changeline; do 

    # Get just the file (not the add/update/etc. status). 
    file=${changeline:4} 

    # Only check source files. 
    if [[ $file == *.cpp || $file == *.hpp || $file == *.c || $file == *.h ]] ; then 
     $SVNLOOK cat -t "$TXN" "$REPOS" $file 2>&1 | iconv -f UTF-8 -t UTF-8 >& /dev/null 
     if [ $? -ne 0 ] ; then 
      exit 1 
     fi 
    fi 
done 
test $? -eq 1 && echo "Only UTF-8 files can be committed" 1>&2 && exit 1 
exit 0