#!/bin/bash
# Copyright (C) 2019 Stefano Zacchiroli <zack@upsilon.cc>
# License: GNU General Public License (GPL), version 3 or above
#
# Leverages git history to generate, and optionally build, a .tex document
# highlighting differences (a la track change) using latexdiff
#
# Depends: git, latexdiff, latex2html (for texexpand), latexmk (only for -b)
set -e # to barf in case of git failures due to potentially dangerous actions
info() {
echo -e "$1" 1>&2
}
die_error() {
info "$1"
exit 1
}
if [ -z "$1" -o -z "$2" -o -z "$3" ] ; then
info "Usage: git-latexdiff [OPTIONS] MAIN_TEX GIT_REVISION_OLD GIT_REVISION_NEW"
info "Options:"
info " -b/--build: also build generated .tex (using latexmk -pdf)"
exit 1
fi
build_tex="no"
if [ "$1" = "-b" -o "$1" = "--build" ] ; then
build_tex="yes"
shift 1
fi
MAIN_TEX="$1"
GIT_OLD_REV="$2"
GIT_NEW_REV="$3"
old_tmp="${MAIN_TEX%.tex}--${GIT_OLD_REV//\//-}.tex" # escape all '/' with '-'
new_tmp="${MAIN_TEX%.tex}--${GIT_NEW_REV//\//-}.tex" # ditto
diff_tmp="${MAIN_TEX%.tex}--${GIT_OLD_REV//\//-}--${GIT_NEW_REV//\//-}.tex"
# for tmpfile in "$old_tmp" "$new_tmp" "$diff_tmp" ; do
# if [ -f "$tmpfile" ] ; then
# info "Abort: $tmpfile (from a previous round?) is still around."
# info "Remove it to continue."
# exit 1
# fi
# done
git checkout "$GIT_OLD_REV"
texexpand "$MAIN_TEX" > "$old_tmp"
git checkout "$GIT_NEW_REV"
texexpand "$MAIN_TEX" > "$new_tmp"
git switch '@{-2}'
latexdiff "$old_tmp" "$new_tmp" > "$diff_tmp"
rm -f "$old_tmp" "$new_tmp"
if [ "$build_tex" = "yes" ] ; then
latexmk -pdf "$diff_tmp"
latexmk -c "$diff_tmp"
rm -f "${diff_tmp%.tex}.bbl" # latexmk -c leaves .bbl arounds
fi