Featured blog post image of a Bash script in action, highlighting the use of automated linters for enhanced coding practices and learning.

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
Katie Linero's profile picture
Katie Linero

Senior Software Engineer

Related Posts

August 18, 2024 • Frank Valcarcel

What makes Enterprise Software Development Different?

Enterprise software powers large organizations, handling complex tasks across departments. From robust security to scalability, these solutions face unique challenges. Explore what makes software “enterprise-ready” and how to choose the right development approach for your business.

Image for 'This Week I Learned' blog post featuring tips on managing Git branches including renaming and syncing with remote changes.
October 8, 2019 • Frank Valcarcel

TWIL 2019-10-04

Join us for ‘TWIL,’ where Emily shares innovative Git tips for managing branches with rewritten history. Learn to sync local branches with remote changes and rename them effectively.