#!/bin/bash set -euo pipefail echo "=== Fixing additional unwrap_used violations in services (Agent W17 Phase 3) ===" # Count before BEFORE=$(grep -r "\.unwrap()" services/api_gateway/src services/trading_service/src services/backtesting_service/src services/ml_training_service/src 2>/dev/null | wc -l) echo "Found $BEFORE .unwrap() calls in services" # Pattern 13: File/Path operations echo "Fixing Pattern 13: Path/File operations → expect()" find services/ -name "*.rs" -type f -exec sed -i \ 's/\.to_str()\.unwrap()/\.to_str().expect("INVARIANT: Path should be valid UTF-8")/g' {} + find services/ -name "*.rs" -type f -exec sed -i \ 's/\.to_string_lossy()\.unwrap()/\.to_string_lossy().expect("INVARIANT: Path conversion should succeed")/g' {} + # Pattern 14: Iterator operations echo "Fixing Pattern 14: Iterator operations → expect()" find services/ -name "*.rs" -type f -exec sed -i \ 's/\.next()\.unwrap()/\.next().expect("INVARIANT: Iterator should have next element")/g' {} + find services/ -name "*.rs" -type f -exec sed -i \ 's/\.nth(\([^)]*\))\.unwrap()/\.nth(\1).expect("INVARIANT: Iterator should have nth element")/g' {} + # Pattern 15: Map/HashMap/BTreeMap operations echo "Fixing Pattern 15: Map get operations → expect()" find services/ -name "*.rs" -type f -exec sed -i \ 's/\.get(\([^)]*\))\.unwrap()/\.get(\1).expect("INVARIANT: Key should exist in map")/g' {} + find services/ -name "*.rs" -type f -exec sed -i \ 's/\.get_mut(\([^)]*\))\.unwrap()/\.get_mut(\1).expect("INVARIANT: Key should exist in map")/g' {} + # Pattern 16: String/byte conversion echo "Fixing Pattern 16: String/byte conversion → expect()" find services/ -name "*.rs" -type f -exec sed -i \ 's/String::from_utf8(\([^)]*\))\.unwrap()/String::from_utf8(\1).expect("INVARIANT: Valid UTF-8 bytes")/g' {} + find services/ -name "*.rs" -type f -exec sed -i \ 's/std::str::from_utf8(\([^)]*\))\.unwrap()/std::str::from_utf8(\1).expect("INVARIANT: Valid UTF-8 bytes")/g' {} + # Pattern 17: OnceLock/OnceCell operations echo "Fixing Pattern 17: OnceLock/OnceCell operations → expect()" find services/ -name "*.rs" -type f -exec sed -i \ 's/\.set(\([^)]*\))\.unwrap()/\.set(\1).expect("INVARIANT: OnceLock should not be already set")/g' {} + # Pattern 18: TryInto/TryFrom operations echo "Fixing Pattern 18: TryInto/TryFrom operations → expect()" find services/ -name "*.rs" -type f -exec sed -i \ 's/\.try_into()\.unwrap()/\.try_into().expect("INVARIANT: Valid conversion")/g' {} + # Count after AFTER=$(grep -r "\.unwrap()" services/api_gateway/src services/trading_service/src services/backtesting_service/src services/ml_training_service/src 2>/dev/null | wc -l) FIXED=$((BEFORE - AFTER)) echo "" echo "Fixed $FIXED violations" echo "Remaining: $AFTER .unwrap() calls" echo "" echo "✓ Fix complete" echo "Review changes with: git diff"