如何在提交时限制文件大小?

Yuv*_*mon 10 linux git github filesize

我完全清楚这个问题在技​​术上使这个问题重复,但答案只提供推送解决方案,这对我的要求来说太晚了.

提交时是否有限制文件大小的选项?

例如:500K以上的文件大小会产生警告.超过10M的文件大小将停止提交.

Leo*_*eon 10

这个预提交钩子将进行文件大小检查:

的.git /钩/预提交

#!/bin/sh
hard_limit=$(git config hooks.filesizehardlimit)
soft_limit=$(git config hooks.filesizesoftlimit)
: ${hard_limit:=10000000}
: ${soft_limit:=500000}

list_new_or_modified_files()
{
    git diff --staged --name-status|sed -e '/^D/ d; /^D/! s/.\s\+//'
}

unmunge()
{
    local result="${1#\"}"
    result="${result%\"}"
    env echo -e "$result"
}

check_file_size()
{
    n=0
    while read -r munged_filename
    do
        f="$(unmunge "$munged_filename")"
        h=$(git ls-files -s "$f"|cut -d' ' -f 2)
        s=$(git cat-file -s "$h")
        if [ "$s" -gt $hard_limit ]
        then
            env echo -E 1>&2 "ERROR: hard size limit ($hard_limit) exceeded: $munged_filename ($s)"
            n=$((n+1))
        elif [ "$s" -gt $soft_limit ]
        then
            env echo -E 1>&2 "WARNING: soft size limit ($soft_limit) exceeded: $munged_filename ($s)"
        fi
    done

    [ $n -eq 0 ]
}

list_new_or_modified_files | check_file_size
Run Code Online (Sandbox Code Playgroud)

上面的脚本必须保存为.git/hooks/pre-commit启用执行权限(chmod +x .git/hooks/pre-commit).

默认的软(警告)和硬(错误)大小限制设置为500,000和10,000,000字节,但可以分别通过hooks.filesizesoftlimithooks.filesizehardlimit设置覆盖:

$ git config hooks.filesizesoftlimit 100000
$ git config hooks.filesizehardlimit 4000000
Run Code Online (Sandbox Code Playgroud)


Con*_*Kay 5

@Leon 脚本的较短的、特定于 bash 的版本,它以人类可读的格式打印文件大小。它需要一个更新的 git 选项--diff-filter=d

#!/bin/bash
hard_limit=$(git config hooks.filesizehardlimit)
soft_limit=$(git config hooks.filesizesoftlimit)
: ${hard_limit:=10000000}
: ${soft_limit:=1000000}

status=0

bytesToHuman() {
  b=${1:-0}; d=''; s=0; S=({,K,M,G,T,P,E,Z,Y}B)
  while ((b > 1000)); do
    d="$(printf ".%01d" $((b % 1000 * 10 / 1000)))"
    b=$((b / 1000))
    let s++
  done
  echo "$b$d${S[$s]}"
}

# Iterate over the zero-delimited list of staged files.
while IFS= read -r -d '' file ; do
  hash=$(git ls-files -s "$file" | cut -d ' ' -f 2)
  size=$(git cat-file -s "$hash")

  if (( $size > $hard_limit )); then
    echo "Error: Cannot commit '$file' because it is $(bytesToHuman $size), which exceeds the hard size limit of $(bytesToHuman $hard_limit)."
    status=1
  elif (( $size > $soft_limit )); then
    echo "Warning: '$file' is $(bytesToHuman $size), which exceeds the soft size limit of $(bytesToHuman $soft_limit). Please double check that you intended to commit this file."
  fi
done < <(git diff -z --staged --name-only --diff-filter=d)
exit $status
Run Code Online (Sandbox Code Playgroud)

与其他答案一样,必须使用执行权限将其保存为.git/hooks/pre-commit.

输出示例:

Error: Cannot commit 'foo' because it is 117.9MB, which exceeds the hard size limit of 10.0MB.
Run Code Online (Sandbox Code Playgroud)