Вопрос по git – Git: показать общую разницу в размере файла между двумя коммитами?
Можно ли показать общую разницу в размере файла между двумя коммитами? Что-то вроде:
$ git file-size-diff 7f3219 bad418 # I wish this worked :)
-1234 bytes
Я пытался:
$ git diff --patch-with-stat
И это показывает разницу в размере файла для каждогоbinary файл в diff & # x2014; но не для текстовых файлов, а не для разницы общего размера файла.
Есть идеи?
скому размеру файла / контента. Это можно найти наhttps://github.com/matthiaskrgr/gitdiffbinstat а также обнаруживает переименования файлов.
Расширение наответ matthiaskrgr, https://github.com/matthiaskrgr/gitdiffbinstat можно использовать как другие скрипты:
gitdiffbinstat.sh HEAD..HEAD~4
По-моему, это действительно хорошо работает, гораздо быстрее, чем все остальное, размещенное здесь. Пример вывода:
$ gitdiffbinstat.sh HEAD~6..HEAD~7
HEAD~6..HEAD~7
704a8b56161d8c69bfaf0c3e6be27a68f27453a6..40a8563d082143d81e622c675de1ea46db706f22
Recursively getting stat for path "./c/data/gitrepo" from repo root......
105 files changed in total
3 text files changed, 16 insertions(+), 16 deletions(-) => [±0 lines]
102 binary files changed 40374331 b (38 Mb) -> 39000258 b (37 Mb) => [-1374073 b (-1 Mb)]
0 binary files added, 3 binary files removed, 99 binary files modified => [-3 files]
0 b added in new files, 777588 b (759 kb) removed => [-777588 b (-759 kb)]
file modifications: 39596743 b (37 Mb) -> 39000258 b (37 Mb) => [-596485 b (-582 kb)]
/ ==> [-1374073 b (-1 Mb)]
Выходной каталог в стиле фанк с ./c/data ... так как / c на самом деле является корневым каталогом файловой системы.
git cat-file -s
выведет размер в байтах объекта в git.git diff-tree
могу рассказать вам различия между одним деревом и другим.
Собираем это вместе в скриптgit-file-size-diff
расположенный где-то на вашем PATH даст вам возможность позвонитьgit file-size-diff <tree-ish> <tree-ish>
, Мы можем попробовать что-то вроде следующего:
#!/bin/bash
USAGE='[--cached] [<rev-list-options>...]
Show file size changes between two commits or the index and a commit.'
. "$(git --exec-path)/git-sh-setup"
args=$(git rev-parse --sq "[email protected]")
[ -n "$args" ] || usage
cmd="diff-tree -r"
[[ $args =~ "--cached" ]] && cmd="diff-index"
eval "git $cmd $args" | {
total=0
while read A B C D M P
do
case $M in
M) bytes=$(( $(git cat-file -s $D) - $(git cat-file -s $C) )) ;;
A) bytes=$(git cat-file -s $D) ;;
D) bytes=-$(git cat-file -s $C) ;;
*)
echo >&2 warning: unhandled mode $M in \"$A $B $C $D $M $P\"
continue
;;
esac
total=$(( $total + $bytes ))
printf '%d\t%s\n' $bytes "$P"
done
echo total $total
}
В использовании это выглядит следующим образом:
$ git file-size-diff HEAD~850..HEAD~845
-234 Documentation/RelNotes/1.7.7.txt
112 Documentation/git.txt
-4 GIT-VERSION-GEN
43 builtin/grep.c
42 diff-lib.c
594 git-rebase--interactive.sh
381 t/t3404-rebase-interactive.sh
114 t/test-lib.sh
743 tree-walk.c
28 tree-walk.h
67 unpack-trees.c
28 unpack-trees.h
total 1914
Используяgit-rev-parse
он должен принимать все обычные способы указания диапазонов фиксации.
РЕДАКТИРОВАТЬ: обновлено, чтобы записать совокупный итог. Обратите внимание, что bash запускает чтение пока в подоболочке, следовательно, дополнительные фигурные скобки, чтобы избежать потери общего количества при выходе из подоболочки.
РЕДАКТИРОВАТЬ: добавлена поддержка сравнения индекса с другой древовидной версией с помощью--cached
аргумент для вызоваgit diff-index
вместоgit diff-tree
, например:
$ git file-size-diff --cached master
-570 Makefile
-134 git-gui.sh
-1 lib/browser.tcl
931 lib/commit.tcl
18 lib/index.tcl
total 244
git-sh-setup
Error: User Rate Limit Exceededany of the functions it definesError: User Rate Limit Exceeded
Mathias Bynens
curl -s https://gist.githubusercontent.com/cschell/9386715/raw/43996adb0f785a5afc17358be7a43ff7ee973215/git-file-size-diff | bash -s <tree-ish> <tree-ish>
git rev-parse
Error: User Rate Limit Exceededgit-scm.com/docs/git-rev-parse)
git-file-size-diff, предложенный patthoyts. Сценарий очень полезен, однако я обнаружил две проблемы:
When someone change permissions on the file, git returns a another type in the case statement:
T) echo >&2 "Skipping change of type"
continue ;;
If a sha-1 value doesn't exist anymore (for some reason), the script crashes. You need to validate the sha before getting the file size:
$(git cat-file -e $D)
if [ "$?" = 1 ]; then continue; fi
Полный оператор case будет выглядеть так:
case $M in
M) $(git cat-file -e $D)
if [ "$?" = 1 ]; then continue; fi
$(git cat-file -e $C)
if [ "$?" = 1 ]; then continue; fi
bytes=$(( $(git cat-file -s $D) - $(git cat-file -s $C) )) ;;
A) $(git cat-file -e $D)
if [ "$?" = 1 ]; then continue; fi
bytes=$(git cat-file -s $D) ;;
D) $(git cat-file -e $C)
if [ "$?" = 1 ]; then continue; fi
bytes=-$(git cat-file -s $C) ;;
T) echo >&2 "Skipping change of type"
continue ;;
*)
echo >&2 warning: unhandled mode $M in \"$A $B $C $D $M $P\"
continue
;;
esac
git show some-ref:some-path-to-file | wc -c
git show some-other-ref:some-path-to-file | wc -c
и сравните 2 числа.