use crate::cli::LocMode;
use crate::content::io;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
pub struct LocCounter {
mode: LocMode,
max_file_size: u64,
}
impl LocCounter {
pub fn new(mode: LocMode) -> Self {
Self {
mode,
max_file_size: 10 * 1024 * 1024,
}
}
pub fn count_lines(&self, path: &Path) -> Option<usize> {
if self.mode == LocMode::Off {
return None;
}
if !path.is_file() {
return None;
}
if io::is_too_large(path, self.max_file_size) {
return None;
}
if io::is_binary_extension(path) {
return None;
}
match io::probe_file(path, 8192) {
Ok(probe) => {
if probe.is_binary {
return None;
}
}
Err(_) => return None,
}
match self.mode {
LocMode::Off => None,
LocMode::Fast => self.count_lines_fast(path),
LocMode::Accurate => self.count_lines_accurate(path),
}
}
fn count_lines_fast(&self, path: &Path) -> Option<usize> {
let file = File::open(path).ok()?;
let reader = BufReader::new(file);
let mut count = 0;
for _ in reader.lines() {
count += 1;
if count > 100_000 {
break;
}
}
Some(count)
}
fn count_lines_accurate(&self, path: &Path) -> Option<usize> {
let file = File::open(path).ok()?;
let reader = BufReader::new(file);
let mut count = 0;
for line in reader.lines() {
if let Ok(line_str) = line {
let trimmed = line_str.trim();
if trimmed.is_empty() {
continue;
}
if trimmed.starts_with("//")
|| trimmed.starts_with('#')
|| trimmed.starts_with("/*")
|| trimmed.starts_with("*")
{
continue;
}
count += 1;
}
if count > 100_000 {
break;
}
}
Some(count)
}
}
impl Default for LocCounter {
fn default() -> Self {
Self::new(LocMode::Fast)
}
}