2011-12-02 81 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