Welcome to another insightful edition of TWIL, where we distill our journey through code into weekly packets of learning. This week features Katie's breakthrough with a bash function that streamlines running code linters like ruff
on file batches, transforming the git commit preparation from a chore into a learning opportunity.
Batch ruff --fix by git status
I made a bash function to let me run ruff --fix
on batches of files based on git status (or on all changed files) at once; for example, when I go to commit changes and the pre-commit-hook ruff tells me i've missed some things, instead of running ruff --fix
for each affected file, I can now do ruff-fix A
to run it for the files I've got staged for commit (which then also lets me review those diffs versus what I've got staged, so I can learn from the changes ruff makes, too).
# ruff --fix changed files all at once
ruff-fix()
{
# Fix files with staged changes
if [[ $1 = "staged" ]] || [[ $1 = "added" ]] || [[ $1 = "A" ]]; then
GIT_STATE="A"
# Fix files with unstaged changes
elif [[ $1 = "unstaged" ]] || [[ $1 = "unadded" ]] || [[ $1 = "modified" ]] || [[ $1 = "M" ]]; then
GIT_STATE="M"
# Fix untracked files
elif [[ $1 = "untracked" ]] || [[ $1 = "new" ]] || [[ $1 = "U" ]] || [[ $1 = "??" ]]; then
GIT_STATE="??"
# Fix all modified files (staged/unstaged/untracked/whatever)
else
GIT_STATE="."
fi
git status -s | grep "$GIT_STATE" | cut -c 4- | xargs ruff --fix
}
- Bash
- git