-
-
Save jamesbraza/ba2848d71644f4c3496def4c1a1d9fc8 to your computer and use it in GitHub Desktop.
Black on selection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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