
| Current Path : /bin/ |
Linux ift1.ift-informatik.de 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64 |
| Current File : //bin/git-sed |
#!/usr/bin/env bash
# reset environment variables that could interfere with normal usage
unset GREP_OPTIONS
# put all utility functions here
# make a temporary file
git_extra_mktemp() {
mktemp -t "$(basename "$0")".XXXXXXX
}
#
# check whether current directory is inside a git repository
#
is_git_repo() {
git rev-parse --show-toplevel > /dev/null 2>&1
result=$?
if test $result != 0; then
>&2 echo 'Not a git repo!'
exit $result
fi
}
is_git_repo
usage() {
cat <<EOF
usage: git sed [ -c ] [ -f <flags> ] <search> <replacement> [ <flags> ]
Run git grep and then send results to sed for replacement with the
given flags, if they are provided via -f or as the third argument.
Also runs git commit if -c is provided.
EOF
}
# don't commit by default
do_commit() {
true
}
while [ "X$1" != "X" ]; do
case "$1" in
-c|--commit)
if git status --porcelain | grep .; then
echo "you need to commit your changes before running with --commit"
exit 1
fi
do_commit() {
git commit -m"replace $search with $replacement
actual command:
$command" -a
}
;;
-f|--flags)
if [ "X$2" = "X" ]; then
usage
echo "missing argument for $1"
exit 1
fi
shift
flags=$1
;;
-h|--help)
usage
exit
;;
-*)
usage
echo "unknown flag: $1"
exit 1
;;
*)
if [ "X$search" = "X" ]; then
search="$1"
elif [ "X$replacement" = "X" ]; then
replacement="$1"
elif [ "X$flags" = "X" ]; then
flags="$1"
else
usage
echo "too many arguments: $1"
exit 1
fi
;;
esac
shift
done
all="$search$replacement$flags"
case "$all" in
*/*)
ascii="$(for((i=32;i<=127;i++)) do printf '%b' "\\$(printf '%03o' "$i")"; done)"
escaped="${all//-/\\-}"
escaped="${escaped//[/\\[}"
sep="$(printf '%s' "$ascii" | tr -d "$escaped")"
sep="$(printf %.1s "$sep")"
if [ "X$sep" = "X" ] ; then
echo 'could not find an unused character for sed separator character'
exit 1
fi
;;
*)
sep=/
;;
esac
r=$(xargs -r false < /dev/null > /dev/null 2>&1 && echo r)
need_bak=$(sed -i s/hello/world/ "$(git_extra_mktemp)" > /dev/null 2>&1 || echo true)
if [ "$need_bak" ]; then
command="git grep -lz '$search' | xargs -0$r sed -i '' 's$sep$search$sep$replacement$sep$flags'"
git grep -lz "$search" | xargs -0"$r" sed -i '' "s$sep$search$sep$replacement$sep$flags"
else
command="git grep -lz '$search' | xargs -0$r sed -i 's$sep$search$sep$replacement$sep$flags'"
git grep -lz "$search" | xargs -0"$r" sed -i "s$sep$search$sep$replacement$sep$flags"
fi
do_commit