Skip to content

Instantly share code, notes, and snippets.

@jamesbraza
Forked from BasPH/black_selection.sh
Last active March 9, 2020 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jamesbraza/ba2848d71644f4c3496def4c1a1d9fc8 to your computer and use it in GitHub Desktop.
Save jamesbraza/ba2848d71644f4c3496def4c1a1d9fc8 to your computer and use it in GitHub Desktop.
Black on selection
#!/usr/bin/env bash
# Source: https://blog.godatadriven.com/black-formatting-selection
# Added debugging prints, permissioning/cleanup, and also a bugfix for
# selecting whole file.
# Print commands/arguments for debugging
set -x
# Inputs
black=$1
input_file=$2
start_line=$3
end_line=$4
# Read selected lines from input file
selection=$(sed -n "$start_line, $end_line p; $((end_line+1)) q" < "$input_file")
tmpfile=$(mktemp)
chmod 600 "$tmpfile" # Only user can read/write (not execute), for security
# Write to tmpfile and apply Black formatting
echo "$selection" > "$tmpfile"
$black "$tmpfile"
# Print tmpfile for debugging
echo -e "Reformatted code:\n---------------\n$(cat "$tmpfile")\n---------------"
# Delete original lines from input file
sed -i "" "$start_line,$end_line d" "$input_file"
# sed doesn't work on empty file, just assume if start line is 1, that the
# whole file was selected.
if [ "$start_line" == 1 ]
then
# sponge wasn't originally installed on my Mac... brew install moreutils
cat "$tmpfile" "$input_file" | sponge "$input_file" # prepend
else
sed -i "" "$((start_line-1)) r $tmpfile" "$input_file"
fi
# Cleanup tmpfile
rm -f "$tmpfile"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment