Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -213,12 +213,13 @@ jobs:

- name: Run benchmarks
run: |
git fetch origin ${{ github.base_ref }}
git checkout ${{ github.base_ref }}
# Check out by SHA: the PR branch does not exist in this repo for
# fork PRs, and a tag named like the base branch would shadow it.
git checkout --detach ${{ github.event.pull_request.base.sha }}
cargo bench --bench serialization --no-run
cargo bench --bench serialization -- --save-baseline ${{ github.base_ref }} '${{ matrix.benchmark_group.group }}/'

git checkout ${{ github.head_ref }}
git checkout --detach ${{ github.sha }}
cargo bench --bench serialization --no-run
cargo bench --bench serialization -- --baseline ${{ github.base_ref }} --noise-threshold 2 '${{ matrix.benchmark_group.group }}/' > benchmark_results.md
echo "## Benchmark Results for ${{ matrix.benchmark_group.name }}" >> $GITHUB_STEP_SUMMARY
Expand Down Expand Up @@ -260,9 +261,10 @@ jobs:
# --- Base Branch Coverage ---
- name: Fetch and check out base branch
if: github.event_name == 'pull_request'
# Check out by SHA: the PR branch does not exist in this repo for
# fork PRs, and a tag named like the base branch would shadow it.
run: |
git fetch origin ${{ github.base_ref }}
git checkout ${{ github.base_ref }}
git checkout --detach ${{ github.event.pull_request.base.sha }}

- name: Build + Test coverage on base
if: github.event_name == 'pull_request'
Expand Down Expand Up @@ -294,7 +296,7 @@ jobs:
- name: Check out head branch (PR)
if: github.event_name == 'pull_request'
run: |
git checkout ${{ github.head_ref }}
git checkout --detach ${{ github.sha }}

- name: Build + Test coverage on PR
run: |
Expand Down
73 changes: 71 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ use std::io::{self, BufRead, BufReader, IsTerminal};
use std::{fs, path::Path, process::Command, str::FromStr, time::UNIX_EPOCH};

use crate::{
defaults::{BINARY_FILE_EXTENSIONS, DEFAULT_IGNORE_PATTERNS, DEFAULT_OUTPUT_TEMPLATE},
defaults::{
BINARY_FILE_EXTENSIONS, DEFAULT_IGNORE_PATTERNS, DEFAULT_MAX_GIT_DEPTH,
DEFAULT_OUTPUT_TEMPLATE,
},
priority::PriorityRule,
};

Expand Down Expand Up @@ -143,7 +146,7 @@ impl Default for YekConfig {
stream: false,
token_mode: false,
output_file_full_path: None,
max_git_depth: 100,
max_git_depth: DEFAULT_MAX_GIT_DEPTH,
}
}
}
Expand Down Expand Up @@ -207,6 +210,7 @@ impl YekConfig {
let (mut cfg, config_path, _config_format) = YekConfig::parse_info();

cfg.apply_config_bool_overrides(config_path.as_deref());
cfg.apply_config_scalar_defaults(config_path.as_deref());

// Handle version flag
if cfg.version {
Expand Down Expand Up @@ -326,6 +330,31 @@ impl YekConfig {
self.tree_only |= config_bool(&settings, "tree_only", "tree-only");
}

/// clap-config-file ignores `default_value` on config-only scalar fields and
/// falls back to `Default::default()` (0). For `max_git_depth` that means
/// reading zero commits, which silently disables the Git recency boost.
/// Restore the documented default unless the config file sets a value.
fn apply_config_scalar_defaults(&mut self, config_path: Option<&Path>) {
let configured_depth = config_path
.and_then(|path| {
::config::Config::builder()
.add_source(::config::File::from(path).required(false))
.build()
.ok()
})
.and_then(|settings| {
settings
.get_int("max_git_depth")
.or_else(|_| settings.get_int("max-git-depth"))
.ok()
});

self.max_git_depth = match configured_depth {
Some(depth) => i32::try_from(depth).unwrap_or(i32::MAX),
None => DEFAULT_MAX_GIT_DEPTH,
};
}

/// Compute a quick checksum for the input paths (files and directories).
/// For directories, it uses the top-level listing. For files, it uses the file metadata.
pub fn get_checksum(input_paths: &[String]) -> String {
Expand Down Expand Up @@ -739,3 +768,43 @@ mod bool_config_tests {
assert!(!cfg.json && !cfg.debug && !cfg.line_numbers && !cfg.tree_header && !cfg.tree_only);
}
}

#[cfg(test)]
mod scalar_default_tests {
use super::*;

fn depth_after_defaults(config_path: Option<&Path>) -> i32 {
let mut cfg = YekConfig {
max_git_depth: 0, // what clap-config-file yields when the key is absent
..YekConfig::default()
};
cfg.apply_config_scalar_defaults(config_path);
cfg.max_git_depth
}

#[test]
fn max_git_depth_defaults_to_100_without_a_config_file() {
assert_eq!(depth_after_defaults(None), DEFAULT_MAX_GIT_DEPTH);
}

#[test]
fn max_git_depth_defaults_to_100_when_config_omits_it() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("yek.yaml");
fs::write(&path, "json: false\n").unwrap();

assert_eq!(depth_after_defaults(Some(&path)), DEFAULT_MAX_GIT_DEPTH);
}

#[test]
fn max_git_depth_from_config_is_respected_in_either_key_style() {
let dir = tempfile::tempdir().unwrap();
let snake = dir.path().join("snake.yaml");
let kebab = dir.path().join("kebab.toml");
fs::write(&snake, "max_git_depth: 0\n").unwrap();
fs::write(&kebab, "max-git-depth = 7\n").unwrap();

assert_eq!(depth_after_defaults(Some(&snake)), 0);
assert_eq!(depth_after_defaults(Some(&kebab)), 7);
}
}
3 changes: 3 additions & 0 deletions src/defaults.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,6 @@ pub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[
];

pub const DEFAULT_OUTPUT_TEMPLATE: &str = ">>>> FILE_PATH\nFILE_CONTENT";

/// Number of most recent commits scanned for the Git recency boost.
pub const DEFAULT_MAX_GIT_DEPTH: i32 = 100;
51 changes: 33 additions & 18 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,37 @@ pub fn is_text_file(path: &Path, user_binary_extensions: &[String]) -> io::Resul
Ok(inspect(&buf) != ContentType::BINARY)
}

/// Gather last-commit times for every input directory that lives in a Git repo.
///
/// Git reports paths relative to the repository root, while files are later
/// processed relative to each input path. Keying by canonical absolute path
/// lets the two meet regardless of which subdirectory the user passed in.
fn collect_commit_times(config: &YekConfig) -> HashMap<String, u64> {
let max_commits = config.max_git_depth.try_into().unwrap_or(0);
config
.input_paths
.par_iter()
.filter_map(|path_str| {
let input_dir = Path::new(path_str);
if !input_dir.is_dir() {
return None;
}
// An absolute path lets repo discovery walk up from a subdirectory.
let input_dir = input_dir.canonicalize().ok()?;
let (repo_root, times) =
priority::get_recent_commit_times_with_root(&input_dir, max_commits)?;
let repo_root = repo_root.canonicalize().unwrap_or(repo_root);
Some(
times
.into_iter()
.map(|(rel, time)| (repo_root.join(rel).to_string_lossy().into_owned(), time))
.collect::<Vec<_>>(),
)
})
.flatten()
.collect()
}

/// Main entrypoint for serialization, used by CLI and tests
pub fn serialize_repo(config: &YekConfig) -> Result<(String, Vec<ProcessedFile>)> {
// Validate input paths and warn about non-existent ones
Expand All @@ -79,25 +110,9 @@ pub fn serialize_repo(config: &YekConfig) -> Result<(String, Vec<ProcessedFile>)
}
}

// Gather commit times from each input path that is a directory
let combined_commit_times = config
.input_paths
.par_iter()
.filter_map(|path_str| {
let repo_path = Path::new(path_str);
if repo_path.is_dir() {
priority::get_recent_commit_times_git2(
repo_path,
config.max_git_depth.try_into().unwrap_or(0),
)
} else {
None
}
})
.flatten()
.collect::<HashMap<String, u64>>();
let combined_commit_times = collect_commit_times(config);

// Compute a recentness-based boost
// Compute a recentness-based boost, keyed by canonical absolute file path
let recentness_boost =
compute_recentness_boost(&combined_commit_times, config.git_boost_max.unwrap_or(100));

Expand Down
74 changes: 53 additions & 21 deletions src/parallel.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::{
models::{InputConfig, OutputConfig, ProcessedFile, ProcessingConfig},
pipeline::ProcessingContext,
priority::{get_compiled_file_priority_with_category, CompiledPriorityRules},
};
use anyhow::{anyhow, Result};
use content_inspector::{inspect, ContentType};
Expand All @@ -9,7 +10,7 @@ use path_slash::PathBufExt;
use rayon::prelude::*;
use std::{
collections::HashMap,
path::Path,
path::{Path, PathBuf},
sync::{Arc, Mutex},
time::Instant,
};
Expand All @@ -19,13 +20,32 @@ use tracing::debug;
pub struct ParallelFileProcessor {
context: Arc<ProcessingContext>,
file_counter: Arc<Mutex<HashMap<i32, usize>>>,
/// Git recency boost keyed by canonical absolute file path.
recentness_boost: HashMap<PathBuf, i32>,
/// Priority rules compiled once instead of once per file.
priority_rules: CompiledPriorityRules,
}

impl ParallelFileProcessor {
pub fn new(context: ProcessingContext) -> Self {
let priority_rules = CompiledPriorityRules::new(&context.processing_config.priority_rules);
Self {
priority_rules,
context: Arc::new(context),
file_counter: Arc::new(Mutex::new(HashMap::new())),
recentness_boost: HashMap::new(),
}
}

/// Apply a Git recency boost, keyed by canonical absolute file path.
pub fn with_recentness_boost(self, boost_map: &HashMap<String, i32>) -> Self {
let recentness_boost = boost_map
.iter()
.map(|(path, boost)| (PathBuf::from(path), *boost))
.collect();
Self {
recentness_boost,
..self
}
}

Expand Down Expand Up @@ -195,7 +215,8 @@ impl ParallelFileProcessor {
debug!("Skipping binary file: {rel_path}");
Ok(Vec::new())
} else {
let processed_file = self.create_processed_file(&rel_path, &content)?;
let processed_file =
self.create_processed_file(file_path, &rel_path, &content)?;
Ok(vec![processed_file])
}
}
Expand Down Expand Up @@ -291,7 +312,7 @@ impl ParallelFileProcessor {
}

// Calculate priority with category
let (priority, category) = self.calculate_priority_with_category(rel_path);
let (priority, category) = self.calculate_priority_with_category(file_path, rel_path);

// Get thread-safe file index
let file_index = self.get_next_file_index(priority);
Expand Down Expand Up @@ -335,30 +356,33 @@ impl ParallelFileProcessor {
/// Calculate priority for a file including category-based offset
fn calculate_priority_with_category(
&self,
file_path: &Path,
rel_path: &str,
) -> (i32, crate::category::FileCategory) {
use crate::priority::get_file_priority_with_category;

// Get base priority from rules and category
let (mut priority, category) = get_file_priority_with_category(
let (mut priority, category) = get_compiled_file_priority_with_category(
rel_path,
&self.context.processing_config.priority_rules,
&self.priority_rules,
&self.context.processing_config.category_weights,
);

// Apply git boost if available
if let Some(commit_time) = self.context.repository_info.commit_times.get(rel_path) {
let max_boost = self.context.input_config.git_boost_max.unwrap_or(100);
priority += self.calculate_git_boost(
*commit_time,
&self.context.repository_info.commit_times,
max_boost,
);
}
priority += self.recentness_boost_for(file_path);

(priority, category)
}

/// Look up the Git recency boost for a file, or 0 when it has none.
fn recentness_boost_for(&self, file_path: &Path) -> i32 {
if self.recentness_boost.is_empty() {
return 0;
}
file_path
.canonicalize()
.ok()
.and_then(|path| self.recentness_boost.get(&path).copied())
.unwrap_or(0)
}

/// Calculate git boost for a file
fn calculate_git_boost(
&self,
Expand Down Expand Up @@ -431,8 +455,13 @@ impl ParallelFileProcessor {
}

/// Create a processed file with proper metadata
fn create_processed_file(&self, rel_path: &str, content: &[u8]) -> Result<ProcessedFile> {
let (priority, category) = self.calculate_priority_with_category(rel_path);
fn create_processed_file(
&self,
file_path: &Path,
rel_path: &str,
content: &[u8],
) -> Result<ProcessedFile> {
let (priority, category) = self.calculate_priority_with_category(file_path, rel_path);
let file_index = self.get_next_file_index(priority);

Ok(ProcessedFile::new_with_category(
Expand Down Expand Up @@ -465,11 +494,13 @@ pub fn normalize_path(path: &Path, base: &Path) -> String {
.to_string()
}

/// Legacy function for backward compatibility - delegates to new implementation
/// Legacy function for backward compatibility - delegates to new implementation.
///
/// `boost_map` holds the Git recency boost keyed by canonical absolute file path.
pub fn process_files_parallel(
base_path: &Path,
config: &crate::config::YekConfig,
_boost_map: &HashMap<String, i32>,
boost_map: &HashMap<String, i32>,
) -> Result<Vec<ProcessedFile>> {
// This is a temporary bridge - in the final implementation,
// this would be replaced with the new pipeline-based approach
Expand Down Expand Up @@ -497,7 +528,8 @@ pub fn process_files_parallel(
},
crate::models::RepositoryInfo::new(base_path.to_path_buf(), false), // TODO: Proper repo info
Arc::new(crate::repository::RealFileSystem),
));
))
.with_recentness_boost(boost_map);

processor.process_files_parallel(base_path)
}
Loading
Loading