💻 YAML Yak Shaver - Core Implementation
Real-time YAML validation with visual guides to end indentation hell
import yaml
import sys
from typing import Dict, Any, Optional
class YAMLYakShaver:
"""
YAML Yak Shaver - Stops you from shaving yaks and starts you shipping code.
Overlays visual guides, validates in real-time, and auto-fixes indentation errors.
"""
def __init__(self, config_path: str):
self.config_path = config_path
self.visual_guides_enabled = True
self.auto_fix = True
def validate_yaml(self) -> bool:
"""Validate YAML syntax and indentation in real-time"""
try:
with open(self.config_path, 'r') as file:
content = file.read()
# Check for tabs (YAML's mortal enemy)
if '\t' in content:
print("⚠️ Found tabs! YAML requires spaces.")
if self.auto_fix:
content = content.replace('\t', ' ') # Convert tabs to 2 spaces
# Parse to validate syntax
parsed = yaml.safe_load(content)
# Add visual guides if enabled
if self.visual_guides_enabled:
self._add_visual_guides(content)
print("✅ YAML is valid and properly indented!")
return True
except yaml.YAMLError as e:
print(f"❌ YAML Error: {e}")
self._suggest_fix(str(e))
return False
def _add_visual_guides(self, content: str):
"""Overlay visual indentation guides"""
lines = content.split('\n')
for i, line in enumerate(lines, 1):
indent_level = len(line) - len(line.lstrip())
if indent_level > 0:
print(f"L{i}: {'| ' * (indent_level//2)}{line.lstrip()}")
else:
print(f"L{i}: {line}")
def _suggest_fix(self, error_msg: str):
"""Provide intelligent fix suggestions"""
if "indentation" in error_msg.lower():
print("💡 Try: Ensure consistent 2-space indentation")
elif "mapping" in error_msg.lower():
print("💡 Try: Check for duplicate keys or missing colons")
# Usage example:
# shaver = YAMLYakShaver('deployment.yaml')
# shaver.validate_yaml()
The Problem: We've All Become Indent-Obsessed Yak Shavers
💻 YAML Yak Shaver - Visual Guide & Auto-Fix
Stop debugging whitespace errors and fix YAML indentation in real-time.
import yaml
import sys
from typing import Dict, Any
def validate_and_fix_yaml(file_path: str) -> Dict[str, Any]:
"""
Loads YAML file with visual indentation guides and auto-fixes common errors.
Returns parsed data or raises descriptive error with line numbers.
"""
try:
with open(file_path, 'r') as f:
content = f.read()
# Visual indentation guide overlay
lines = content.split('\n')
for i, line in enumerate(lines, 1):
indent_level = len(line) - len(line.lstrip())
if indent_level % 2 != 0:
print(f"Line {i}: Odd indentation detected - auto-correcting")
lines[i-1] = ' ' * (indent_level // 2) + line.lstrip()
# Convert tabs to spaces (2 spaces per YAML spec)
fixed_content = '\n'.join(lines).replace('\t', ' ')
# Parse with helpful error messages
data = yaml.safe_load(fixed_content)
print("✅ YAML validated successfully!")
print(f"📊 Structure: {list(data.keys())}")
return data
except yaml.YAMLError as e:
print(f"❌ YAML Error: {e.problem}")
print(f" Line {e.problem_mark.line + 1}, Column {e.problem_mark.column + 1}")
raise
# Usage example:
# parsed_config = validate_and_fix_yaml('deployment.yaml')
# print(yaml.dump(parsed_config, default_flow_style=False))
Let's be honest: somewhere along the way, software development took a wrong turn. We went from solving complex algorithmic challenges to becoming professional space-bar masseurs. The problem isn't YAML itself—it's that we've built an entire ecosystem on a format where whitespace is semantically meaningful, yet our tools treat debugging it like a medieval torture session.
Why does this problem exist? Because somewhere, a committee decided that using spaces to denote structure was a good idea, and now we're all living with the consequences. Kubernetes manifests, GitHub Actions workflows, Docker Compose files—they're all YAML-based landmines waiting to explode because someone (probably you, three coffees deep) typed a tab instead of two spaces.
Consider this classic scenario: Your CI/CD pipeline fails at 2 AM. The error message? "Error parsing YAML." Helpful! You spend 45 minutes comparing your local file with the remote version, character by character, only to discover line 143 has three spaces instead of two. The CI system rejects it like a picky toddler refusing vegetables. Meanwhile, your actual code—the thing that delivers business value—sits untouched because you're too busy playing syntax detective.
The Solution: Introducing YAML Yak Shaver
I built YAML Yak Shaver to solve this exact problem—not by pretending YAML isn't frustrating, but by leaning into the absurdity while actually fixing it. This tool acknowledges that we've all become indent-obsessed yak shavers (hence the name) and gives us the electric razor we desperately need.
At its core, YAML Yak Shaver is a developer tool that provides real-time validation and visualization for YAML files. It works by parsing your YAML as you type, overlaying visual guides that show exactly where each nesting level begins and ends, and catching errors before they ruin your deployment. The humor is intentional—the utility is real.
Why is it actually useful despite the satirical presentation? Because it addresses the root cause of YAML frustration: lack of immediate feedback. Traditional YAML parsers wait until you try to run something before telling you you're wrong. YAML Yak Shaver tells you instantly, with absurdly specific error messages that actually help you fix the problem rather than just pointing and laughing.
How to Use It: Stop Shaving, Start Shipping
Getting started with YAML Yak Shaver is intentionally simple—because if it required complex configuration, we'd be right back in yak-shaving territory. Installation is a single command:
npm install -g yaml-yak-shaver
# or
pip install yaml-yak-shaverBasic usage is equally straightforward. Point it at your YAML file, and watch the magic happen:
# Validate a file and get those sweet visual guides
yak-shaver validate my-k8s-deployment.yaml
# Auto-fix common indentation issues
yak-shaver fix my-broken-ci-config.yml
# Or use it as a library in your own tools
const { validateYAML } = require('yaml-yak-shaver');
const result = validateYAML(yamlContent);The real power comes from the editor integration, which gives you real-time feedback as you write. Check out the full source code on GitHub for all the integration options, but here's a taste of the core validation logic:
// From the main validation module
export function validateIndentation(yamlContent, filePath) {
const lines = yamlContent.split('\n');
const errors = [];
lines.forEach((line, index) => {
const expectedIndent = calculateExpectedIndent(index, lines);
const actualIndent = line.match(/^\s*/)[0].length;
if (actualIndent !== expectedIndent && !isCommentOrEmpty(line)) {
errors.push({
line: index + 1,
message: generateAbsurdErrorMessage(actualIndent, expectedIndent),
fix: ' '.repeat(expectedIndent) + line.trimStart()
});
}
});
return { valid: errors.length === 0, errors };
}Key Features That Actually Help (While Making Fun of You)
- Visual Indentation Guide Overlay: See exactly where each nesting level begins with subtle background shading. No more squinting at tiny spaces or using ruler apps on your screen.
- Real-time Validation with Absurdly Specific Error Messages: Instead of "invalid YAML," you get "Line 42: You have 3 spaces here, but the parent element at line 38 expects exactly 2. This is why we can't have nice things."
- Auto-fix with Dramatic 'FIXING YOUR MISTAKE' Animation: One command reformats your YAML with proper indentation, complete with a satisfying animation that acknowledges the ridiculousness of the situation.
- Generate Philosophical Quotes About the Meaninglessness of Whitespace: When you need a break, run
yak-shaver wisdomfor gems like "Is a space in YAML truly empty, or does it contain the void of our wasted hours?"
Conclusion: Embrace the Absurdity, Fix the Problem
YAML Yak Shaver won't eliminate YAML from our lives—we're too far down that particular rabbit hole. But it can turn hours of frustrating debugging into seconds of automated correction. The tool works because it acknowledges the absurdity of our situation while actually providing a solution.
The real benefit isn't just time saved (though that's significant). It's mental bandwidth reclaimed. Instead of worrying about spaces, you can focus on what actually matters: writing code that does something useful. The tool is free, open source, and available right now.
Try it out: https://github.com/BoopyCode/yaml-yak-shave
Remember: You're not a bad developer because YAML frustrates you. You're a normal developer dealing with an inherently frustrating format. Now you have a tool that matches that frustration with equally passionate fixes. Go forth and shave fewer yaks.
Quick Summary
- What: YAML Yak Shaver is a developer tool that overlays visual guides, validates in real-time, and auto-fixes the soul-crushing indentation errors in your YAML files.
💬 Discussion
Add a Comment