vibe_coding_tracker 0.5.12

Vibe Coding Tracker - AI coding assistant telemetry/usage parser, aggregate JSONL events into CodeAnalysis results
Documentation
use crate::constants::buffer;
use anyhow::{Context, Result};
use serde_json::Value;
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::path::Path;

/// Reads a JSONL file and returns all JSON objects
///
/// Each non-empty line is parsed as a separate JSON object. Pre-allocates capacity
/// based on file size estimation for optimal performance.
pub fn read_jsonl<P: AsRef<Path>>(path: P) -> Result<Vec<Value>> {
    let file = File::open(path.as_ref())
        .with_context(|| format!("Failed to open file: {}", path.as_ref().display()))?;

    // Pre-allocate Vec capacity based on estimated line count
    // This reduces allocations and improves performance significantly
    let file_size = file.metadata().ok().map(|m| m.len() as usize).unwrap_or(0);
    let estimated_lines = if file_size > 0 {
        // Use centralized constant for average line size estimation
        file_size / buffer::AVG_JSONL_LINE_SIZE
    } else {
        10 // Default minimum capacity
    };
    let mut results = Vec::with_capacity(estimated_lines);

    // Use centralized buffer size constant for optimal I/O performance
    let reader = BufReader::with_capacity(buffer::FILE_READ_BUFFER, file);

    for (index, line) in reader.lines().enumerate() {
        let line = line.with_context(|| format!("Failed to read line {}", index + 1))?;

        if line.trim().is_empty() {
            continue;
        }

        let obj: Value = serde_json::from_str(&line)
            .with_context(|| format!("Failed to parse JSON at line {}", index + 1))?;

        results.push(obj);
    }

    // Shrink capacity to actual size to free excess memory
    results.shrink_to_fit();

    Ok(results)
}

/// Reads a JSON file and returns it as a single-element vector for consistency
pub fn read_json<P: AsRef<Path>>(path: P) -> Result<Vec<Value>> {
    let file = File::open(path.as_ref())
        .with_context(|| format!("Failed to open file: {}", path.as_ref().display()))?;

    // Pre-allocate String capacity based on file size to reduce allocations
    let file_size = file.metadata().ok().map(|m| m.len() as usize).unwrap_or(0);
    let mut contents = String::with_capacity(file_size);

    // Use centralized buffer size constant for optimal I/O performance
    let mut reader = BufReader::with_capacity(buffer::FILE_READ_BUFFER, file);
    reader
        .read_to_string(&mut contents)
        .with_context(|| format!("Failed to read file: {}", path.as_ref().display()))?;

    let obj: Value = serde_json::from_str(&contents).with_context(|| {
        format!(
            "Failed to parse JSON from file: {}",
            path.as_ref().display()
        )
    })?;

    Ok(vec![obj])
}

/// Counts lines in text using SIMD-accelerated byte counting
///
/// Uses the `bytecount` crate for ~2.9% faster performance compared to standard iteration.
pub fn count_lines(text: &str) -> usize {
    if text.is_empty() {
        return 0;
    }
    // Use bytecount for much faster line counting (SIMD-accelerated)
    // Count newlines and add 1 if text doesn't end with newline
    let newline_count = bytecount::count(text.as_bytes(), b'\n');
    if text.ends_with('\n') {
        newline_count
    } else {
        newline_count + 1
    }
}

/// Saves JSON data to a file with pretty formatting
pub fn save_json_pretty<P: AsRef<Path>>(path: P, value: &Value) -> Result<()> {
    let json_str = serde_json::to_string_pretty(value).context("Failed to serialize JSON")?;

    std::fs::write(path.as_ref(), json_str)
        .with_context(|| format!("Failed to write file: {}", path.as_ref().display()))?;

    Ok(())
}