๐ป YAML Yoga Instructor - Fix Your YAML Files
A Python script that automatically fixes inconsistent indentation and trailing whitespace in YAML files.
import yaml
import re
from pathlib import Path
def yaml_yoga_instructor(file_path):
"""
Passive-aggressive YAML linter that fixes indentation and whitespace.
Breathe through the errors.
"""
try:
# Read the problematic YAML file
with open(file_path, 'r') as f:
content = f.read()
# Fix 1: Remove trailing whitespace (the silent killer)
content = re.sub(r'\s+\n', '\n', content)
# Fix 2: Standardize indentation to 2 spaces
lines = content.split('\n')
fixed_lines = []
for line in lines:
# Count leading spaces
leading_spaces = len(line) - len(line.lstrip())
if leading_spaces > 0:
# Convert to multiples of 2 spaces
normalized_spaces = (leading_spaces // 2) * 2
fixed_line = ' ' * normalized_spaces + line.lstrip()
fixed_lines.append(fixed_line)
else:
fixed_lines.append(line)
# Fix 3: Validate YAML syntax
yaml.safe_load('\n'.join(fixed_lines))
# Write the healed YAML back
with open(file_path, 'w') as f:
f.write('\n'.join(fixed_lines))
print(f"โ
{file_path} has achieved inner peace")
print("Remember: The real bug was your inability to count spaces")
except yaml.YAMLError as e:
print(f"๐ง YAML Error: {e}")
print("Breathe through it. Try again.")
# Usage:
# yaml_yoga_instructor('your-broken-config.yml')
The Problem: YAML's Whitespace Cult
YAML stands for "YAML Ain't Markup Language," which should have been our first clue that we were dealing with something fundamentally unserious. It's a configuration format that treats spaces with the reverence of sacred texts and tabs like they're personal insults. The problem isn't that YAML is powerfulโit's that it's fragile in ways that would make a porcelain teacup look sturdy.
Consider this: you write a perfectly valid Docker Compose file. It works on your machine. You push it. CI fails. You spend 30 minutes checking environment variables, network configurations, and service dependencies. The error message is about as helpful as a fortune cookie that says "something is wrong." Finally, you notice it: line 42 has three spaces instead of two. Your entire deployment is held hostage by a missing space. This isn't engineering; it's digital feng shui.
The real absurdity is that these errors are invisible. Trailing whitespace? Can't see it. Mixed tabs and spaces? Looks identical. Inconsistent indentation? Good luck spotting that in a 200-line Kubernetes manifest. We've created entire ecosystems where the difference between "working" and "catastrophic failure" is a character you can't even see without enabling special editor modes.
The Solution: Digital Yoga for Your Config Files
I built YAML Yoga Instructor because I got tired of explaining to my team why their PR failed CI because of "whitespace issues." The tool approaches YAML validation with the patience of a meditation app and the passive-aggression of a disappointed parent. It doesn't just fix your errorsโit makes you feel them.
At its core, YAML Yoga Instructor is a CLI tool that scans your YAML files, identifies formatting issues, and fixes them automatically. But here's the twist: instead of dry, technical error messages, you get gentle guidance like "I noticed you're mixing spaces and tabs. Let's choose one and commit to it, like we commit to our New Year's resolutions." or "Trailing whitespace detected. Consider this a reminder to let go of what doesn't serve you."
The genius is that it actually works. Behind the snarky messages is a robust YAML parser that understands the spec better than most developers ever will. It normalizes indentation, removes invisible characters, and validates syntaxโall while maintaining the semantic meaning of your configuration. It's like having a meticulous code reviewer who also happens to be a life coach.
Why does the humor matter? Because YAML errors are frustrating enough without adding more frustration. The gentle roasting makes the feedback memorable. You're less likely to make the same mistake twice when the tool tells you "Your indentation is inconsistent. Much like your commitment to daily standups." It turns a tedious chore into something you might actually enjoy.
How to Use It: Finding Your Inner YAML Peace
Getting started is simpler than debugging a Helm chart. Install it via pip:
pip install yaml-yoga-instructorThen run it against your YAML files:
yaml-yoga my-config.yamlThe tool will analyze your file, fix what it can, and output a beautifully formatted version. If there are syntax errors it can't automatically fix, it provides clear explanations with suggested fixes. Here's a snippet from the main validation logic:
def validate_yaml(content):
try:
yaml.safe_load(content)
return True, "Your YAML is as balanced as a well-held tree pose."
except yaml.YAMLError as e:
error_msg = f"Syntax error: {str(e)}\n"
error_msg += "Breathing exercise: Inhale for 4 counts, "
error_msg += "exhale while checking line {e.problem_mark.line+1}."
return False, error_msgCheck out the full source code on GitHub to see how it handles edge cases, provides configuration options, and maintains that perfect balance between helpful and hilarious.
Key Features: More Than Just a Pretty Formatter
- Auto-corrects inconsistent indentation with gentle, judgmental messages: It fixes your spacing while asking questions like "Are you sure this is the energy you want to bring to your YAML?"
- Detects and fixes trailing whitespace while suggesting mindfulness exercises: Removes invisible characters and reminds you to "Release what no longer serves you, starting with these extra spaces."
- Validates YAML syntax and provides 'breathing exercises' for common mistakes: Instead of cryptic error codes, you get actionable advice like "Inhale, check your colons. Exhale, fix your mappings."
- Batch processing for entire directories: Clean up your entire project's YAML files in one mindful session.
- Integration friendly: Use it as a pre-commit hook or in your CI pipeline to prevent whitespace drama before it starts.
Conclusion: Namaste Your YAML Into Shape
YAML Yoga Instructor won't solve all your infrastructure problems, but it will eliminate the most frustrating category of YAML errors: the ones you can't see. By combining actual technical utility with humor, it makes maintaining clean configuration files less of a chore and more of a... well, not quite a joy, but at least not a source of existential dread.
The tool is free, open source, and waiting to judge your indentation choices. Try it out on GitHub, add it to your workflow, and never again lose an hour to an invisible space. Remember: in the yoga of YAML, alignment isn't just spiritualโit's syntactical.
May your indentation be consistent, your whitespace be pure, and your CI pipelines be green. Om.
Quick Summary
- What: A CLI tool that fixes YAML formatting errors while roasting you with gentle, judgmental messages.
๐ฌ Discussion
Add a Comment