m2geval / rust /yek_function_bench.jsonl
Tswatery's picture
Add files using upload-large-folder tool
f18999e verified
{"repo_name": "yek", "file_name": "/yek/src/config.rs", "inference_info": {"prefix_code": "use anyhow::{anyhow, Result};\nuse bytesize::ByteSize;\nuse clap_config_file::ClapConfigFile;\nuse sha2::{Digest, Sha256};\nuse std::io::IsTerminal;\nuse std::{fs, path::Path, str::FromStr, time::UNIX_EPOCH};\n\nuse crate::{\n defaults::{BINARY_FILE_EXTENSIONS, DEFAULT_IGNORE_PATTERNS, DEFAULT_OUTPUT_TEMPLATE},\n priority::PriorityRule,\n};\n\n#[derive(Clone, Debug, Default, clap::ValueEnum, serde::Serialize, serde::Deserialize)]\npub enum ConfigFormat {\n #[default]\n Toml,\n Yaml,\n Json,\n}\n\n#[derive(ClapConfigFile, Clone)]\n#[config_file_name = \"yek\"]\n#[config_file_formats = \"toml,yaml,json\"]\npub struct YekConfig {\n /// Input files and/or directories to process\n #[config_arg(positional)]\n pub input_paths: Vec<String>,\n\n /// Print version of yek\n #[config_arg(long = \"version\", short = 'V')]\n pub version: bool,\n\n /// Max size per chunk. e.g. \"10MB\" or \"128K\" or when using token counting mode, \"100\" or \"128K\"\n #[config_arg(default_value = \"10MB\")]\n pub max_size: String,\n\n /// Use token mode instead of byte mode\n #[config_arg()]\n pub tokens: String,\n\n /// Enable JSON output\n #[config_arg()]\n pub json: bool,\n\n /// Enable debug output\n #[config_arg()]\n pub debug: bool,\n\n /// Output directory. If none is provided & stdout is a TTY, we pick a temp dir\n #[config_arg()]\n pub output_dir: Option<String>,\n\n /// Output template. Defaults to \">>>> FILE_PATH\\nFILE_CONTENT\"\n #[config_arg(default_value = \">>>> FILE_PATH\\nFILE_CONTENT\")]\n pub output_template: String,\n\n /// Ignore patterns\n #[config_arg(long = \"ignore-patterns\", multi_value_behavior = \"extend\")]\n pub ignore_patterns: Vec<String>,\n\n /// Unignore patterns. Yek has some built-in ignore patterns, but you can override them here.\n #[config_arg(long = \"unignore-patterns\", multi_value_behavior = \"extend\")]\n pub unignore_patterns: Vec<String>,\n\n /// Priority rules\n #[config_arg(accept_from = \"config_only\")]\n pub priority_rules: Vec<PriorityRule>,\n\n /// Binary file extensions to ignore\n #[config_arg(accept_from = \"config_only\", default_value = BINARY_FILE_EXTENSIONS)]\n pub binary_extensions: Vec<String>,\n\n /// Maximum additional boost from Git commit times (0..1000)\n #[config_arg(accept_from = \"config_only\")]\n pub git_boost_max: Option<i32>,\n\n /// True if we should stream output to stdout (computed)\n pub stream: bool,\n\n /// True if we should count tokens, not bytes (computed)\n pub token_mode: bool,\n\n /// Final resolved output file path (only used if not streaming)\n pub output_file_full_path: Option<String>,\n\n /// Maximum depth to search for Git commit times\n #[config_arg(accept_from = \"config_only\", default_value = \"100\")]\n pub max_git_depth: i32,\n}\n\n/// Provide defaults so tests or other callers can create a baseline YekConfig easily.\nimpl Default for YekConfig {\n fn default() -> Self {\n Self {\n input_paths: Vec::new(),\n version: false,\n max_size: \"10MB\".to_string(),\n tokens: String::new(),\n json: false,\n debug: false,\n output_dir: None,\n output_template: DEFAULT_OUTPUT_TEMPLATE.to_string(),\n ignore_patterns: Vec::new(),\n unignore_patterns: Vec::new(),\n priority_rules: Vec::new(),\n binary_extensions: BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect(),\n git_boost_max: Some(100),\n\n // computed fields\n stream: false,\n token_mode: false,\n output_file_full_path: None,\n max_git_depth: 100,\n }\n }\n}\n\nimpl YekConfig {\n pub fn extend_config_with_defaults(input_paths: Vec<String>, output_dir: String) -> Self {\n YekConfig {\n input_paths,\n output_dir: Some(output_dir),\n ..Default::default()\n }\n }\n}\n\nimpl YekConfig {\n /// Ensure output directory exists and is valid. Returns the resolved output directory path.\n pub fn ensure_output_dir(&self) -> Result<String> {\n if self.stream {\n return Ok(String::new());\n }\n\n let output_dir = if let Some(dir) = &self.output_dir {\n dir.clone()\n } else {\n let temp_dir = std::env::temp_dir().join(\"yek-output\");\n temp_dir.to_string_lossy().to_string()\n };\n\n let path = Path::new(&output_dir);\n if path.exists() && !path.is_dir() {\n return Err(anyhow!(\n \"output_dir: '{}' exists but is not a directory\",\n output_dir\n ));\n }\n\n std::fs::create_dir_all(path)\n .map_err(|e| anyhow!(\"output_dir: cannot create '{}': {}\", output_dir, e))?;\n\n Ok(output_dir)\n }\n\n /// Parse from CLI + config file, fill in computed fields, and validate.\n pub fn init_config() -> Self {\n // 1) parse from CLI and optional config file:\n let mut cfg = YekConfig::parse();\n\n // Handle version flag\n if cfg.version {\n println!(\"{}\", env!(\"CARGO_PKG_VERSION\"));\n std::process::exit(0);\n }\n\n // 2) compute derived fields:\n cfg.token_mode = !cfg.tokens.is_empty();\n let force_tty = std::env::var(\"FORCE_TTY\").is_ok();\n\n cfg.stream = !std::io::stdout().is_terminal() && !force_tty;\n\n // default input dirs to current dir if none:\n if cfg.input_paths.is_empty() {\n cfg.input_paths.push(\".\".to_string());\n }\n\n // Extend binary extensions with the built-in list:\n let mut merged_bins = BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n merged_bins.append(&mut cfg.binary_extensions);\n cfg.binary_extensions = merged_bins\n .into_iter()\n .collect::<std::collections::HashSet<_>>()\n .into_iter()\n .collect();\n\n // Always start with default ignore patterns, then add user's:\n let mut ignore = DEFAULT_IGNORE_PATTERNS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n ignore.extend(cfg.ignore_patterns);\n cfg.ignore_patterns = ignore;\n\n // Apply unignore patterns (turn them into negative globs \"!…\")\n cfg.ignore_patterns\n .extend(cfg.unignore_patterns.iter().map(|pat| format!(\"!{}\", pat)));\n\n // Handle output directory setup\n if !cfg.stream {\n match cfg.ensure_output_dir() {\n Ok(dir) => cfg.output_dir = Some(dir),\n Err(e) => {\n eprintln!(\"Warning: Failed to create output directory: {}\", e);\n cfg.stream = true; // Fall back to streaming mode\n }\n }\n }\n\n // By default, we start with no final output_file_full_path:\n cfg.output_file_full_path = None;\n\n // 3) Validate\n if let Err(e) = cfg.validate() {\n eprintln!(\"Error: {}\", e);\n std::process::exit(1);\n }\n\n cfg\n }\n\n /// Compute a quick checksum for the input paths (files and directories).\n /// For directories, it uses the top-level listing. For files, it uses the file metadata.\n pub fn get_checksum(input_paths: &[String]) -> String {\n let mut hasher = Sha256::new();\n for path_str in input_paths {\n let base_path = Path::new(path_str);\n if !base_path.exists() {\n continue;\n }\n\n // If it's a file, hash the file metadata directly\n if base_path.is_file() {\n if let Ok(meta) = fs::metadata(base_path) {\n hasher.update(path_str.as_bytes());\n hasher.update(meta.len().to_le_bytes());\n\n if let Ok(mod_time) = meta.modified() {\n if let Ok(dur) = mod_time.duration_since(UNIX_EPOCH) {\n hasher.update(dur.as_secs().to_le_bytes());\n hasher.update(dur.subsec_nanos().to_le_bytes());\n }\n }\n }\n continue;\n }\n\n // If it's a directory, hash its contents\n let entries = match fs::read_dir(base_path) {\n Ok(iter) => iter.filter_map(|e| e.ok()).collect::<Vec<_>>(),\n Err(_) => continue,\n };\n\n // Sort deterministically by path name\n let mut sorted = entries;\n sorted.sort_by_key(|a| a.path());\n\n for entry in sorted {\n let p = entry.path();\n if let Ok(meta) = fs::metadata(&p) {\n let path_str = p.to_string_lossy();\n hasher.update(path_str.as_bytes());\n hasher.update(meta.len().to_le_bytes());\n\n if let Ok(mod_time) = meta.modified() {\n if let Ok(dur) = mod_time.duration_since(UNIX_EPOCH) {\n hasher.update(dur.as_secs().to_le_bytes());\n hasher.update(dur.subsec_nanos().to_le_bytes());\n }\n }\n }\n }\n }\n let result = hasher.finalize();\n // Convert the 32-byte result to hex, but only keep the first 8 characters\n let hex = format!(\"{:x}\", result);\n hex[..8].to_owned()\n }\n\n /// Validate the final config.\n ", "suffix_code": "\n}\n", "middle_code": "pub fn validate(&self) -> Result<()> {\n if !self.output_template.contains(\"FILE_PATH\")\n || !self.output_template.contains(\"FILE_CONTENT\")\n {\n return Err(anyhow!(\n \"output_template: must contain FILE_PATH and FILE_CONTENT\"\n ));\n }\n if self.max_size == \"0\" {\n return Err(anyhow!(\"max_size: cannot be 0\"));\n }\n if !self.token_mode {\n ByteSize::from_str(&self.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?;\n } else if self.tokens.to_lowercase().ends_with('k') {\n let val = self.tokens[..self.tokens.len() - 1]\n .trim()\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n } else if !self.tokens.is_empty() {\n let val = self\n .tokens\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n }\n if !self.stream {\n self.ensure_output_dir()?;\n }\n for pattern in &self.ignore_patterns {\n glob::Pattern::new(pattern)\n .map_err(|e| anyhow!(\"ignore_patterns: Invalid pattern '{}': {}\", pattern, e))?;\n }\n for rule in &self.priority_rules {\n if rule.score < 0 || rule.score > 1000 {\n return Err(anyhow!(\n \"priority_rules: Priority score {} must be between 0 and 1000\",\n rule.score\n ));\n }\n glob::Pattern::new(&rule.pattern).map_err(|e| {\n anyhow!(\"priority_rules: Invalid pattern '{}': {}\", rule.pattern, e)\n })?;\n }\n Ok(())\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/yek/src/lib.rs", "use anyhow::anyhow;\nuse anyhow::Result;\nuse bytesize::ByteSize;\nuse content_inspector::{inspect, ContentType};\nuse rayon::prelude::*;\nuse std::{\n collections::HashMap,\n fs::File,\n io::{self, Read},\n path::Path,\n str::FromStr,\n sync::OnceLock,\n};\nuse tiktoken_rs::CoreBPE;\n\npub mod config;\npub mod defaults;\npub mod parallel;\npub mod priority;\n\nuse config::YekConfig;\nuse parallel::{process_files_parallel, ProcessedFile};\nuse priority::compute_recentness_boost;\n\n// Add a static BPE encoder for reuse\nstatic TOKENIZER: OnceLock<CoreBPE> = OnceLock::new();\n\nfn get_tokenizer() -> &'static CoreBPE {\n TOKENIZER.get_or_init(|| {\n tiktoken_rs::get_bpe_from_model(\"gpt-3.5-turbo\").expect(\"Failed to load tokenizer\")\n })\n}\n\n/// Check if a file is likely text or binary by reading only a small chunk.\n/// This avoids reading large files fully just to detect their type.\npub fn is_text_file(path: &Path, user_binary_extensions: &[String]) -> io::Result<bool> {\n // If extension is known to be binary, skip quickly\n if let Some(ext) = path.extension().and_then(|e| e.to_str()) {\n if user_binary_extensions.iter().any(|bin_ext| bin_ext == ext) {\n return Ok(false);\n }\n }\n\n // Short partial read to check if it's binary or text\n const INSPECTION_BYTES: usize = 8192;\n let mut file = File::open(path)?;\n let mut buf = vec![0u8; INSPECTION_BYTES];\n let n = file.read(&mut buf)?;\n buf.truncate(n);\n\n Ok(inspect(&buf) != ContentType::BINARY)\n}\n\n/// Main entrypoint for serialization, used by CLI and tests\npub fn serialize_repo(config: &YekConfig) -> Result<(String, Vec<ProcessedFile>)> {\n // Gather commit times from each input path that is a directory\n let combined_commit_times = config\n .input_paths\n .par_iter()\n .filter_map(|path_str| {\n let repo_path = Path::new(path_str);\n if repo_path.is_dir() {\n priority::get_recent_commit_times_git2(\n repo_path,\n config.max_git_depth.try_into().unwrap_or(0),\n )\n } else {\n None\n }\n })\n .flatten()\n .collect::<HashMap<String, u64>>();\n\n // Compute a recentness-based boost\n let recentness_boost =\n compute_recentness_boost(&combined_commit_times, config.git_boost_max.unwrap_or(100));\n\n // Process files in parallel for each input path\n let merged_files = config\n .input_paths\n .par_iter()\n .map(|path_str| {\n let path = Path::new(path_str);\n process_files_parallel(path, config, &recentness_boost)\n })\n .collect::<Result<Vec<Vec<ProcessedFile>>>>()?\n .into_iter()\n .flatten()\n .collect::<Vec<ProcessedFile>>();\n\n let mut files = merged_files;\n\n // Sort final (priority asc, then file_index asc)\n files.par_sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .then_with(|| a.rel_path.cmp(&b.rel_path))\n });\n\n // Build the final output string\n let output_string = concat_files(&files, config)?;\n\n // Only count tokens if debug logging is enabled\n if tracing::Level::DEBUG <= tracing::level_filters::STATIC_MAX_LEVEL {\n tracing::debug!(\"{} tokens generated\", count_tokens(&output_string));\n }\n\n Ok((output_string, files))\n}\n\npub fn concat_files(files: &[ProcessedFile], config: &YekConfig) -> anyhow::Result<String> {\n let mut accumulated = 0_usize;\n let cap = if config.token_mode {\n parse_token_limit(&config.tokens)?\n } else {\n ByteSize::from_str(&config.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?\n .as_u64() as usize\n };\n\n // Sort by priority (asc) and file_index (asc)\n let mut sorted_files: Vec<_> = files.iter().collect();\n sorted_files.sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .then_with(|| a.rel_path.cmp(&b.rel_path))\n });\n\n let mut files_to_include = Vec::new();\n for file in sorted_files {\n let content_size = if config.token_mode {\n // Format the file content with template first, then count tokens\n let formatted = if config.json {\n serde_json::to_string(&serde_json::json!({\n \"filename\": &file.rel_path,\n \"content\": &file.content,\n }))\n .map_err(|e| anyhow!(\"Failed to serialize JSON: {}\", e))?\n } else {\n config\n .output_template\n .replace(\"FILE_PATH\", &file.rel_path)\n .replace(\"FILE_CONTENT\", &file.content)\n };\n count_tokens(&formatted)\n } else {\n file.content.len()\n };\n\n if accumulated + content_size <= cap {\n accumulated += content_size;\n files_to_include.push(file);\n } else {\n break;\n }\n }\n\n if config.json {\n // JSON array of objects\n Ok(serde_json::to_string_pretty(\n &files_to_include\n .iter()\n .map(|f| {\n serde_json::json!({\n \"filename\": &f.rel_path,\n \"content\": &f.content,\n })\n })\n .collect::<Vec<_>>(),\n )?)\n } else {\n // Use the user-defined template\n Ok(files_to_include\n .iter()\n .map(|f| {\n config\n .output_template\n .replace(\"FILE_PATH\", &f.rel_path)\n .replace(\"FILE_CONTENT\", &f.content)\n // Handle both literal \"\\n\" and escaped \"\\\\n\"\n .replace(\"\\\\\\\\\\n\", \"\\n\") // First handle escaped newline\n .replace(\"\\\\\\\\n\", \"\\n\") // Then handle escaped \\n sequence\n })\n .collect::<Vec<_>>()\n .join(\"\\n\"))\n }\n}\n\n/// Parse a token limit string like \"800k\" or \"1000\" into a number\npub fn parse_token_limit(limit: &str) -> anyhow::Result<usize> {\n if limit.to_lowercase().ends_with('k') {\n limit[..limit.len() - 1]\n .trim()\n .parse::<usize>()\n .map(|n| n * 1000)\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n } else {\n limit\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n }\n}\n\n/// Count tokens using tiktoken's GPT-3.5-Turbo tokenizer for accuracy\npub fn count_tokens(text: &str) -> usize {\n get_tokenizer().encode_with_special_tokens(text).len()\n}\n"], ["/yek/src/parallel.rs", "use crate::{config::YekConfig, priority::get_file_priority, Result};\nuse content_inspector::{inspect, ContentType};\nuse glob::glob;\nuse ignore::gitignore::GitignoreBuilder;\nuse path_slash::PathBufExt;\nuse rayon::prelude::*;\nuse std::{\n collections::HashMap,\n fs,\n path::Path,\n sync::{mpsc, Arc},\n};\nuse tracing::debug;\n\n#[derive(Debug, Clone)]\npub struct ProcessedFile {\n pub priority: i32,\n pub file_index: usize,\n pub rel_path: String,\n pub content: String,\n}\n\n/// Process a single file, checking ignore patterns and reading its contents.\nfn process_single_file(\n file_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n let base_dir = file_path.parent().unwrap_or(Path::new(\"\"));\n let rel_path = normalize_path(file_path, base_dir);\n\n // Build the gitignore\n let mut gitignore_builder = GitignoreBuilder::new(base_dir);\n for pattern in &config.ignore_patterns {\n gitignore_builder.add_line(None, pattern)?;\n }\n\n // If there is a .gitignore in this folder, add it last so its \"!\" lines override prior patterns\n let gitignore_file = base_dir.join(\".gitignore\");\n if gitignore_file.exists() {\n gitignore_builder.add(&gitignore_file);\n }\n\n let gitignore = gitignore_builder.build()?;\n if gitignore.matched(file_path, false).is_ignore() {\n debug!(\"Skipping ignored file: {rel_path}\");\n return Ok(Vec::new());\n }\n\n let mut processed_files = Vec::new();\n\n match fs::read(file_path) {\n Ok(content) => {\n if inspect(&content) == ContentType::BINARY {\n debug!(\"Skipping binary file: {rel_path}\");\n } else {\n let rule_priority = get_file_priority(&rel_path, &config.priority_rules);\n let boost = boost_map.get(&rel_path).copied().unwrap_or(0);\n let combined_priority = rule_priority + boost;\n\n processed_files.push(ProcessedFile {\n priority: combined_priority,\n file_index: 0, // For a single file, the index is always 0\n rel_path,\n content: String::from_utf8_lossy(&content).to_string(),\n });\n }\n }\n Err(e) => {\n debug!(\"Failed to read {rel_path}: {e}\");\n }\n }\n\n Ok(processed_files)\n}\n\n/// Walk files in parallel (if a directory is given), skipping ignored paths,\n/// then read each file's contents in a separate thread.\n/// Return the resulting `ProcessedFile` objects.\npub fn process_files_parallel(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n // Expand globs into a list of paths\n let mut expanded_paths = Vec::new();\n let path_str = base_path.to_string_lossy();\n for entry in glob(&path_str)? {\n match entry {\n Ok(path) => expanded_paths.push(path),\n Err(e) => debug!(\"Glob entry error: {:?}\", e),\n }\n }\n\n // If it's a single file (no glob expansion or single file result), process it directly\n if expanded_paths.len() == 1 && expanded_paths[0].is_file() {\n return process_single_file(&expanded_paths[0], config, boost_map);\n }\n\n // Iterate over expanded paths, handling files and directories\n let mut all_processed_files = Vec::new();\n for path in expanded_paths {\n if path.is_file() {\n all_processed_files.extend(process_single_file(&path, config, boost_map)?);\n } else if path.is_dir() {\n // For directories, use the original recursive logic\n all_processed_files.extend(process_files_parallel_internal(&path, config, boost_map)?);\n }\n }\n\n Ok(all_processed_files)\n}\n\n/// Internal function to handle directory recursion (separated for clarity)\nfn process_files_parallel_internal(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n // It's a directory, so walk it\n let mut walk_builder = ignore::WalkBuilder::new(base_path);\n\n // Standard filters + no follow symlinks\n walk_builder\n .follow_links(false)\n .standard_filters(true)\n .require_git(false);\n\n // Build the gitignore\n let mut gitignore_builder = GitignoreBuilder::new(base_path);\n // Add our custom patterns first\n for pattern in &config.ignore_patterns {\n gitignore_builder.add_line(None, pattern)?;\n }\n\n // If there is a .gitignore in this folder, add it last so its \"!\" lines override prior patterns\n let gitignore_file = base_path.join(\".gitignore\");\n if gitignore_file.exists() {\n gitignore_builder.add(&gitignore_file);\n }\n\n let gitignore = Arc::new(gitignore_builder.build()?); // Propagate error here\n\n // This channel will carry (path, rel_path) to the processing thread\n let (processed_files_tx, processed_files_rx) = mpsc::channel::<(std::path::PathBuf, String)>();\n\n // Processing happens on a dedicated thread, to keep from blocking the main walker\n let process_thread = std::thread::spawn({\n let priority_rules = config.priority_rules.clone();\n let boost_map = boost_map.clone();\n move || {\n let mut processed = Vec::new();\n for (path, rel_path) in processed_files_rx {\n // Read entire file\n match fs::read(&path) {\n Ok(content) => {\n // Check if it's binary quickly\n if inspect(&content) == ContentType::BINARY {\n debug!(\"Skipping binary file: {rel_path}\");\n continue;\n }\n // Compute priority\n let rule_priority = get_file_priority(&rel_path, &priority_rules);\n let boost = boost_map.get(&rel_path).copied().unwrap_or(0);\n let combined = rule_priority + boost;\n processed.push(ProcessedFile {\n priority: combined,\n file_index: 0, // assigned later\n rel_path,\n content: String::from_utf8_lossy(&content).to_string(),\n });\n }\n Err(e) => {\n debug!(\"Failed to read {rel_path}: {e}\");\n }\n }\n }\n processed\n }\n });\n\n // Use ignore's parallel walker to skip ignored files\n let base_cloned = base_path.to_owned();\n let walker_tx = processed_files_tx.clone();\n\n // Now build the walker (no .gitignore custom filename)\n walk_builder.build_parallel().run(move || {\n let base_dir = base_cloned.clone();\n let processed_files_tx = walker_tx.clone();\n let gitignore = Arc::clone(&gitignore);\n\n Box::new(move |entry| {\n let entry = match entry {\n Ok(e) => e,\n Err(_) => return ignore::WalkState::Continue,\n };\n // Only process files\n if !entry.file_type().is_some_and(|ft| ft.is_file()) {\n return ignore::WalkState::Continue;\n }\n\n let path = entry.path().to_path_buf();\n let rel_path = normalize_path(&path, &base_dir);\n\n // If gitignore says skip, we do not even read\n if gitignore.matched(&path, false).is_ignore() {\n debug!(\"Skipping ignored file: {rel_path}\");\n return ignore::WalkState::Continue;\n }\n\n // Otherwise we send to processing thread\n processed_files_tx.send((path, rel_path)).ok();\n ignore::WalkState::Continue\n })\n });\n\n // Drop the sender so the thread can end\n drop(processed_files_tx);\n\n // Join the processing thread\n let mut processed_files = process_thread.join().unwrap();\n\n // Now assign file_index within each priority group\n let mut counters = HashMap::new();\n for f in &mut processed_files {\n let ctr = counters.entry(f.priority).or_insert(0);\n f.file_index = *ctr;\n *ctr += 1;\n }\n\n if config.debug {\n debug!(\n \"Processed {} files in parallel for base_path: {}\",\n processed_files.len(),\n base_path.display()\n );\n }\n\n // Sort by priority desc, then file_index\n processed_files.par_sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .reverse()\n .then_with(|| a.file_index.cmp(&b.file_index))\n });\n\n Ok(processed_files)\n}\n\n/// Create a relative, slash-normalized path\npub fn normalize_path(path: &Path, base: &Path) -> String {\n path.strip_prefix(base)\n .unwrap_or(path)\n .to_path_buf()\n .to_slash()\n .unwrap_or_default()\n .to_string()\n}\n"], ["/yek/src/priority.rs", "use git2;\nuse regex;\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, path::Path};\nuse tracing::debug;\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\npub struct PriorityRule {\n pub pattern: String,\n pub score: i32,\n}\n\n/// Determine final priority of a file by scanning the priority list\n/// in descending order of score.\npub fn get_file_priority(path: &str, rules: &[PriorityRule]) -> i32 {\n let mut priority = 0;\n for rule in rules {\n if let Ok(re) = regex::Regex::new(&rule.pattern) {\n if re.is_match(path) {\n priority += rule.score;\n }\n }\n }\n priority\n}\n\n/// Rank-based approach to compute how \"recent\" each file is (0=oldest, 1=newest).\n/// Then scale it to a user-defined or default max boost.\npub fn compute_recentness_boost(\n commit_times: &HashMap<String, u64>,\n max_boost: i32,\n) -> HashMap<String, i32> {\n if commit_times.is_empty() {\n return HashMap::new();\n }\n\n // Sort by ascending commit time => first is oldest\n let mut sorted: Vec<(&String, &u64)> = commit_times.iter().collect();\n sorted.sort_by_key(|(_, t)| **t);\n\n // If there's only one file, or zero, no boosts make sense\n if sorted.len() <= 1 {\n let mut single = HashMap::new();\n for file in commit_times.keys() {\n single.insert(file.clone(), 0);\n }\n return single;\n }\n\n let mut result = HashMap::new();\n let oldest_time = *sorted.first().unwrap().1;\n let newest_time = *sorted.last().unwrap().1;\n let time_range = newest_time.saturating_sub(oldest_time) as f64;\n\n // If all files have the same timestamp, they should all get the same boost\n if time_range == 0.0 {\n for (path, _) in sorted {\n result.insert(path.clone(), 0);\n }\n return result;\n }\n\n // Calculate boost based on time difference from oldest file\n for (path, time) in sorted {\n let time_diff = (*time - oldest_time) as f64;\n let rank = time_diff / time_range; // 0.0..1.0 (older files get lower rank)\n let boost = (rank * max_boost as f64).round() as i32; // Newer files get higher boost\n result.insert(path.clone(), boost);\n }\n result\n}\n\n/// Get the commit time of the most recent change to each file using git2.\n/// Returns a map from file path (relative to the repo root) → last commit Unix time.\n/// If Git or .git folder is missing, returns None instead of erroring.\n/// Only considers up to `max_commits` most recent commits.\npub fn get_recent_commit_times_git2(\n repo_path: &Path,\n max_commits: usize,\n) -> Option<HashMap<String, u64>> {\n // Walk up until you find a .git folder but not higher than the base of the given repo_path\n let mut current_path = repo_path.to_path_buf();\n while current_path.components().count() > 1 {\n if current_path.join(\".git\").exists() {\n break;\n }\n current_path = current_path.parent()?.to_path_buf();\n }\n\n let repo = match git2::Repository::open(&current_path) {\n Ok(repo) => repo,\n Err(_) => {\n debug!(\"Not a Git repository or unable to open: {:?}\", current_path);\n return None;\n }\n };\n\n let mut revwalk = match repo.revwalk() {\n Ok(revwalk) => revwalk,\n Err(_) => {\n debug!(\"Unable to get revwalk for: {:?}\", current_path);\n return None;\n }\n };\n\n if let Err(e) = revwalk.push_head() {\n debug!(\n \"Unable to push HEAD to revwalk: {:?} in {:?}\",\n e, current_path\n );\n return None;\n }\n revwalk.set_sorting(git2::Sort::TIME).ok()?;\n\n let mut commit_times = HashMap::new();\n for oid_result in revwalk.take(max_commits) {\n let oid = match oid_result {\n Ok(oid) => oid,\n Err(e) => {\n debug!(\"Error during revwalk iteration: {:?}\", e);\n continue;\n }\n };\n\n let commit = match repo.find_commit(oid) {\n Ok(commit) => commit,\n Err(e) => {\n debug!(\"Failed to find commit for OID {:?}: {:?}\", oid, e);\n continue;\n }\n };\n let tree = match commit.tree() {\n Ok(tree) => tree,\n Err(e) => {\n debug!(\"Failed to get tree for commit {:?}: {:?}\", oid, e);\n continue;\n }\n };\n\n let time = commit.time().seconds() as u64;\n tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {\n if let Some(name) = entry.name() {\n if entry.kind() == Some(git2::ObjectType::Blob) {\n let full_path = format!(\"{}{}\", root, name);\n commit_times.entry(full_path).or_insert(time);\n }\n }\n git2::TreeWalkResult::Ok\n })\n .ok()?;\n }\n\n Some(commit_times)\n}\n"], ["/yek/src/main.rs", "use anyhow::Result;\nuse bytesize::ByteSize;\nuse rayon::join;\nuse std::path::Path;\nuse tracing::{debug, Level};\nuse tracing_subscriber::fmt;\nuse yek::{config::YekConfig, serialize_repo};\n\nfn main() -> Result<()> {\n // 1) Parse CLI + config files:\n let mut full_config = YekConfig::init_config();\n\n let env_filter = if full_config.debug {\n \"yek=debug,ignore=off\"\n } else {\n \"yek=info,ignore=off\"\n };\n\n // 2) Initialize tracing:\n fmt::Subscriber::builder()\n .with_max_level(if full_config.debug {\n Level::DEBUG\n } else {\n Level::INFO\n })\n .with_target(false)\n .with_thread_ids(false)\n .with_thread_names(false)\n .with_file(false)\n .with_line_number(false)\n .with_level(true)\n .with_env_filter(env_filter)\n .compact()\n .init();\n\n if full_config.debug {\n let config_str = serde_json::to_string_pretty(&full_config)?;\n debug!(\"Configuration:\\n{}\", config_str);\n }\n\n // If streaming => skip checksum + read. Just do single-thread call to serialize_repo.\n // If not streaming => run checksum + repo serialization in parallel.\n if full_config.stream {\n let (output, files) = serialize_repo(&full_config)?;\n // We print actual text to stdout:\n println!(\"{}\", output);\n\n if full_config.debug {\n debug!(\"{} files processed (streaming).\", files.len());\n debug!(\"Output lines: {}\", output.lines().count());\n }\n } else {\n // Not streaming => run repo serialization & checksum in parallel\n let (serialization_res, checksum_res) = join(\n || serialize_repo(&full_config),\n || YekConfig::get_checksum(&full_config.input_paths),\n );\n\n // Handle both results\n let (output_string, files) = serialization_res?;\n let checksum = checksum_res;\n\n // Now set the final output file with the computed checksum\n let extension = if full_config.json { \"json\" } else { \"txt\" };\n let output_dir = full_config.output_dir.as_ref().ok_or_else(|| {\n anyhow::anyhow!(\"Output directory is required when not in streaming mode. This may indicate a configuration validation error.\")\n })?;\n\n let final_path = Path::new(output_dir)\n .join(format!(\"yek-output-{}.{}\", checksum, extension))\n .to_string_lossy()\n .to_string();\n full_config.output_file_full_path = Some(final_path.clone());\n\n // If debug, show stats\n if full_config.debug {\n let size = ByteSize::b(output_string.len() as u64);\n debug!(\"{} files processed\", files.len());\n debug!(\"{} generated\", size);\n debug!(\"{} lines generated\", output_string.lines().count());\n }\n\n // Actually write the final output file.\n // We'll do it right here (instead of inside `serialize_repo`) to ensure we use our new final_path:\n std::fs::write(&final_path, output_string.as_bytes())?;\n\n // Print path to stdout (like original code did)\n println!(\"{}\", final_path);\n }\n\n Ok(())\n}\n"], ["/yek/src/defaults.rs", "/// Known binary file extensions that should be skipped\n#[rustfmt::skip]\npub const BINARY_FILE_EXTENSIONS: &[&str] = &[\n // Executables, Libraries, Core Dumps\n \"exe\", \"dll\", \"so\", \"dylib\", \"ocx\", \"ax\", \"drv\", \"sys\", \"msi\", \"app\", \"ipa\", \"apk\",\n \"bin\", \"out\", \"a\", \"lib\", \"ko\", \"elf\", \"o\", \"nro\", \"core\", \"img\", \"iso\",\n\n // Java / .NET / Archives\n \"class\", \"jar\", \"war\", \"ear\",\n \"resources\", // sometimes included in Java archives\n \"nupkg\", // NuGet package\n \"exe.config\", // sometimes for .NET\n \"dll.config\",\n \n // Archives & Compressed\n \"zip\", \"tar\", \"gz\", \"tgz\", \"bz2\", \"xz\", \"7z\", \"rar\", \"lz4\", \"lz\", \"zst\", \"lzma\",\n \"cab\", \"ar\", \"cpio\", \"rpm\", \"deb\", \"pkg\", \"crx\", \"bin\", \"dmg\", \"hfs\", \"img\",\n \"cso\", // Compressed ISO\n \"bz\", \"tbz\", \"tbz2\", \"tlz\", \"txz\", \"z\", \"Z\", \"apk\", \"xapk\",\n\n // Disk & Container Images\n \"iso\", \"img\", \"dmg\", \"vhd\", \"vhdx\", \"vmdk\", \"vdi\", \"qcow\", \"qcow2\",\n \"mdf\", \"mds\", \"nrg\", \"uif\",\n\n // Documents & Office\n \"pdf\",\n \"doc\", \"docx\", \"dot\", \"dotx\", \"docm\", \"dotm\",\n \"xls\", \"xlsx\", \"xlsm\", \"xlsb\", \"xlt\", \"xltx\", \"xltm\", \"xlc\", \"xlw\",\n \"ppt\", \"pptx\", \"pptm\", \"pps\", \"ppsx\", \"pot\", \"potx\", \"potm\",\n \"pub\", // Microsoft Publisher\n \"vsd\", \"vsdx\", // Visio\n \"accdb\", \"accde\", \"mdb\", \"mde\", // Access\n \"odt\", \"ods\", \"odp\", \"odg\", \"odf\", // OpenDocument\n \"pages\", \"numbers\", \"key\", // Apple iWork\n \"rtf\", // can be binary-like depending on usage\n\n // Spreadsheets, DB, and Misc Data\n \"db\", \"sqlite\", \"db3\", \"s3db\", \"frm\", \"myd\", \"myi\", // MySQL\n \"mdb\", \"bak\", \"nsf\", // Lotus Notes\n \"gdb\", \"fdb\", // Firebird\n \"mdb\", // Access DB\n \"wdb\", // Works DB\n\n // Images\n \"jpg\", \"jpeg\", \"png\", \"gif\", \"bmp\", \"ico\", \"tiff\", \"tif\", \"webp\", \"jfif\", \"jp2\",\n \"psd\", \"psb\", \"xcf\", \"ai\", \"eps\", \"raw\", \"arw\", \"cr2\", \"nef\", \"dng\", \"raf\", \"orf\",\n \"sr2\", \"heic\", \"heif\", \"icns\", \"img\", \"bpg\",\n\n // Audio\n \"mp3\", \"mp2\", \"aac\", \"ac3\", \"wav\", \"ogg\", \"oga\", \"flac\", \"alac\", \"m4a\", \"mp4a\",\n \"wma\", \"ra\", \"ram\", \"ape\", \"opus\", \"amr\", \"awb\",\n\n // Video\n \"mp4\", \"m4v\", \"mov\", \"avi\", \"wmv\", \"mkv\", \"flv\", \"f4v\", \"f4p\", \"f4a\", \"f4b\", \"3gp\",\n \"3g2\", \"mpeg\", \"mpg\", \"mpe\", \"m1v\", \"m2v\", \"ts\", \"mts\", \"m2ts\", \"vob\", \"rm\", \"rmvb\",\n \"asf\", \"ogv\", \"ogm\", \"webm\", \"dv\", \"divx\", \"xvid\",\n\n // Font Files\n \"ttf\", \"otf\", \"woff\", \"woff2\", \"eot\", \"fon\", \"psf\",\n\n // Firmware / BIOS / ROM / Game Data\n \"rom\", \"iso\", \"bin\", \"gba\", \"gbc\", \"nds\", \"n64\", \"z64\", \"v64\", \"gcm\", \"ciso\", \"wbfs\",\n \"pak\", \"wad\", \"dat\", \"sav\", \"rpx\",\n\n // Flash / Vector\n \"swf\", \"fla\", \"svgz\", // .svgz is compressed SVG (binary)\n\n // CAD / 3D\n \"dwg\", \"dxf\", \"dwf\", \"skp\", \"ifc\",\n \"stl\", \"obj\", \"fbx\", \"dae\", \"blend\", \"3ds\", \"ase\", \"gltf\", \"glb\",\n \n // E-Books\n \"epub\", \"mobi\", \"azw\", \"azw3\", \"fb2\", \"lrf\", \"lit\", \"pdb\",\n\n // Other\n \"swp\", \"swo\", // Vim swap files\n \"pch\", // Precompiled header\n \"xex\", \"elf\", // Console executables\n \"dmp\", \"mdmp\", // Memory dump\n \"bkf\", \"bkp\", // Backup\n \"pak\", // Common game data archives\n \"idx\", \"dat\", \"vcd\", // Various binary data\n \"icns\", // macOS icon\n \"hlp\", \"chm\", // Windows help\n \"torrent\", // BitTorrent\n \"mar\", // Mozilla archive\n \"qcow\", \"qcow2\", // QEMU disk\n \"apk\", \"aab\", // Android package/bundle\n \"crx\", // Chrome extension\n \"appx\", // Windows app package\n \"xap\", // Windows Phone app\n];\n\n/// Default sets of ignore patterns (separate from .gitignore)\npub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[\n \"LICENSE\",\n \".git/**\",\n \".next/**\",\n \"node_modules/**\",\n \"vendor/**\",\n \"dist/**\",\n \"build/**\",\n \"out/**\",\n \"target/**\",\n \"bin/**\",\n \"obj/**\",\n \".idea/**\",\n \".vscode/**\",\n \".vs/**\",\n \".settings/**\",\n \".gradle/**\",\n \".mvn/**\",\n \".pytest_cache/**\",\n \"__pycache__/**\",\n \".sass-cache/**\",\n \".vercel/**\",\n \".turbo/**\",\n \"coverage/**\",\n \"test-results/**\",\n \".gitignore\",\n \"pnpm-lock.yaml\",\n \"yek.toml\",\n \"package-lock.json\",\n \"yarn.lock\",\n \"Cargo.lock\",\n \"Gemfile.lock\",\n \"composer.lock\",\n \"mix.lock\",\n \"poetry.lock\",\n \"Pipfile.lock\",\n \"packages.lock.json\",\n \"paket.lock\",\n \"*.pyc\",\n \"*.pyo\",\n \"*.pyd\",\n \"*.class\",\n \"*.o\",\n \"*.obj\",\n \"*.dll\",\n \"*.exe\",\n \"*.so\",\n \"*.dylib\",\n \"*.log\",\n \"*.tmp\",\n \"*.temp\",\n \"*.swp\",\n \"*.swo\",\n \".DS_Store\",\n \"Thumbs.db\",\n \".env*\",\n \"*.bak\",\n \"*~\",\n];\n\npub const DEFAULT_OUTPUT_TEMPLATE: &str = \">>>> FILE_PATH\\nFILE_CONTENT\";\n"]], "task_instance_info": {"created_time": "2025-08-21 01:47:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub fn validate (&self) -> Result<()> {}", "code_description": "This code segment functions to: Perform comprehensive validation checks on configuration parameters including template structure integrity, size format correctness, directory existence, and pattern syntax verification while enforcing constraints on numeric value ranges."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n pub fn validate(&self) -> Result<()> {\n // Validate max_size format\n if self.token_mode {\n self.tokens.parse::<usize>().map_err(|_| {\n anyhow!(\"Invalid token size format '{}' - must be a positive integer\", self.tokens)\n })?;\n } else {\n ByteSize::from_str(&self.max_size).map_err(|_| {\n anyhow!(\n \"Invalid size format '{}' - must be like '10MB' or '128K'\",\n self.max_size\n )\n })?;\n }\n\n // Validate git_boost_max bounds\n if let Some(boost) = self.git_boost_max {\n if !(0..=1000).contains(&boost) {\n return Err(anyhow!(\"git_boost_max must be between 0 and 1000\"));\n }\n }\n\n // Validate output template contains required placeholders\n if !self.output_template.contains(\"FILE_PATH\") {\n return Err(anyhow!(\"output_template must contain FILE_PATH placeholder\"));\n }\n if !self.output_template.contains(\"FILE_CONTENT\") {\n return Err(anyhow!(\"output_template must contain FILE_CONTENT placeholder\"));\n }\n\n // Validate max_git_depth\n if self.max_git_depth < 0 {\n return Err(anyhow!(\"max_git_depth cannot be negative\"));\n }\n\n Ok(())\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 01-48-01"}, "editdistance_info": {"edit_distance": 18.4149, "calculate_time": "2025-08-21 01:48:01", "true_code_clean": "pub fn validate(&self) -> Result<()> {\n if !self.output_template.contains(\"FILE_PATH\")\n || !self.output_template.contains(\"FILE_CONTENT\")\n {\n return Err(anyhow!(\n \"output_template: must contain FILE_PATH and FILE_CONTENT\"\n ));\n }\n if self.max_size == \"0\" {\n return Err(anyhow!(\"max_size: cannot be 0\"));\n }\n if !self.token_mode {\n ByteSize::from_str(&self.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?;\n } else if self.tokens.to_lowercase().ends_with('k') {\n let val = self.tokens[..self.tokens.len() - 1]\n .trim()\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n } else if !self.tokens.is_empty() {\n let val = self\n .tokens\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n }\n if !self.stream {\n self.ensure_output_dir()?;\n }\n for pattern in &self.ignore_patterns {\n glob::Pattern::new(pattern)\n .map_err(|e| anyhow!(\"ignore_patterns: Invalid pattern '{}': {}\", pattern, e))?;\n }\n for rule in &self.priority_rules {\n if rule.score < 0 || rule.score > 1000 {\n return Err(anyhow!(\n \"priority_rules: Priority score {} must be between 0 and 1000\",\n rule.score\n ));\n }\n glob::Pattern::new(&rule.pattern).map_err(|e| {\n anyhow!(\"priority_rules: Invalid pattern '{}': {}\", rule.pattern, e)\n })?;\n }\n Ok(())\n }", "predict_code_clean": "pub fn validate(&self) -> Result<()> {\n if self.token_mode {\n self.tokens.parse::<usize>().map_err(|_| {\n anyhow!(\"Invalid token size format '{}' - must be a positive integer\", self.tokens)\n })?;\n } else {\n ByteSize::from_str(&self.max_size).map_err(|_| {\n anyhow!(\n \"Invalid size format '{}' - must be like '10MB' or '128K'\",\n self.max_size\n )\n })?;\n }\n if let Some(boost) = self.git_boost_max {\n if !(0..=1000).contains(&boost) {\n return Err(anyhow!(\"git_boost_max must be between 0 and 1000\"));\n }\n }\n if !self.output_template.contains(\"FILE_PATH\") {\n return Err(anyhow!(\"output_template must contain FILE_PATH placeholder\"));\n }\n if !self.output_template.contains(\"FILE_CONTENT\") {\n return Err(anyhow!(\"output_template must contain FILE_CONTENT placeholder\"));\n }\n if self.max_git_depth < 0 {\n return Err(anyhow!(\"max_git_depth cannot be negative\"));\n }\n Ok(())\n }"}}
{"repo_name": "yek", "file_name": "/yek/src/parallel.rs", "inference_info": {"prefix_code": "use crate::{config::YekConfig, priority::get_file_priority, Result};\nuse content_inspector::{inspect, ContentType};\nuse glob::glob;\nuse ignore::gitignore::GitignoreBuilder;\nuse path_slash::PathBufExt;\nuse rayon::prelude::*;\nuse std::{\n collections::HashMap,\n fs,\n path::Path,\n sync::{mpsc, Arc},\n};\nuse tracing::debug;\n\n#[derive(Debug, Clone)]\npub struct ProcessedFile {\n pub priority: i32,\n pub file_index: usize,\n pub rel_path: String,\n pub content: String,\n}\n\n/// Process a single file, checking ignore patterns and reading its contents.\nfn process_single_file(\n file_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n let base_dir = file_path.parent().unwrap_or(Path::new(\"\"));\n let rel_path = normalize_path(file_path, base_dir);\n\n // Build the gitignore\n let mut gitignore_builder = GitignoreBuilder::new(base_dir);\n for pattern in &config.ignore_patterns {\n gitignore_builder.add_line(None, pattern)?;\n }\n\n // If there is a .gitignore in this folder, add it last so its \"!\" lines override prior patterns\n let gitignore_file = base_dir.join(\".gitignore\");\n if gitignore_file.exists() {\n gitignore_builder.add(&gitignore_file);\n }\n\n let gitignore = gitignore_builder.build()?;\n if gitignore.matched(file_path, false).is_ignore() {\n debug!(\"Skipping ignored file: {rel_path}\");\n return Ok(Vec::new());\n }\n\n let mut processed_files = Vec::new();\n\n match fs::read(file_path) {\n Ok(content) => {\n if inspect(&content) == ContentType::BINARY {\n debug!(\"Skipping binary file: {rel_path}\");\n } else {\n let rule_priority = get_file_priority(&rel_path, &config.priority_rules);\n let boost = boost_map.get(&rel_path).copied().unwrap_or(0);\n let combined_priority = rule_priority + boost;\n\n processed_files.push(ProcessedFile {\n priority: combined_priority,\n file_index: 0, // For a single file, the index is always 0\n rel_path,\n content: String::from_utf8_lossy(&content).to_string(),\n });\n }\n }\n Err(e) => {\n debug!(\"Failed to read {rel_path}: {e}\");\n }\n }\n\n Ok(processed_files)\n}\n\n/// Walk files in parallel (if a directory is given), skipping ignored paths,\n/// then read each file's contents in a separate thread.\n/// Return the resulting `ProcessedFile` objects.\n", "suffix_code": "\n\n/// Internal function to handle directory recursion (separated for clarity)\nfn process_files_parallel_internal(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n // It's a directory, so walk it\n let mut walk_builder = ignore::WalkBuilder::new(base_path);\n\n // Standard filters + no follow symlinks\n walk_builder\n .follow_links(false)\n .standard_filters(true)\n .require_git(false);\n\n // Build the gitignore\n let mut gitignore_builder = GitignoreBuilder::new(base_path);\n // Add our custom patterns first\n for pattern in &config.ignore_patterns {\n gitignore_builder.add_line(None, pattern)?;\n }\n\n // If there is a .gitignore in this folder, add it last so its \"!\" lines override prior patterns\n let gitignore_file = base_path.join(\".gitignore\");\n if gitignore_file.exists() {\n gitignore_builder.add(&gitignore_file);\n }\n\n let gitignore = Arc::new(gitignore_builder.build()?); // Propagate error here\n\n // This channel will carry (path, rel_path) to the processing thread\n let (processed_files_tx, processed_files_rx) = mpsc::channel::<(std::path::PathBuf, String)>();\n\n // Processing happens on a dedicated thread, to keep from blocking the main walker\n let process_thread = std::thread::spawn({\n let priority_rules = config.priority_rules.clone();\n let boost_map = boost_map.clone();\n move || {\n let mut processed = Vec::new();\n for (path, rel_path) in processed_files_rx {\n // Read entire file\n match fs::read(&path) {\n Ok(content) => {\n // Check if it's binary quickly\n if inspect(&content) == ContentType::BINARY {\n debug!(\"Skipping binary file: {rel_path}\");\n continue;\n }\n // Compute priority\n let rule_priority = get_file_priority(&rel_path, &priority_rules);\n let boost = boost_map.get(&rel_path).copied().unwrap_or(0);\n let combined = rule_priority + boost;\n processed.push(ProcessedFile {\n priority: combined,\n file_index: 0, // assigned later\n rel_path,\n content: String::from_utf8_lossy(&content).to_string(),\n });\n }\n Err(e) => {\n debug!(\"Failed to read {rel_path}: {e}\");\n }\n }\n }\n processed\n }\n });\n\n // Use ignore's parallel walker to skip ignored files\n let base_cloned = base_path.to_owned();\n let walker_tx = processed_files_tx.clone();\n\n // Now build the walker (no .gitignore custom filename)\n walk_builder.build_parallel().run(move || {\n let base_dir = base_cloned.clone();\n let processed_files_tx = walker_tx.clone();\n let gitignore = Arc::clone(&gitignore);\n\n Box::new(move |entry| {\n let entry = match entry {\n Ok(e) => e,\n Err(_) => return ignore::WalkState::Continue,\n };\n // Only process files\n if !entry.file_type().is_some_and(|ft| ft.is_file()) {\n return ignore::WalkState::Continue;\n }\n\n let path = entry.path().to_path_buf();\n let rel_path = normalize_path(&path, &base_dir);\n\n // If gitignore says skip, we do not even read\n if gitignore.matched(&path, false).is_ignore() {\n debug!(\"Skipping ignored file: {rel_path}\");\n return ignore::WalkState::Continue;\n }\n\n // Otherwise we send to processing thread\n processed_files_tx.send((path, rel_path)).ok();\n ignore::WalkState::Continue\n })\n });\n\n // Drop the sender so the thread can end\n drop(processed_files_tx);\n\n // Join the processing thread\n let mut processed_files = process_thread.join().unwrap();\n\n // Now assign file_index within each priority group\n let mut counters = HashMap::new();\n for f in &mut processed_files {\n let ctr = counters.entry(f.priority).or_insert(0);\n f.file_index = *ctr;\n *ctr += 1;\n }\n\n if config.debug {\n debug!(\n \"Processed {} files in parallel for base_path: {}\",\n processed_files.len(),\n base_path.display()\n );\n }\n\n // Sort by priority desc, then file_index\n processed_files.par_sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .reverse()\n .then_with(|| a.file_index.cmp(&b.file_index))\n });\n\n Ok(processed_files)\n}\n\n/// Create a relative, slash-normalized path\npub fn normalize_path(path: &Path, base: &Path) -> String {\n path.strip_prefix(base)\n .unwrap_or(path)\n .to_path_buf()\n .to_slash()\n .unwrap_or_default()\n .to_string()\n}\n", "middle_code": "pub fn process_files_parallel(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n let mut expanded_paths = Vec::new();\n let path_str = base_path.to_string_lossy();\n for entry in glob(&path_str)? {\n match entry {\n Ok(path) => expanded_paths.push(path),\n Err(e) => debug!(\"Glob entry error: {:?}\", e),\n }\n }\n if expanded_paths.len() == 1 && expanded_paths[0].is_file() {\n return process_single_file(&expanded_paths[0], config, boost_map);\n }\n let mut all_processed_files = Vec::new();\n for path in expanded_paths {\n if path.is_file() {\n all_processed_files.extend(process_single_file(&path, config, boost_map)?);\n } else if path.is_dir() {\n all_processed_files.extend(process_files_parallel_internal(&path, config, boost_map)?);\n }\n }\n Ok(all_processed_files)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/yek/src/lib.rs", "use anyhow::anyhow;\nuse anyhow::Result;\nuse bytesize::ByteSize;\nuse content_inspector::{inspect, ContentType};\nuse rayon::prelude::*;\nuse std::{\n collections::HashMap,\n fs::File,\n io::{self, Read},\n path::Path,\n str::FromStr,\n sync::OnceLock,\n};\nuse tiktoken_rs::CoreBPE;\n\npub mod config;\npub mod defaults;\npub mod parallel;\npub mod priority;\n\nuse config::YekConfig;\nuse parallel::{process_files_parallel, ProcessedFile};\nuse priority::compute_recentness_boost;\n\n// Add a static BPE encoder for reuse\nstatic TOKENIZER: OnceLock<CoreBPE> = OnceLock::new();\n\nfn get_tokenizer() -> &'static CoreBPE {\n TOKENIZER.get_or_init(|| {\n tiktoken_rs::get_bpe_from_model(\"gpt-3.5-turbo\").expect(\"Failed to load tokenizer\")\n })\n}\n\n/// Check if a file is likely text or binary by reading only a small chunk.\n/// This avoids reading large files fully just to detect their type.\npub fn is_text_file(path: &Path, user_binary_extensions: &[String]) -> io::Result<bool> {\n // If extension is known to be binary, skip quickly\n if let Some(ext) = path.extension().and_then(|e| e.to_str()) {\n if user_binary_extensions.iter().any(|bin_ext| bin_ext == ext) {\n return Ok(false);\n }\n }\n\n // Short partial read to check if it's binary or text\n const INSPECTION_BYTES: usize = 8192;\n let mut file = File::open(path)?;\n let mut buf = vec![0u8; INSPECTION_BYTES];\n let n = file.read(&mut buf)?;\n buf.truncate(n);\n\n Ok(inspect(&buf) != ContentType::BINARY)\n}\n\n/// Main entrypoint for serialization, used by CLI and tests\npub fn serialize_repo(config: &YekConfig) -> Result<(String, Vec<ProcessedFile>)> {\n // Gather commit times from each input path that is a directory\n let combined_commit_times = config\n .input_paths\n .par_iter()\n .filter_map(|path_str| {\n let repo_path = Path::new(path_str);\n if repo_path.is_dir() {\n priority::get_recent_commit_times_git2(\n repo_path,\n config.max_git_depth.try_into().unwrap_or(0),\n )\n } else {\n None\n }\n })\n .flatten()\n .collect::<HashMap<String, u64>>();\n\n // Compute a recentness-based boost\n let recentness_boost =\n compute_recentness_boost(&combined_commit_times, config.git_boost_max.unwrap_or(100));\n\n // Process files in parallel for each input path\n let merged_files = config\n .input_paths\n .par_iter()\n .map(|path_str| {\n let path = Path::new(path_str);\n process_files_parallel(path, config, &recentness_boost)\n })\n .collect::<Result<Vec<Vec<ProcessedFile>>>>()?\n .into_iter()\n .flatten()\n .collect::<Vec<ProcessedFile>>();\n\n let mut files = merged_files;\n\n // Sort final (priority asc, then file_index asc)\n files.par_sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .then_with(|| a.rel_path.cmp(&b.rel_path))\n });\n\n // Build the final output string\n let output_string = concat_files(&files, config)?;\n\n // Only count tokens if debug logging is enabled\n if tracing::Level::DEBUG <= tracing::level_filters::STATIC_MAX_LEVEL {\n tracing::debug!(\"{} tokens generated\", count_tokens(&output_string));\n }\n\n Ok((output_string, files))\n}\n\npub fn concat_files(files: &[ProcessedFile], config: &YekConfig) -> anyhow::Result<String> {\n let mut accumulated = 0_usize;\n let cap = if config.token_mode {\n parse_token_limit(&config.tokens)?\n } else {\n ByteSize::from_str(&config.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?\n .as_u64() as usize\n };\n\n // Sort by priority (asc) and file_index (asc)\n let mut sorted_files: Vec<_> = files.iter().collect();\n sorted_files.sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .then_with(|| a.rel_path.cmp(&b.rel_path))\n });\n\n let mut files_to_include = Vec::new();\n for file in sorted_files {\n let content_size = if config.token_mode {\n // Format the file content with template first, then count tokens\n let formatted = if config.json {\n serde_json::to_string(&serde_json::json!({\n \"filename\": &file.rel_path,\n \"content\": &file.content,\n }))\n .map_err(|e| anyhow!(\"Failed to serialize JSON: {}\", e))?\n } else {\n config\n .output_template\n .replace(\"FILE_PATH\", &file.rel_path)\n .replace(\"FILE_CONTENT\", &file.content)\n };\n count_tokens(&formatted)\n } else {\n file.content.len()\n };\n\n if accumulated + content_size <= cap {\n accumulated += content_size;\n files_to_include.push(file);\n } else {\n break;\n }\n }\n\n if config.json {\n // JSON array of objects\n Ok(serde_json::to_string_pretty(\n &files_to_include\n .iter()\n .map(|f| {\n serde_json::json!({\n \"filename\": &f.rel_path,\n \"content\": &f.content,\n })\n })\n .collect::<Vec<_>>(),\n )?)\n } else {\n // Use the user-defined template\n Ok(files_to_include\n .iter()\n .map(|f| {\n config\n .output_template\n .replace(\"FILE_PATH\", &f.rel_path)\n .replace(\"FILE_CONTENT\", &f.content)\n // Handle both literal \"\\n\" and escaped \"\\\\n\"\n .replace(\"\\\\\\\\\\n\", \"\\n\") // First handle escaped newline\n .replace(\"\\\\\\\\n\", \"\\n\") // Then handle escaped \\n sequence\n })\n .collect::<Vec<_>>()\n .join(\"\\n\"))\n }\n}\n\n/// Parse a token limit string like \"800k\" or \"1000\" into a number\npub fn parse_token_limit(limit: &str) -> anyhow::Result<usize> {\n if limit.to_lowercase().ends_with('k') {\n limit[..limit.len() - 1]\n .trim()\n .parse::<usize>()\n .map(|n| n * 1000)\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n } else {\n limit\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n }\n}\n\n/// Count tokens using tiktoken's GPT-3.5-Turbo tokenizer for accuracy\npub fn count_tokens(text: &str) -> usize {\n get_tokenizer().encode_with_special_tokens(text).len()\n}\n"], ["/yek/src/config.rs", "use anyhow::{anyhow, Result};\nuse bytesize::ByteSize;\nuse clap_config_file::ClapConfigFile;\nuse sha2::{Digest, Sha256};\nuse std::io::IsTerminal;\nuse std::{fs, path::Path, str::FromStr, time::UNIX_EPOCH};\n\nuse crate::{\n defaults::{BINARY_FILE_EXTENSIONS, DEFAULT_IGNORE_PATTERNS, DEFAULT_OUTPUT_TEMPLATE},\n priority::PriorityRule,\n};\n\n#[derive(Clone, Debug, Default, clap::ValueEnum, serde::Serialize, serde::Deserialize)]\npub enum ConfigFormat {\n #[default]\n Toml,\n Yaml,\n Json,\n}\n\n#[derive(ClapConfigFile, Clone)]\n#[config_file_name = \"yek\"]\n#[config_file_formats = \"toml,yaml,json\"]\npub struct YekConfig {\n /// Input files and/or directories to process\n #[config_arg(positional)]\n pub input_paths: Vec<String>,\n\n /// Print version of yek\n #[config_arg(long = \"version\", short = 'V')]\n pub version: bool,\n\n /// Max size per chunk. e.g. \"10MB\" or \"128K\" or when using token counting mode, \"100\" or \"128K\"\n #[config_arg(default_value = \"10MB\")]\n pub max_size: String,\n\n /// Use token mode instead of byte mode\n #[config_arg()]\n pub tokens: String,\n\n /// Enable JSON output\n #[config_arg()]\n pub json: bool,\n\n /// Enable debug output\n #[config_arg()]\n pub debug: bool,\n\n /// Output directory. If none is provided & stdout is a TTY, we pick a temp dir\n #[config_arg()]\n pub output_dir: Option<String>,\n\n /// Output template. Defaults to \">>>> FILE_PATH\\nFILE_CONTENT\"\n #[config_arg(default_value = \">>>> FILE_PATH\\nFILE_CONTENT\")]\n pub output_template: String,\n\n /// Ignore patterns\n #[config_arg(long = \"ignore-patterns\", multi_value_behavior = \"extend\")]\n pub ignore_patterns: Vec<String>,\n\n /// Unignore patterns. Yek has some built-in ignore patterns, but you can override them here.\n #[config_arg(long = \"unignore-patterns\", multi_value_behavior = \"extend\")]\n pub unignore_patterns: Vec<String>,\n\n /// Priority rules\n #[config_arg(accept_from = \"config_only\")]\n pub priority_rules: Vec<PriorityRule>,\n\n /// Binary file extensions to ignore\n #[config_arg(accept_from = \"config_only\", default_value = BINARY_FILE_EXTENSIONS)]\n pub binary_extensions: Vec<String>,\n\n /// Maximum additional boost from Git commit times (0..1000)\n #[config_arg(accept_from = \"config_only\")]\n pub git_boost_max: Option<i32>,\n\n /// True if we should stream output to stdout (computed)\n pub stream: bool,\n\n /// True if we should count tokens, not bytes (computed)\n pub token_mode: bool,\n\n /// Final resolved output file path (only used if not streaming)\n pub output_file_full_path: Option<String>,\n\n /// Maximum depth to search for Git commit times\n #[config_arg(accept_from = \"config_only\", default_value = \"100\")]\n pub max_git_depth: i32,\n}\n\n/// Provide defaults so tests or other callers can create a baseline YekConfig easily.\nimpl Default for YekConfig {\n fn default() -> Self {\n Self {\n input_paths: Vec::new(),\n version: false,\n max_size: \"10MB\".to_string(),\n tokens: String::new(),\n json: false,\n debug: false,\n output_dir: None,\n output_template: DEFAULT_OUTPUT_TEMPLATE.to_string(),\n ignore_patterns: Vec::new(),\n unignore_patterns: Vec::new(),\n priority_rules: Vec::new(),\n binary_extensions: BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect(),\n git_boost_max: Some(100),\n\n // computed fields\n stream: false,\n token_mode: false,\n output_file_full_path: None,\n max_git_depth: 100,\n }\n }\n}\n\nimpl YekConfig {\n pub fn extend_config_with_defaults(input_paths: Vec<String>, output_dir: String) -> Self {\n YekConfig {\n input_paths,\n output_dir: Some(output_dir),\n ..Default::default()\n }\n }\n}\n\nimpl YekConfig {\n /// Ensure output directory exists and is valid. Returns the resolved output directory path.\n pub fn ensure_output_dir(&self) -> Result<String> {\n if self.stream {\n return Ok(String::new());\n }\n\n let output_dir = if let Some(dir) = &self.output_dir {\n dir.clone()\n } else {\n let temp_dir = std::env::temp_dir().join(\"yek-output\");\n temp_dir.to_string_lossy().to_string()\n };\n\n let path = Path::new(&output_dir);\n if path.exists() && !path.is_dir() {\n return Err(anyhow!(\n \"output_dir: '{}' exists but is not a directory\",\n output_dir\n ));\n }\n\n std::fs::create_dir_all(path)\n .map_err(|e| anyhow!(\"output_dir: cannot create '{}': {}\", output_dir, e))?;\n\n Ok(output_dir)\n }\n\n /// Parse from CLI + config file, fill in computed fields, and validate.\n pub fn init_config() -> Self {\n // 1) parse from CLI and optional config file:\n let mut cfg = YekConfig::parse();\n\n // Handle version flag\n if cfg.version {\n println!(\"{}\", env!(\"CARGO_PKG_VERSION\"));\n std::process::exit(0);\n }\n\n // 2) compute derived fields:\n cfg.token_mode = !cfg.tokens.is_empty();\n let force_tty = std::env::var(\"FORCE_TTY\").is_ok();\n\n cfg.stream = !std::io::stdout().is_terminal() && !force_tty;\n\n // default input dirs to current dir if none:\n if cfg.input_paths.is_empty() {\n cfg.input_paths.push(\".\".to_string());\n }\n\n // Extend binary extensions with the built-in list:\n let mut merged_bins = BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n merged_bins.append(&mut cfg.binary_extensions);\n cfg.binary_extensions = merged_bins\n .into_iter()\n .collect::<std::collections::HashSet<_>>()\n .into_iter()\n .collect();\n\n // Always start with default ignore patterns, then add user's:\n let mut ignore = DEFAULT_IGNORE_PATTERNS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n ignore.extend(cfg.ignore_patterns);\n cfg.ignore_patterns = ignore;\n\n // Apply unignore patterns (turn them into negative globs \"!…\")\n cfg.ignore_patterns\n .extend(cfg.unignore_patterns.iter().map(|pat| format!(\"!{}\", pat)));\n\n // Handle output directory setup\n if !cfg.stream {\n match cfg.ensure_output_dir() {\n Ok(dir) => cfg.output_dir = Some(dir),\n Err(e) => {\n eprintln!(\"Warning: Failed to create output directory: {}\", e);\n cfg.stream = true; // Fall back to streaming mode\n }\n }\n }\n\n // By default, we start with no final output_file_full_path:\n cfg.output_file_full_path = None;\n\n // 3) Validate\n if let Err(e) = cfg.validate() {\n eprintln!(\"Error: {}\", e);\n std::process::exit(1);\n }\n\n cfg\n }\n\n /// Compute a quick checksum for the input paths (files and directories).\n /// For directories, it uses the top-level listing. For files, it uses the file metadata.\n pub fn get_checksum(input_paths: &[String]) -> String {\n let mut hasher = Sha256::new();\n for path_str in input_paths {\n let base_path = Path::new(path_str);\n if !base_path.exists() {\n continue;\n }\n\n // If it's a file, hash the file metadata directly\n if base_path.is_file() {\n if let Ok(meta) = fs::metadata(base_path) {\n hasher.update(path_str.as_bytes());\n hasher.update(meta.len().to_le_bytes());\n\n if let Ok(mod_time) = meta.modified() {\n if let Ok(dur) = mod_time.duration_since(UNIX_EPOCH) {\n hasher.update(dur.as_secs().to_le_bytes());\n hasher.update(dur.subsec_nanos().to_le_bytes());\n }\n }\n }\n continue;\n }\n\n // If it's a directory, hash its contents\n let entries = match fs::read_dir(base_path) {\n Ok(iter) => iter.filter_map(|e| e.ok()).collect::<Vec<_>>(),\n Err(_) => continue,\n };\n\n // Sort deterministically by path name\n let mut sorted = entries;\n sorted.sort_by_key(|a| a.path());\n\n for entry in sorted {\n let p = entry.path();\n if let Ok(meta) = fs::metadata(&p) {\n let path_str = p.to_string_lossy();\n hasher.update(path_str.as_bytes());\n hasher.update(meta.len().to_le_bytes());\n\n if let Ok(mod_time) = meta.modified() {\n if let Ok(dur) = mod_time.duration_since(UNIX_EPOCH) {\n hasher.update(dur.as_secs().to_le_bytes());\n hasher.update(dur.subsec_nanos().to_le_bytes());\n }\n }\n }\n }\n }\n let result = hasher.finalize();\n // Convert the 32-byte result to hex, but only keep the first 8 characters\n let hex = format!(\"{:x}\", result);\n hex[..8].to_owned()\n }\n\n /// Validate the final config.\n pub fn validate(&self) -> Result<()> {\n if !self.output_template.contains(\"FILE_PATH\")\n || !self.output_template.contains(\"FILE_CONTENT\")\n {\n return Err(anyhow!(\n \"output_template: must contain FILE_PATH and FILE_CONTENT\"\n ));\n }\n\n if self.max_size == \"0\" {\n return Err(anyhow!(\"max_size: cannot be 0\"));\n }\n\n if !self.token_mode {\n ByteSize::from_str(&self.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?;\n } else if self.tokens.to_lowercase().ends_with('k') {\n let val = self.tokens[..self.tokens.len() - 1]\n .trim()\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n } else if !self.tokens.is_empty() {\n // parse as integer\n let val = self\n .tokens\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n }\n\n // If not streaming, validate output directory\n if !self.stream {\n self.ensure_output_dir()?;\n }\n\n // Validate ignore patterns\n for pattern in &self.ignore_patterns {\n glob::Pattern::new(pattern)\n .map_err(|e| anyhow!(\"ignore_patterns: Invalid pattern '{}': {}\", pattern, e))?;\n }\n\n // Validate priority rules\n for rule in &self.priority_rules {\n if rule.score < 0 || rule.score > 1000 {\n return Err(anyhow!(\n \"priority_rules: Priority score {} must be between 0 and 1000\",\n rule.score\n ));\n }\n glob::Pattern::new(&rule.pattern).map_err(|e| {\n anyhow!(\"priority_rules: Invalid pattern '{}': {}\", rule.pattern, e)\n })?;\n }\n\n Ok(())\n }\n}\n"], ["/yek/src/priority.rs", "use git2;\nuse regex;\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, path::Path};\nuse tracing::debug;\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\npub struct PriorityRule {\n pub pattern: String,\n pub score: i32,\n}\n\n/// Determine final priority of a file by scanning the priority list\n/// in descending order of score.\npub fn get_file_priority(path: &str, rules: &[PriorityRule]) -> i32 {\n let mut priority = 0;\n for rule in rules {\n if let Ok(re) = regex::Regex::new(&rule.pattern) {\n if re.is_match(path) {\n priority += rule.score;\n }\n }\n }\n priority\n}\n\n/// Rank-based approach to compute how \"recent\" each file is (0=oldest, 1=newest).\n/// Then scale it to a user-defined or default max boost.\npub fn compute_recentness_boost(\n commit_times: &HashMap<String, u64>,\n max_boost: i32,\n) -> HashMap<String, i32> {\n if commit_times.is_empty() {\n return HashMap::new();\n }\n\n // Sort by ascending commit time => first is oldest\n let mut sorted: Vec<(&String, &u64)> = commit_times.iter().collect();\n sorted.sort_by_key(|(_, t)| **t);\n\n // If there's only one file, or zero, no boosts make sense\n if sorted.len() <= 1 {\n let mut single = HashMap::new();\n for file in commit_times.keys() {\n single.insert(file.clone(), 0);\n }\n return single;\n }\n\n let mut result = HashMap::new();\n let oldest_time = *sorted.first().unwrap().1;\n let newest_time = *sorted.last().unwrap().1;\n let time_range = newest_time.saturating_sub(oldest_time) as f64;\n\n // If all files have the same timestamp, they should all get the same boost\n if time_range == 0.0 {\n for (path, _) in sorted {\n result.insert(path.clone(), 0);\n }\n return result;\n }\n\n // Calculate boost based on time difference from oldest file\n for (path, time) in sorted {\n let time_diff = (*time - oldest_time) as f64;\n let rank = time_diff / time_range; // 0.0..1.0 (older files get lower rank)\n let boost = (rank * max_boost as f64).round() as i32; // Newer files get higher boost\n result.insert(path.clone(), boost);\n }\n result\n}\n\n/// Get the commit time of the most recent change to each file using git2.\n/// Returns a map from file path (relative to the repo root) → last commit Unix time.\n/// If Git or .git folder is missing, returns None instead of erroring.\n/// Only considers up to `max_commits` most recent commits.\npub fn get_recent_commit_times_git2(\n repo_path: &Path,\n max_commits: usize,\n) -> Option<HashMap<String, u64>> {\n // Walk up until you find a .git folder but not higher than the base of the given repo_path\n let mut current_path = repo_path.to_path_buf();\n while current_path.components().count() > 1 {\n if current_path.join(\".git\").exists() {\n break;\n }\n current_path = current_path.parent()?.to_path_buf();\n }\n\n let repo = match git2::Repository::open(&current_path) {\n Ok(repo) => repo,\n Err(_) => {\n debug!(\"Not a Git repository or unable to open: {:?}\", current_path);\n return None;\n }\n };\n\n let mut revwalk = match repo.revwalk() {\n Ok(revwalk) => revwalk,\n Err(_) => {\n debug!(\"Unable to get revwalk for: {:?}\", current_path);\n return None;\n }\n };\n\n if let Err(e) = revwalk.push_head() {\n debug!(\n \"Unable to push HEAD to revwalk: {:?} in {:?}\",\n e, current_path\n );\n return None;\n }\n revwalk.set_sorting(git2::Sort::TIME).ok()?;\n\n let mut commit_times = HashMap::new();\n for oid_result in revwalk.take(max_commits) {\n let oid = match oid_result {\n Ok(oid) => oid,\n Err(e) => {\n debug!(\"Error during revwalk iteration: {:?}\", e);\n continue;\n }\n };\n\n let commit = match repo.find_commit(oid) {\n Ok(commit) => commit,\n Err(e) => {\n debug!(\"Failed to find commit for OID {:?}: {:?}\", oid, e);\n continue;\n }\n };\n let tree = match commit.tree() {\n Ok(tree) => tree,\n Err(e) => {\n debug!(\"Failed to get tree for commit {:?}: {:?}\", oid, e);\n continue;\n }\n };\n\n let time = commit.time().seconds() as u64;\n tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {\n if let Some(name) = entry.name() {\n if entry.kind() == Some(git2::ObjectType::Blob) {\n let full_path = format!(\"{}{}\", root, name);\n commit_times.entry(full_path).or_insert(time);\n }\n }\n git2::TreeWalkResult::Ok\n })\n .ok()?;\n }\n\n Some(commit_times)\n}\n"], ["/yek/src/main.rs", "use anyhow::Result;\nuse bytesize::ByteSize;\nuse rayon::join;\nuse std::path::Path;\nuse tracing::{debug, Level};\nuse tracing_subscriber::fmt;\nuse yek::{config::YekConfig, serialize_repo};\n\nfn main() -> Result<()> {\n // 1) Parse CLI + config files:\n let mut full_config = YekConfig::init_config();\n\n let env_filter = if full_config.debug {\n \"yek=debug,ignore=off\"\n } else {\n \"yek=info,ignore=off\"\n };\n\n // 2) Initialize tracing:\n fmt::Subscriber::builder()\n .with_max_level(if full_config.debug {\n Level::DEBUG\n } else {\n Level::INFO\n })\n .with_target(false)\n .with_thread_ids(false)\n .with_thread_names(false)\n .with_file(false)\n .with_line_number(false)\n .with_level(true)\n .with_env_filter(env_filter)\n .compact()\n .init();\n\n if full_config.debug {\n let config_str = serde_json::to_string_pretty(&full_config)?;\n debug!(\"Configuration:\\n{}\", config_str);\n }\n\n // If streaming => skip checksum + read. Just do single-thread call to serialize_repo.\n // If not streaming => run checksum + repo serialization in parallel.\n if full_config.stream {\n let (output, files) = serialize_repo(&full_config)?;\n // We print actual text to stdout:\n println!(\"{}\", output);\n\n if full_config.debug {\n debug!(\"{} files processed (streaming).\", files.len());\n debug!(\"Output lines: {}\", output.lines().count());\n }\n } else {\n // Not streaming => run repo serialization & checksum in parallel\n let (serialization_res, checksum_res) = join(\n || serialize_repo(&full_config),\n || YekConfig::get_checksum(&full_config.input_paths),\n );\n\n // Handle both results\n let (output_string, files) = serialization_res?;\n let checksum = checksum_res;\n\n // Now set the final output file with the computed checksum\n let extension = if full_config.json { \"json\" } else { \"txt\" };\n let output_dir = full_config.output_dir.as_ref().ok_or_else(|| {\n anyhow::anyhow!(\"Output directory is required when not in streaming mode. This may indicate a configuration validation error.\")\n })?;\n\n let final_path = Path::new(output_dir)\n .join(format!(\"yek-output-{}.{}\", checksum, extension))\n .to_string_lossy()\n .to_string();\n full_config.output_file_full_path = Some(final_path.clone());\n\n // If debug, show stats\n if full_config.debug {\n let size = ByteSize::b(output_string.len() as u64);\n debug!(\"{} files processed\", files.len());\n debug!(\"{} generated\", size);\n debug!(\"{} lines generated\", output_string.lines().count());\n }\n\n // Actually write the final output file.\n // We'll do it right here (instead of inside `serialize_repo`) to ensure we use our new final_path:\n std::fs::write(&final_path, output_string.as_bytes())?;\n\n // Print path to stdout (like original code did)\n println!(\"{}\", final_path);\n }\n\n Ok(())\n}\n"], ["/yek/src/defaults.rs", "/// Known binary file extensions that should be skipped\n#[rustfmt::skip]\npub const BINARY_FILE_EXTENSIONS: &[&str] = &[\n // Executables, Libraries, Core Dumps\n \"exe\", \"dll\", \"so\", \"dylib\", \"ocx\", \"ax\", \"drv\", \"sys\", \"msi\", \"app\", \"ipa\", \"apk\",\n \"bin\", \"out\", \"a\", \"lib\", \"ko\", \"elf\", \"o\", \"nro\", \"core\", \"img\", \"iso\",\n\n // Java / .NET / Archives\n \"class\", \"jar\", \"war\", \"ear\",\n \"resources\", // sometimes included in Java archives\n \"nupkg\", // NuGet package\n \"exe.config\", // sometimes for .NET\n \"dll.config\",\n \n // Archives & Compressed\n \"zip\", \"tar\", \"gz\", \"tgz\", \"bz2\", \"xz\", \"7z\", \"rar\", \"lz4\", \"lz\", \"zst\", \"lzma\",\n \"cab\", \"ar\", \"cpio\", \"rpm\", \"deb\", \"pkg\", \"crx\", \"bin\", \"dmg\", \"hfs\", \"img\",\n \"cso\", // Compressed ISO\n \"bz\", \"tbz\", \"tbz2\", \"tlz\", \"txz\", \"z\", \"Z\", \"apk\", \"xapk\",\n\n // Disk & Container Images\n \"iso\", \"img\", \"dmg\", \"vhd\", \"vhdx\", \"vmdk\", \"vdi\", \"qcow\", \"qcow2\",\n \"mdf\", \"mds\", \"nrg\", \"uif\",\n\n // Documents & Office\n \"pdf\",\n \"doc\", \"docx\", \"dot\", \"dotx\", \"docm\", \"dotm\",\n \"xls\", \"xlsx\", \"xlsm\", \"xlsb\", \"xlt\", \"xltx\", \"xltm\", \"xlc\", \"xlw\",\n \"ppt\", \"pptx\", \"pptm\", \"pps\", \"ppsx\", \"pot\", \"potx\", \"potm\",\n \"pub\", // Microsoft Publisher\n \"vsd\", \"vsdx\", // Visio\n \"accdb\", \"accde\", \"mdb\", \"mde\", // Access\n \"odt\", \"ods\", \"odp\", \"odg\", \"odf\", // OpenDocument\n \"pages\", \"numbers\", \"key\", // Apple iWork\n \"rtf\", // can be binary-like depending on usage\n\n // Spreadsheets, DB, and Misc Data\n \"db\", \"sqlite\", \"db3\", \"s3db\", \"frm\", \"myd\", \"myi\", // MySQL\n \"mdb\", \"bak\", \"nsf\", // Lotus Notes\n \"gdb\", \"fdb\", // Firebird\n \"mdb\", // Access DB\n \"wdb\", // Works DB\n\n // Images\n \"jpg\", \"jpeg\", \"png\", \"gif\", \"bmp\", \"ico\", \"tiff\", \"tif\", \"webp\", \"jfif\", \"jp2\",\n \"psd\", \"psb\", \"xcf\", \"ai\", \"eps\", \"raw\", \"arw\", \"cr2\", \"nef\", \"dng\", \"raf\", \"orf\",\n \"sr2\", \"heic\", \"heif\", \"icns\", \"img\", \"bpg\",\n\n // Audio\n \"mp3\", \"mp2\", \"aac\", \"ac3\", \"wav\", \"ogg\", \"oga\", \"flac\", \"alac\", \"m4a\", \"mp4a\",\n \"wma\", \"ra\", \"ram\", \"ape\", \"opus\", \"amr\", \"awb\",\n\n // Video\n \"mp4\", \"m4v\", \"mov\", \"avi\", \"wmv\", \"mkv\", \"flv\", \"f4v\", \"f4p\", \"f4a\", \"f4b\", \"3gp\",\n \"3g2\", \"mpeg\", \"mpg\", \"mpe\", \"m1v\", \"m2v\", \"ts\", \"mts\", \"m2ts\", \"vob\", \"rm\", \"rmvb\",\n \"asf\", \"ogv\", \"ogm\", \"webm\", \"dv\", \"divx\", \"xvid\",\n\n // Font Files\n \"ttf\", \"otf\", \"woff\", \"woff2\", \"eot\", \"fon\", \"psf\",\n\n // Firmware / BIOS / ROM / Game Data\n \"rom\", \"iso\", \"bin\", \"gba\", \"gbc\", \"nds\", \"n64\", \"z64\", \"v64\", \"gcm\", \"ciso\", \"wbfs\",\n \"pak\", \"wad\", \"dat\", \"sav\", \"rpx\",\n\n // Flash / Vector\n \"swf\", \"fla\", \"svgz\", // .svgz is compressed SVG (binary)\n\n // CAD / 3D\n \"dwg\", \"dxf\", \"dwf\", \"skp\", \"ifc\",\n \"stl\", \"obj\", \"fbx\", \"dae\", \"blend\", \"3ds\", \"ase\", \"gltf\", \"glb\",\n \n // E-Books\n \"epub\", \"mobi\", \"azw\", \"azw3\", \"fb2\", \"lrf\", \"lit\", \"pdb\",\n\n // Other\n \"swp\", \"swo\", // Vim swap files\n \"pch\", // Precompiled header\n \"xex\", \"elf\", // Console executables\n \"dmp\", \"mdmp\", // Memory dump\n \"bkf\", \"bkp\", // Backup\n \"pak\", // Common game data archives\n \"idx\", \"dat\", \"vcd\", // Various binary data\n \"icns\", // macOS icon\n \"hlp\", \"chm\", // Windows help\n \"torrent\", // BitTorrent\n \"mar\", // Mozilla archive\n \"qcow\", \"qcow2\", // QEMU disk\n \"apk\", \"aab\", // Android package/bundle\n \"crx\", // Chrome extension\n \"appx\", // Windows app package\n \"xap\", // Windows Phone app\n];\n\n/// Default sets of ignore patterns (separate from .gitignore)\npub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[\n \"LICENSE\",\n \".git/**\",\n \".next/**\",\n \"node_modules/**\",\n \"vendor/**\",\n \"dist/**\",\n \"build/**\",\n \"out/**\",\n \"target/**\",\n \"bin/**\",\n \"obj/**\",\n \".idea/**\",\n \".vscode/**\",\n \".vs/**\",\n \".settings/**\",\n \".gradle/**\",\n \".mvn/**\",\n \".pytest_cache/**\",\n \"__pycache__/**\",\n \".sass-cache/**\",\n \".vercel/**\",\n \".turbo/**\",\n \"coverage/**\",\n \"test-results/**\",\n \".gitignore\",\n \"pnpm-lock.yaml\",\n \"yek.toml\",\n \"package-lock.json\",\n \"yarn.lock\",\n \"Cargo.lock\",\n \"Gemfile.lock\",\n \"composer.lock\",\n \"mix.lock\",\n \"poetry.lock\",\n \"Pipfile.lock\",\n \"packages.lock.json\",\n \"paket.lock\",\n \"*.pyc\",\n \"*.pyo\",\n \"*.pyd\",\n \"*.class\",\n \"*.o\",\n \"*.obj\",\n \"*.dll\",\n \"*.exe\",\n \"*.so\",\n \"*.dylib\",\n \"*.log\",\n \"*.tmp\",\n \"*.temp\",\n \"*.swp\",\n \"*.swo\",\n \".DS_Store\",\n \"Thumbs.db\",\n \".env*\",\n \"*.bak\",\n \"*~\",\n];\n\npub const DEFAULT_OUTPUT_TEMPLATE: &str = \">>>> FILE_PATH\\nFILE_CONTENT\";\n"]], "task_instance_info": {"created_time": "2025-08-21 01:47:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub fn process_files_parallel (\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {}", "code_description": "This code segment functions to: Expand input path patterns into individual files and directories, then recursively process their contents while applying priority calculations and ignoring specified patterns."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\npub fn process_files_parallel(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n if base_path.is_file() {\n process_single_file(base_path, config, boost_map)\n } else if base_path.is_dir() {\n process_files_parallel_internal(base_path, config, boost_map)\n } else {\n Ok(Vec::new())\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-48-05"}, "editdistance_info": {"edit_distance": 32.1429, "calculate_time": "2025-08-21 01:48:05", "true_code_clean": "pub fn process_files_parallel(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n let mut expanded_paths = Vec::new();\n let path_str = base_path.to_string_lossy();\n for entry in glob(&path_str)? {\n match entry {\n Ok(path) => expanded_paths.push(path),\n Err(e) => debug!(\"Glob entry error: {:?}\", e),\n }\n }\n if expanded_paths.len() == 1 && expanded_paths[0].is_file() {\n return process_single_file(&expanded_paths[0], config, boost_map);\n }\n let mut all_processed_files = Vec::new();\n for path in expanded_paths {\n if path.is_file() {\n all_processed_files.extend(process_single_file(&path, config, boost_map)?);\n } else if path.is_dir() {\n all_processed_files.extend(process_files_parallel_internal(&path, config, boost_map)?);\n }\n }\n Ok(all_processed_files)\n}", "predict_code_clean": "pub fn process_files_parallel(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n if base_path.is_file() {\n process_single_file(base_path, config, boost_map)\n } else if base_path.is_dir() {\n process_files_parallel_internal(base_path, config, boost_map)\n } else {\n Ok(Vec::new())\n }\n}"}}
{"repo_name": "yek", "file_name": "/yek/src/config.rs", "inference_info": {"prefix_code": "use anyhow::{anyhow, Result};\nuse bytesize::ByteSize;\nuse clap_config_file::ClapConfigFile;\nuse sha2::{Digest, Sha256};\nuse std::io::IsTerminal;\nuse std::{fs, path::Path, str::FromStr, time::UNIX_EPOCH};\n\nuse crate::{\n defaults::{BINARY_FILE_EXTENSIONS, DEFAULT_IGNORE_PATTERNS, DEFAULT_OUTPUT_TEMPLATE},\n priority::PriorityRule,\n};\n\n#[derive(Clone, Debug, Default, clap::ValueEnum, serde::Serialize, serde::Deserialize)]\npub enum ConfigFormat {\n #[default]\n Toml,\n Yaml,\n Json,\n}\n\n#[derive(ClapConfigFile, Clone)]\n#[config_file_name = \"yek\"]\n#[config_file_formats = \"toml,yaml,json\"]\npub struct YekConfig {\n /// Input files and/or directories to process\n #[config_arg(positional)]\n pub input_paths: Vec<String>,\n\n /// Print version of yek\n #[config_arg(long = \"version\", short = 'V')]\n pub version: bool,\n\n /// Max size per chunk. e.g. \"10MB\" or \"128K\" or when using token counting mode, \"100\" or \"128K\"\n #[config_arg(default_value = \"10MB\")]\n pub max_size: String,\n\n /// Use token mode instead of byte mode\n #[config_arg()]\n pub tokens: String,\n\n /// Enable JSON output\n #[config_arg()]\n pub json: bool,\n\n /// Enable debug output\n #[config_arg()]\n pub debug: bool,\n\n /// Output directory. If none is provided & stdout is a TTY, we pick a temp dir\n #[config_arg()]\n pub output_dir: Option<String>,\n\n /// Output template. Defaults to \">>>> FILE_PATH\\nFILE_CONTENT\"\n #[config_arg(default_value = \">>>> FILE_PATH\\nFILE_CONTENT\")]\n pub output_template: String,\n\n /// Ignore patterns\n #[config_arg(long = \"ignore-patterns\", multi_value_behavior = \"extend\")]\n pub ignore_patterns: Vec<String>,\n\n /// Unignore patterns. Yek has some built-in ignore patterns, but you can override them here.\n #[config_arg(long = \"unignore-patterns\", multi_value_behavior = \"extend\")]\n pub unignore_patterns: Vec<String>,\n\n /// Priority rules\n #[config_arg(accept_from = \"config_only\")]\n pub priority_rules: Vec<PriorityRule>,\n\n /// Binary file extensions to ignore\n #[config_arg(accept_from = \"config_only\", default_value = BINARY_FILE_EXTENSIONS)]\n pub binary_extensions: Vec<String>,\n\n /// Maximum additional boost from Git commit times (0..1000)\n #[config_arg(accept_from = \"config_only\")]\n pub git_boost_max: Option<i32>,\n\n /// True if we should stream output to stdout (computed)\n pub stream: bool,\n\n /// True if we should count tokens, not bytes (computed)\n pub token_mode: bool,\n\n /// Final resolved output file path (only used if not streaming)\n pub output_file_full_path: Option<String>,\n\n /// Maximum depth to search for Git commit times\n #[config_arg(accept_from = \"config_only\", default_value = \"100\")]\n pub max_git_depth: i32,\n}\n\n/// Provide defaults so tests or other callers can create a baseline YekConfig easily.\nimpl Default for YekConfig {\n fn default() -> Self {\n Self {\n input_paths: Vec::new(),\n version: false,\n max_size: \"10MB\".to_string(),\n tokens: String::new(),\n json: false,\n debug: false,\n output_dir: None,\n output_template: DEFAULT_OUTPUT_TEMPLATE.to_string(),\n ignore_patterns: Vec::new(),\n unignore_patterns: Vec::new(),\n priority_rules: Vec::new(),\n binary_extensions: BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect(),\n git_boost_max: Some(100),\n\n // computed fields\n stream: false,\n token_mode: false,\n output_file_full_path: None,\n max_git_depth: 100,\n }\n }\n}\n\nimpl YekConfig {\n pub fn extend_config_with_defaults(input_paths: Vec<String>, output_dir: String) -> Self {\n YekConfig {\n input_paths,\n output_dir: Some(output_dir),\n ..Default::default()\n }\n }\n}\n\nimpl YekConfig {\n /// Ensure output directory exists and is valid. Returns the resolved output directory path.\n pub fn ensure_output_dir(&self) -> Result<String> {\n if self.stream {\n return Ok(String::new());\n }\n\n let output_dir = if let Some(dir) = &self.output_dir {\n dir.clone()\n } else {\n let temp_dir = std::env::temp_dir().join(\"yek-output\");\n temp_dir.to_string_lossy().to_string()\n };\n\n let path = Path::new(&output_dir);\n if path.exists() && !path.is_dir() {\n return Err(anyhow!(\n \"output_dir: '{}' exists but is not a directory\",\n output_dir\n ));\n }\n\n std::fs::create_dir_all(path)\n .map_err(|e| anyhow!(\"output_dir: cannot create '{}': {}\", output_dir, e))?;\n\n Ok(output_dir)\n }\n\n /// Parse from CLI + config file, fill in computed fields, and validate.\n ", "suffix_code": "\n\n /// Compute a quick checksum for the input paths (files and directories).\n /// For directories, it uses the top-level listing. For files, it uses the file metadata.\n pub fn get_checksum(input_paths: &[String]) -> String {\n let mut hasher = Sha256::new();\n for path_str in input_paths {\n let base_path = Path::new(path_str);\n if !base_path.exists() {\n continue;\n }\n\n // If it's a file, hash the file metadata directly\n if base_path.is_file() {\n if let Ok(meta) = fs::metadata(base_path) {\n hasher.update(path_str.as_bytes());\n hasher.update(meta.len().to_le_bytes());\n\n if let Ok(mod_time) = meta.modified() {\n if let Ok(dur) = mod_time.duration_since(UNIX_EPOCH) {\n hasher.update(dur.as_secs().to_le_bytes());\n hasher.update(dur.subsec_nanos().to_le_bytes());\n }\n }\n }\n continue;\n }\n\n // If it's a directory, hash its contents\n let entries = match fs::read_dir(base_path) {\n Ok(iter) => iter.filter_map(|e| e.ok()).collect::<Vec<_>>(),\n Err(_) => continue,\n };\n\n // Sort deterministically by path name\n let mut sorted = entries;\n sorted.sort_by_key(|a| a.path());\n\n for entry in sorted {\n let p = entry.path();\n if let Ok(meta) = fs::metadata(&p) {\n let path_str = p.to_string_lossy();\n hasher.update(path_str.as_bytes());\n hasher.update(meta.len().to_le_bytes());\n\n if let Ok(mod_time) = meta.modified() {\n if let Ok(dur) = mod_time.duration_since(UNIX_EPOCH) {\n hasher.update(dur.as_secs().to_le_bytes());\n hasher.update(dur.subsec_nanos().to_le_bytes());\n }\n }\n }\n }\n }\n let result = hasher.finalize();\n // Convert the 32-byte result to hex, but only keep the first 8 characters\n let hex = format!(\"{:x}\", result);\n hex[..8].to_owned()\n }\n\n /// Validate the final config.\n pub fn validate(&self) -> Result<()> {\n if !self.output_template.contains(\"FILE_PATH\")\n || !self.output_template.contains(\"FILE_CONTENT\")\n {\n return Err(anyhow!(\n \"output_template: must contain FILE_PATH and FILE_CONTENT\"\n ));\n }\n\n if self.max_size == \"0\" {\n return Err(anyhow!(\"max_size: cannot be 0\"));\n }\n\n if !self.token_mode {\n ByteSize::from_str(&self.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?;\n } else if self.tokens.to_lowercase().ends_with('k') {\n let val = self.tokens[..self.tokens.len() - 1]\n .trim()\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n } else if !self.tokens.is_empty() {\n // parse as integer\n let val = self\n .tokens\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n }\n\n // If not streaming, validate output directory\n if !self.stream {\n self.ensure_output_dir()?;\n }\n\n // Validate ignore patterns\n for pattern in &self.ignore_patterns {\n glob::Pattern::new(pattern)\n .map_err(|e| anyhow!(\"ignore_patterns: Invalid pattern '{}': {}\", pattern, e))?;\n }\n\n // Validate priority rules\n for rule in &self.priority_rules {\n if rule.score < 0 || rule.score > 1000 {\n return Err(anyhow!(\n \"priority_rules: Priority score {} must be between 0 and 1000\",\n rule.score\n ));\n }\n glob::Pattern::new(&rule.pattern).map_err(|e| {\n anyhow!(\"priority_rules: Invalid pattern '{}': {}\", rule.pattern, e)\n })?;\n }\n\n Ok(())\n }\n}\n", "middle_code": "pub fn init_config() -> Self {\n let mut cfg = YekConfig::parse();\n if cfg.version {\n println!(\"{}\", env!(\"CARGO_PKG_VERSION\"));\n std::process::exit(0);\n }\n cfg.token_mode = !cfg.tokens.is_empty();\n let force_tty = std::env::var(\"FORCE_TTY\").is_ok();\n cfg.stream = !std::io::stdout().is_terminal() && !force_tty;\n if cfg.input_paths.is_empty() {\n cfg.input_paths.push(\".\".to_string());\n }\n let mut merged_bins = BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n merged_bins.append(&mut cfg.binary_extensions);\n cfg.binary_extensions = merged_bins\n .into_iter()\n .collect::<std::collections::HashSet<_>>()\n .into_iter()\n .collect();\n let mut ignore = DEFAULT_IGNORE_PATTERNS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n ignore.extend(cfg.ignore_patterns);\n cfg.ignore_patterns = ignore;\n cfg.ignore_patterns\n .extend(cfg.unignore_patterns.iter().map(|pat| format!(\"!{}\", pat)));\n if !cfg.stream {\n match cfg.ensure_output_dir() {\n Ok(dir) => cfg.output_dir = Some(dir),\n Err(e) => {\n eprintln!(\"Warning: Failed to create output directory: {}\", e);\n cfg.stream = true; \n }\n }\n }\n cfg.output_file_full_path = None;\n if let Err(e) = cfg.validate() {\n eprintln!(\"Error: {}\", e);\n std::process::exit(1);\n }\n cfg\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/yek/src/lib.rs", "use anyhow::anyhow;\nuse anyhow::Result;\nuse bytesize::ByteSize;\nuse content_inspector::{inspect, ContentType};\nuse rayon::prelude::*;\nuse std::{\n collections::HashMap,\n fs::File,\n io::{self, Read},\n path::Path,\n str::FromStr,\n sync::OnceLock,\n};\nuse tiktoken_rs::CoreBPE;\n\npub mod config;\npub mod defaults;\npub mod parallel;\npub mod priority;\n\nuse config::YekConfig;\nuse parallel::{process_files_parallel, ProcessedFile};\nuse priority::compute_recentness_boost;\n\n// Add a static BPE encoder for reuse\nstatic TOKENIZER: OnceLock<CoreBPE> = OnceLock::new();\n\nfn get_tokenizer() -> &'static CoreBPE {\n TOKENIZER.get_or_init(|| {\n tiktoken_rs::get_bpe_from_model(\"gpt-3.5-turbo\").expect(\"Failed to load tokenizer\")\n })\n}\n\n/// Check if a file is likely text or binary by reading only a small chunk.\n/// This avoids reading large files fully just to detect their type.\npub fn is_text_file(path: &Path, user_binary_extensions: &[String]) -> io::Result<bool> {\n // If extension is known to be binary, skip quickly\n if let Some(ext) = path.extension().and_then(|e| e.to_str()) {\n if user_binary_extensions.iter().any(|bin_ext| bin_ext == ext) {\n return Ok(false);\n }\n }\n\n // Short partial read to check if it's binary or text\n const INSPECTION_BYTES: usize = 8192;\n let mut file = File::open(path)?;\n let mut buf = vec![0u8; INSPECTION_BYTES];\n let n = file.read(&mut buf)?;\n buf.truncate(n);\n\n Ok(inspect(&buf) != ContentType::BINARY)\n}\n\n/// Main entrypoint for serialization, used by CLI and tests\npub fn serialize_repo(config: &YekConfig) -> Result<(String, Vec<ProcessedFile>)> {\n // Gather commit times from each input path that is a directory\n let combined_commit_times = config\n .input_paths\n .par_iter()\n .filter_map(|path_str| {\n let repo_path = Path::new(path_str);\n if repo_path.is_dir() {\n priority::get_recent_commit_times_git2(\n repo_path,\n config.max_git_depth.try_into().unwrap_or(0),\n )\n } else {\n None\n }\n })\n .flatten()\n .collect::<HashMap<String, u64>>();\n\n // Compute a recentness-based boost\n let recentness_boost =\n compute_recentness_boost(&combined_commit_times, config.git_boost_max.unwrap_or(100));\n\n // Process files in parallel for each input path\n let merged_files = config\n .input_paths\n .par_iter()\n .map(|path_str| {\n let path = Path::new(path_str);\n process_files_parallel(path, config, &recentness_boost)\n })\n .collect::<Result<Vec<Vec<ProcessedFile>>>>()?\n .into_iter()\n .flatten()\n .collect::<Vec<ProcessedFile>>();\n\n let mut files = merged_files;\n\n // Sort final (priority asc, then file_index asc)\n files.par_sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .then_with(|| a.rel_path.cmp(&b.rel_path))\n });\n\n // Build the final output string\n let output_string = concat_files(&files, config)?;\n\n // Only count tokens if debug logging is enabled\n if tracing::Level::DEBUG <= tracing::level_filters::STATIC_MAX_LEVEL {\n tracing::debug!(\"{} tokens generated\", count_tokens(&output_string));\n }\n\n Ok((output_string, files))\n}\n\npub fn concat_files(files: &[ProcessedFile], config: &YekConfig) -> anyhow::Result<String> {\n let mut accumulated = 0_usize;\n let cap = if config.token_mode {\n parse_token_limit(&config.tokens)?\n } else {\n ByteSize::from_str(&config.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?\n .as_u64() as usize\n };\n\n // Sort by priority (asc) and file_index (asc)\n let mut sorted_files: Vec<_> = files.iter().collect();\n sorted_files.sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .then_with(|| a.rel_path.cmp(&b.rel_path))\n });\n\n let mut files_to_include = Vec::new();\n for file in sorted_files {\n let content_size = if config.token_mode {\n // Format the file content with template first, then count tokens\n let formatted = if config.json {\n serde_json::to_string(&serde_json::json!({\n \"filename\": &file.rel_path,\n \"content\": &file.content,\n }))\n .map_err(|e| anyhow!(\"Failed to serialize JSON: {}\", e))?\n } else {\n config\n .output_template\n .replace(\"FILE_PATH\", &file.rel_path)\n .replace(\"FILE_CONTENT\", &file.content)\n };\n count_tokens(&formatted)\n } else {\n file.content.len()\n };\n\n if accumulated + content_size <= cap {\n accumulated += content_size;\n files_to_include.push(file);\n } else {\n break;\n }\n }\n\n if config.json {\n // JSON array of objects\n Ok(serde_json::to_string_pretty(\n &files_to_include\n .iter()\n .map(|f| {\n serde_json::json!({\n \"filename\": &f.rel_path,\n \"content\": &f.content,\n })\n })\n .collect::<Vec<_>>(),\n )?)\n } else {\n // Use the user-defined template\n Ok(files_to_include\n .iter()\n .map(|f| {\n config\n .output_template\n .replace(\"FILE_PATH\", &f.rel_path)\n .replace(\"FILE_CONTENT\", &f.content)\n // Handle both literal \"\\n\" and escaped \"\\\\n\"\n .replace(\"\\\\\\\\\\n\", \"\\n\") // First handle escaped newline\n .replace(\"\\\\\\\\n\", \"\\n\") // Then handle escaped \\n sequence\n })\n .collect::<Vec<_>>()\n .join(\"\\n\"))\n }\n}\n\n/// Parse a token limit string like \"800k\" or \"1000\" into a number\npub fn parse_token_limit(limit: &str) -> anyhow::Result<usize> {\n if limit.to_lowercase().ends_with('k') {\n limit[..limit.len() - 1]\n .trim()\n .parse::<usize>()\n .map(|n| n * 1000)\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n } else {\n limit\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n }\n}\n\n/// Count tokens using tiktoken's GPT-3.5-Turbo tokenizer for accuracy\npub fn count_tokens(text: &str) -> usize {\n get_tokenizer().encode_with_special_tokens(text).len()\n}\n"], ["/yek/src/parallel.rs", "use crate::{config::YekConfig, priority::get_file_priority, Result};\nuse content_inspector::{inspect, ContentType};\nuse glob::glob;\nuse ignore::gitignore::GitignoreBuilder;\nuse path_slash::PathBufExt;\nuse rayon::prelude::*;\nuse std::{\n collections::HashMap,\n fs,\n path::Path,\n sync::{mpsc, Arc},\n};\nuse tracing::debug;\n\n#[derive(Debug, Clone)]\npub struct ProcessedFile {\n pub priority: i32,\n pub file_index: usize,\n pub rel_path: String,\n pub content: String,\n}\n\n/// Process a single file, checking ignore patterns and reading its contents.\nfn process_single_file(\n file_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n let base_dir = file_path.parent().unwrap_or(Path::new(\"\"));\n let rel_path = normalize_path(file_path, base_dir);\n\n // Build the gitignore\n let mut gitignore_builder = GitignoreBuilder::new(base_dir);\n for pattern in &config.ignore_patterns {\n gitignore_builder.add_line(None, pattern)?;\n }\n\n // If there is a .gitignore in this folder, add it last so its \"!\" lines override prior patterns\n let gitignore_file = base_dir.join(\".gitignore\");\n if gitignore_file.exists() {\n gitignore_builder.add(&gitignore_file);\n }\n\n let gitignore = gitignore_builder.build()?;\n if gitignore.matched(file_path, false).is_ignore() {\n debug!(\"Skipping ignored file: {rel_path}\");\n return Ok(Vec::new());\n }\n\n let mut processed_files = Vec::new();\n\n match fs::read(file_path) {\n Ok(content) => {\n if inspect(&content) == ContentType::BINARY {\n debug!(\"Skipping binary file: {rel_path}\");\n } else {\n let rule_priority = get_file_priority(&rel_path, &config.priority_rules);\n let boost = boost_map.get(&rel_path).copied().unwrap_or(0);\n let combined_priority = rule_priority + boost;\n\n processed_files.push(ProcessedFile {\n priority: combined_priority,\n file_index: 0, // For a single file, the index is always 0\n rel_path,\n content: String::from_utf8_lossy(&content).to_string(),\n });\n }\n }\n Err(e) => {\n debug!(\"Failed to read {rel_path}: {e}\");\n }\n }\n\n Ok(processed_files)\n}\n\n/// Walk files in parallel (if a directory is given), skipping ignored paths,\n/// then read each file's contents in a separate thread.\n/// Return the resulting `ProcessedFile` objects.\npub fn process_files_parallel(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n // Expand globs into a list of paths\n let mut expanded_paths = Vec::new();\n let path_str = base_path.to_string_lossy();\n for entry in glob(&path_str)? {\n match entry {\n Ok(path) => expanded_paths.push(path),\n Err(e) => debug!(\"Glob entry error: {:?}\", e),\n }\n }\n\n // If it's a single file (no glob expansion or single file result), process it directly\n if expanded_paths.len() == 1 && expanded_paths[0].is_file() {\n return process_single_file(&expanded_paths[0], config, boost_map);\n }\n\n // Iterate over expanded paths, handling files and directories\n let mut all_processed_files = Vec::new();\n for path in expanded_paths {\n if path.is_file() {\n all_processed_files.extend(process_single_file(&path, config, boost_map)?);\n } else if path.is_dir() {\n // For directories, use the original recursive logic\n all_processed_files.extend(process_files_parallel_internal(&path, config, boost_map)?);\n }\n }\n\n Ok(all_processed_files)\n}\n\n/// Internal function to handle directory recursion (separated for clarity)\nfn process_files_parallel_internal(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n // It's a directory, so walk it\n let mut walk_builder = ignore::WalkBuilder::new(base_path);\n\n // Standard filters + no follow symlinks\n walk_builder\n .follow_links(false)\n .standard_filters(true)\n .require_git(false);\n\n // Build the gitignore\n let mut gitignore_builder = GitignoreBuilder::new(base_path);\n // Add our custom patterns first\n for pattern in &config.ignore_patterns {\n gitignore_builder.add_line(None, pattern)?;\n }\n\n // If there is a .gitignore in this folder, add it last so its \"!\" lines override prior patterns\n let gitignore_file = base_path.join(\".gitignore\");\n if gitignore_file.exists() {\n gitignore_builder.add(&gitignore_file);\n }\n\n let gitignore = Arc::new(gitignore_builder.build()?); // Propagate error here\n\n // This channel will carry (path, rel_path) to the processing thread\n let (processed_files_tx, processed_files_rx) = mpsc::channel::<(std::path::PathBuf, String)>();\n\n // Processing happens on a dedicated thread, to keep from blocking the main walker\n let process_thread = std::thread::spawn({\n let priority_rules = config.priority_rules.clone();\n let boost_map = boost_map.clone();\n move || {\n let mut processed = Vec::new();\n for (path, rel_path) in processed_files_rx {\n // Read entire file\n match fs::read(&path) {\n Ok(content) => {\n // Check if it's binary quickly\n if inspect(&content) == ContentType::BINARY {\n debug!(\"Skipping binary file: {rel_path}\");\n continue;\n }\n // Compute priority\n let rule_priority = get_file_priority(&rel_path, &priority_rules);\n let boost = boost_map.get(&rel_path).copied().unwrap_or(0);\n let combined = rule_priority + boost;\n processed.push(ProcessedFile {\n priority: combined,\n file_index: 0, // assigned later\n rel_path,\n content: String::from_utf8_lossy(&content).to_string(),\n });\n }\n Err(e) => {\n debug!(\"Failed to read {rel_path}: {e}\");\n }\n }\n }\n processed\n }\n });\n\n // Use ignore's parallel walker to skip ignored files\n let base_cloned = base_path.to_owned();\n let walker_tx = processed_files_tx.clone();\n\n // Now build the walker (no .gitignore custom filename)\n walk_builder.build_parallel().run(move || {\n let base_dir = base_cloned.clone();\n let processed_files_tx = walker_tx.clone();\n let gitignore = Arc::clone(&gitignore);\n\n Box::new(move |entry| {\n let entry = match entry {\n Ok(e) => e,\n Err(_) => return ignore::WalkState::Continue,\n };\n // Only process files\n if !entry.file_type().is_some_and(|ft| ft.is_file()) {\n return ignore::WalkState::Continue;\n }\n\n let path = entry.path().to_path_buf();\n let rel_path = normalize_path(&path, &base_dir);\n\n // If gitignore says skip, we do not even read\n if gitignore.matched(&path, false).is_ignore() {\n debug!(\"Skipping ignored file: {rel_path}\");\n return ignore::WalkState::Continue;\n }\n\n // Otherwise we send to processing thread\n processed_files_tx.send((path, rel_path)).ok();\n ignore::WalkState::Continue\n })\n });\n\n // Drop the sender so the thread can end\n drop(processed_files_tx);\n\n // Join the processing thread\n let mut processed_files = process_thread.join().unwrap();\n\n // Now assign file_index within each priority group\n let mut counters = HashMap::new();\n for f in &mut processed_files {\n let ctr = counters.entry(f.priority).or_insert(0);\n f.file_index = *ctr;\n *ctr += 1;\n }\n\n if config.debug {\n debug!(\n \"Processed {} files in parallel for base_path: {}\",\n processed_files.len(),\n base_path.display()\n );\n }\n\n // Sort by priority desc, then file_index\n processed_files.par_sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .reverse()\n .then_with(|| a.file_index.cmp(&b.file_index))\n });\n\n Ok(processed_files)\n}\n\n/// Create a relative, slash-normalized path\npub fn normalize_path(path: &Path, base: &Path) -> String {\n path.strip_prefix(base)\n .unwrap_or(path)\n .to_path_buf()\n .to_slash()\n .unwrap_or_default()\n .to_string()\n}\n"], ["/yek/src/priority.rs", "use git2;\nuse regex;\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, path::Path};\nuse tracing::debug;\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\npub struct PriorityRule {\n pub pattern: String,\n pub score: i32,\n}\n\n/// Determine final priority of a file by scanning the priority list\n/// in descending order of score.\npub fn get_file_priority(path: &str, rules: &[PriorityRule]) -> i32 {\n let mut priority = 0;\n for rule in rules {\n if let Ok(re) = regex::Regex::new(&rule.pattern) {\n if re.is_match(path) {\n priority += rule.score;\n }\n }\n }\n priority\n}\n\n/// Rank-based approach to compute how \"recent\" each file is (0=oldest, 1=newest).\n/// Then scale it to a user-defined or default max boost.\npub fn compute_recentness_boost(\n commit_times: &HashMap<String, u64>,\n max_boost: i32,\n) -> HashMap<String, i32> {\n if commit_times.is_empty() {\n return HashMap::new();\n }\n\n // Sort by ascending commit time => first is oldest\n let mut sorted: Vec<(&String, &u64)> = commit_times.iter().collect();\n sorted.sort_by_key(|(_, t)| **t);\n\n // If there's only one file, or zero, no boosts make sense\n if sorted.len() <= 1 {\n let mut single = HashMap::new();\n for file in commit_times.keys() {\n single.insert(file.clone(), 0);\n }\n return single;\n }\n\n let mut result = HashMap::new();\n let oldest_time = *sorted.first().unwrap().1;\n let newest_time = *sorted.last().unwrap().1;\n let time_range = newest_time.saturating_sub(oldest_time) as f64;\n\n // If all files have the same timestamp, they should all get the same boost\n if time_range == 0.0 {\n for (path, _) in sorted {\n result.insert(path.clone(), 0);\n }\n return result;\n }\n\n // Calculate boost based on time difference from oldest file\n for (path, time) in sorted {\n let time_diff = (*time - oldest_time) as f64;\n let rank = time_diff / time_range; // 0.0..1.0 (older files get lower rank)\n let boost = (rank * max_boost as f64).round() as i32; // Newer files get higher boost\n result.insert(path.clone(), boost);\n }\n result\n}\n\n/// Get the commit time of the most recent change to each file using git2.\n/// Returns a map from file path (relative to the repo root) → last commit Unix time.\n/// If Git or .git folder is missing, returns None instead of erroring.\n/// Only considers up to `max_commits` most recent commits.\npub fn get_recent_commit_times_git2(\n repo_path: &Path,\n max_commits: usize,\n) -> Option<HashMap<String, u64>> {\n // Walk up until you find a .git folder but not higher than the base of the given repo_path\n let mut current_path = repo_path.to_path_buf();\n while current_path.components().count() > 1 {\n if current_path.join(\".git\").exists() {\n break;\n }\n current_path = current_path.parent()?.to_path_buf();\n }\n\n let repo = match git2::Repository::open(&current_path) {\n Ok(repo) => repo,\n Err(_) => {\n debug!(\"Not a Git repository or unable to open: {:?}\", current_path);\n return None;\n }\n };\n\n let mut revwalk = match repo.revwalk() {\n Ok(revwalk) => revwalk,\n Err(_) => {\n debug!(\"Unable to get revwalk for: {:?}\", current_path);\n return None;\n }\n };\n\n if let Err(e) = revwalk.push_head() {\n debug!(\n \"Unable to push HEAD to revwalk: {:?} in {:?}\",\n e, current_path\n );\n return None;\n }\n revwalk.set_sorting(git2::Sort::TIME).ok()?;\n\n let mut commit_times = HashMap::new();\n for oid_result in revwalk.take(max_commits) {\n let oid = match oid_result {\n Ok(oid) => oid,\n Err(e) => {\n debug!(\"Error during revwalk iteration: {:?}\", e);\n continue;\n }\n };\n\n let commit = match repo.find_commit(oid) {\n Ok(commit) => commit,\n Err(e) => {\n debug!(\"Failed to find commit for OID {:?}: {:?}\", oid, e);\n continue;\n }\n };\n let tree = match commit.tree() {\n Ok(tree) => tree,\n Err(e) => {\n debug!(\"Failed to get tree for commit {:?}: {:?}\", oid, e);\n continue;\n }\n };\n\n let time = commit.time().seconds() as u64;\n tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {\n if let Some(name) = entry.name() {\n if entry.kind() == Some(git2::ObjectType::Blob) {\n let full_path = format!(\"{}{}\", root, name);\n commit_times.entry(full_path).or_insert(time);\n }\n }\n git2::TreeWalkResult::Ok\n })\n .ok()?;\n }\n\n Some(commit_times)\n}\n"], ["/yek/src/main.rs", "use anyhow::Result;\nuse bytesize::ByteSize;\nuse rayon::join;\nuse std::path::Path;\nuse tracing::{debug, Level};\nuse tracing_subscriber::fmt;\nuse yek::{config::YekConfig, serialize_repo};\n\nfn main() -> Result<()> {\n // 1) Parse CLI + config files:\n let mut full_config = YekConfig::init_config();\n\n let env_filter = if full_config.debug {\n \"yek=debug,ignore=off\"\n } else {\n \"yek=info,ignore=off\"\n };\n\n // 2) Initialize tracing:\n fmt::Subscriber::builder()\n .with_max_level(if full_config.debug {\n Level::DEBUG\n } else {\n Level::INFO\n })\n .with_target(false)\n .with_thread_ids(false)\n .with_thread_names(false)\n .with_file(false)\n .with_line_number(false)\n .with_level(true)\n .with_env_filter(env_filter)\n .compact()\n .init();\n\n if full_config.debug {\n let config_str = serde_json::to_string_pretty(&full_config)?;\n debug!(\"Configuration:\\n{}\", config_str);\n }\n\n // If streaming => skip checksum + read. Just do single-thread call to serialize_repo.\n // If not streaming => run checksum + repo serialization in parallel.\n if full_config.stream {\n let (output, files) = serialize_repo(&full_config)?;\n // We print actual text to stdout:\n println!(\"{}\", output);\n\n if full_config.debug {\n debug!(\"{} files processed (streaming).\", files.len());\n debug!(\"Output lines: {}\", output.lines().count());\n }\n } else {\n // Not streaming => run repo serialization & checksum in parallel\n let (serialization_res, checksum_res) = join(\n || serialize_repo(&full_config),\n || YekConfig::get_checksum(&full_config.input_paths),\n );\n\n // Handle both results\n let (output_string, files) = serialization_res?;\n let checksum = checksum_res;\n\n // Now set the final output file with the computed checksum\n let extension = if full_config.json { \"json\" } else { \"txt\" };\n let output_dir = full_config.output_dir.as_ref().ok_or_else(|| {\n anyhow::anyhow!(\"Output directory is required when not in streaming mode. This may indicate a configuration validation error.\")\n })?;\n\n let final_path = Path::new(output_dir)\n .join(format!(\"yek-output-{}.{}\", checksum, extension))\n .to_string_lossy()\n .to_string();\n full_config.output_file_full_path = Some(final_path.clone());\n\n // If debug, show stats\n if full_config.debug {\n let size = ByteSize::b(output_string.len() as u64);\n debug!(\"{} files processed\", files.len());\n debug!(\"{} generated\", size);\n debug!(\"{} lines generated\", output_string.lines().count());\n }\n\n // Actually write the final output file.\n // We'll do it right here (instead of inside `serialize_repo`) to ensure we use our new final_path:\n std::fs::write(&final_path, output_string.as_bytes())?;\n\n // Print path to stdout (like original code did)\n println!(\"{}\", final_path);\n }\n\n Ok(())\n}\n"], ["/yek/src/defaults.rs", "/// Known binary file extensions that should be skipped\n#[rustfmt::skip]\npub const BINARY_FILE_EXTENSIONS: &[&str] = &[\n // Executables, Libraries, Core Dumps\n \"exe\", \"dll\", \"so\", \"dylib\", \"ocx\", \"ax\", \"drv\", \"sys\", \"msi\", \"app\", \"ipa\", \"apk\",\n \"bin\", \"out\", \"a\", \"lib\", \"ko\", \"elf\", \"o\", \"nro\", \"core\", \"img\", \"iso\",\n\n // Java / .NET / Archives\n \"class\", \"jar\", \"war\", \"ear\",\n \"resources\", // sometimes included in Java archives\n \"nupkg\", // NuGet package\n \"exe.config\", // sometimes for .NET\n \"dll.config\",\n \n // Archives & Compressed\n \"zip\", \"tar\", \"gz\", \"tgz\", \"bz2\", \"xz\", \"7z\", \"rar\", \"lz4\", \"lz\", \"zst\", \"lzma\",\n \"cab\", \"ar\", \"cpio\", \"rpm\", \"deb\", \"pkg\", \"crx\", \"bin\", \"dmg\", \"hfs\", \"img\",\n \"cso\", // Compressed ISO\n \"bz\", \"tbz\", \"tbz2\", \"tlz\", \"txz\", \"z\", \"Z\", \"apk\", \"xapk\",\n\n // Disk & Container Images\n \"iso\", \"img\", \"dmg\", \"vhd\", \"vhdx\", \"vmdk\", \"vdi\", \"qcow\", \"qcow2\",\n \"mdf\", \"mds\", \"nrg\", \"uif\",\n\n // Documents & Office\n \"pdf\",\n \"doc\", \"docx\", \"dot\", \"dotx\", \"docm\", \"dotm\",\n \"xls\", \"xlsx\", \"xlsm\", \"xlsb\", \"xlt\", \"xltx\", \"xltm\", \"xlc\", \"xlw\",\n \"ppt\", \"pptx\", \"pptm\", \"pps\", \"ppsx\", \"pot\", \"potx\", \"potm\",\n \"pub\", // Microsoft Publisher\n \"vsd\", \"vsdx\", // Visio\n \"accdb\", \"accde\", \"mdb\", \"mde\", // Access\n \"odt\", \"ods\", \"odp\", \"odg\", \"odf\", // OpenDocument\n \"pages\", \"numbers\", \"key\", // Apple iWork\n \"rtf\", // can be binary-like depending on usage\n\n // Spreadsheets, DB, and Misc Data\n \"db\", \"sqlite\", \"db3\", \"s3db\", \"frm\", \"myd\", \"myi\", // MySQL\n \"mdb\", \"bak\", \"nsf\", // Lotus Notes\n \"gdb\", \"fdb\", // Firebird\n \"mdb\", // Access DB\n \"wdb\", // Works DB\n\n // Images\n \"jpg\", \"jpeg\", \"png\", \"gif\", \"bmp\", \"ico\", \"tiff\", \"tif\", \"webp\", \"jfif\", \"jp2\",\n \"psd\", \"psb\", \"xcf\", \"ai\", \"eps\", \"raw\", \"arw\", \"cr2\", \"nef\", \"dng\", \"raf\", \"orf\",\n \"sr2\", \"heic\", \"heif\", \"icns\", \"img\", \"bpg\",\n\n // Audio\n \"mp3\", \"mp2\", \"aac\", \"ac3\", \"wav\", \"ogg\", \"oga\", \"flac\", \"alac\", \"m4a\", \"mp4a\",\n \"wma\", \"ra\", \"ram\", \"ape\", \"opus\", \"amr\", \"awb\",\n\n // Video\n \"mp4\", \"m4v\", \"mov\", \"avi\", \"wmv\", \"mkv\", \"flv\", \"f4v\", \"f4p\", \"f4a\", \"f4b\", \"3gp\",\n \"3g2\", \"mpeg\", \"mpg\", \"mpe\", \"m1v\", \"m2v\", \"ts\", \"mts\", \"m2ts\", \"vob\", \"rm\", \"rmvb\",\n \"asf\", \"ogv\", \"ogm\", \"webm\", \"dv\", \"divx\", \"xvid\",\n\n // Font Files\n \"ttf\", \"otf\", \"woff\", \"woff2\", \"eot\", \"fon\", \"psf\",\n\n // Firmware / BIOS / ROM / Game Data\n \"rom\", \"iso\", \"bin\", \"gba\", \"gbc\", \"nds\", \"n64\", \"z64\", \"v64\", \"gcm\", \"ciso\", \"wbfs\",\n \"pak\", \"wad\", \"dat\", \"sav\", \"rpx\",\n\n // Flash / Vector\n \"swf\", \"fla\", \"svgz\", // .svgz is compressed SVG (binary)\n\n // CAD / 3D\n \"dwg\", \"dxf\", \"dwf\", \"skp\", \"ifc\",\n \"stl\", \"obj\", \"fbx\", \"dae\", \"blend\", \"3ds\", \"ase\", \"gltf\", \"glb\",\n \n // E-Books\n \"epub\", \"mobi\", \"azw\", \"azw3\", \"fb2\", \"lrf\", \"lit\", \"pdb\",\n\n // Other\n \"swp\", \"swo\", // Vim swap files\n \"pch\", // Precompiled header\n \"xex\", \"elf\", // Console executables\n \"dmp\", \"mdmp\", // Memory dump\n \"bkf\", \"bkp\", // Backup\n \"pak\", // Common game data archives\n \"idx\", \"dat\", \"vcd\", // Various binary data\n \"icns\", // macOS icon\n \"hlp\", \"chm\", // Windows help\n \"torrent\", // BitTorrent\n \"mar\", // Mozilla archive\n \"qcow\", \"qcow2\", // QEMU disk\n \"apk\", \"aab\", // Android package/bundle\n \"crx\", // Chrome extension\n \"appx\", // Windows app package\n \"xap\", // Windows Phone app\n];\n\n/// Default sets of ignore patterns (separate from .gitignore)\npub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[\n \"LICENSE\",\n \".git/**\",\n \".next/**\",\n \"node_modules/**\",\n \"vendor/**\",\n \"dist/**\",\n \"build/**\",\n \"out/**\",\n \"target/**\",\n \"bin/**\",\n \"obj/**\",\n \".idea/**\",\n \".vscode/**\",\n \".vs/**\",\n \".settings/**\",\n \".gradle/**\",\n \".mvn/**\",\n \".pytest_cache/**\",\n \"__pycache__/**\",\n \".sass-cache/**\",\n \".vercel/**\",\n \".turbo/**\",\n \"coverage/**\",\n \"test-results/**\",\n \".gitignore\",\n \"pnpm-lock.yaml\",\n \"yek.toml\",\n \"package-lock.json\",\n \"yarn.lock\",\n \"Cargo.lock\",\n \"Gemfile.lock\",\n \"composer.lock\",\n \"mix.lock\",\n \"poetry.lock\",\n \"Pipfile.lock\",\n \"packages.lock.json\",\n \"paket.lock\",\n \"*.pyc\",\n \"*.pyo\",\n \"*.pyd\",\n \"*.class\",\n \"*.o\",\n \"*.obj\",\n \"*.dll\",\n \"*.exe\",\n \"*.so\",\n \"*.dylib\",\n \"*.log\",\n \"*.tmp\",\n \"*.temp\",\n \"*.swp\",\n \"*.swo\",\n \".DS_Store\",\n \"Thumbs.db\",\n \".env*\",\n \"*.bak\",\n \"*~\",\n];\n\npub const DEFAULT_OUTPUT_TEMPLATE: &str = \">>>> FILE_PATH\\nFILE_CONTENT\";\n"]], "task_instance_info": {"created_time": "2025-08-21 01:47:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub fn init_config () -> Self {}", "code_description": "This code segment functions to: Initialize application configuration by merging command-line inputs with default values and environment variables, validate user-provided parameters, handle version requests, determine output streaming behavior based on terminal detection, merge system-defined and custom patterns for file processing, and ensure proper error handling for invalid configurations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n pub fn init_config() -> Self {\n let mut config = YekConfig::from_clap_config_file()\n .expect(\"Failed to parse CLI arguments and config file\");\n \n // Compute streaming mode: stream if output_dir not specified AND stdout isn't a TTY\n config.stream = config.output_dir.is_none() && !std::io::stdout().is_terminal();\n \n // Detect token mode from tokens field\n config.token_mode = !config.tokens.is_empty();\n\n // Validate before returning\n config.validate().expect(\"Invalid configuration\");\n \n config\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 01-48-52"}, "editdistance_info": {"edit_distance": 10.5978, "calculate_time": "2025-08-21 01:48:52", "true_code_clean": "pub fn init_config() -> Self {\n let mut cfg = YekConfig::parse();\n if cfg.version {\n println!(\"{}\", env!(\"CARGO_PKG_VERSION\"));\n std::process::exit(0);\n }\n cfg.token_mode = !cfg.tokens.is_empty();\n let force_tty = std::env::var(\"FORCE_TTY\").is_ok();\n cfg.stream = !std::io::stdout().is_terminal() && !force_tty;\n if cfg.input_paths.is_empty() {\n cfg.input_paths.push(\".\".to_string());\n }\n let mut merged_bins = BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n merged_bins.append(&mut cfg.binary_extensions);\n cfg.binary_extensions = merged_bins\n .into_iter()\n .collect::<std::collections::HashSet<_>>()\n .into_iter()\n .collect();\n let mut ignore = DEFAULT_IGNORE_PATTERNS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n ignore.extend(cfg.ignore_patterns);\n cfg.ignore_patterns = ignore;\n cfg.ignore_patterns\n .extend(cfg.unignore_patterns.iter().map(|pat| format!(\"!{}\", pat)));\n if !cfg.stream {\n match cfg.ensure_output_dir() {\n Ok(dir) => cfg.output_dir = Some(dir),\n Err(e) => {\n eprintln!(\"Warning: Failed to create output directory: {}\", e);\n cfg.stream = true; \n }\n }\n }\n cfg.output_file_full_path = None;\n if let Err(e) = cfg.validate() {\n eprintln!(\"Error: {}\", e);\n std::process::exit(1);\n }\n cfg\n }", "predict_code_clean": "pub fn init_config() -> Self {\n let mut config = YekConfig::from_clap_config_file()\n .expect(\"Failed to parse CLI arguments and config file\");\n config.stream = config.output_dir.is_none() && !std::io::stdout().is_terminal();\n config.token_mode = !config.tokens.is_empty();\n config.validate().expect(\"Invalid configuration\");\n config\n }"}}
{"repo_name": "yek", "file_name": "/yek/src/config.rs", "inference_info": {"prefix_code": "use anyhow::{anyhow, Result};\nuse bytesize::ByteSize;\nuse clap_config_file::ClapConfigFile;\nuse sha2::{Digest, Sha256};\nuse std::io::IsTerminal;\nuse std::{fs, path::Path, str::FromStr, time::UNIX_EPOCH};\n\nuse crate::{\n defaults::{BINARY_FILE_EXTENSIONS, DEFAULT_IGNORE_PATTERNS, DEFAULT_OUTPUT_TEMPLATE},\n priority::PriorityRule,\n};\n\n#[derive(Clone, Debug, Default, clap::ValueEnum, serde::Serialize, serde::Deserialize)]\npub enum ConfigFormat {\n #[default]\n Toml,\n Yaml,\n Json,\n}\n\n#[derive(ClapConfigFile, Clone)]\n#[config_file_name = \"yek\"]\n#[config_file_formats = \"toml,yaml,json\"]\npub struct YekConfig {\n /// Input files and/or directories to process\n #[config_arg(positional)]\n pub input_paths: Vec<String>,\n\n /// Print version of yek\n #[config_arg(long = \"version\", short = 'V')]\n pub version: bool,\n\n /// Max size per chunk. e.g. \"10MB\" or \"128K\" or when using token counting mode, \"100\" or \"128K\"\n #[config_arg(default_value = \"10MB\")]\n pub max_size: String,\n\n /// Use token mode instead of byte mode\n #[config_arg()]\n pub tokens: String,\n\n /// Enable JSON output\n #[config_arg()]\n pub json: bool,\n\n /// Enable debug output\n #[config_arg()]\n pub debug: bool,\n\n /// Output directory. If none is provided & stdout is a TTY, we pick a temp dir\n #[config_arg()]\n pub output_dir: Option<String>,\n\n /// Output template. Defaults to \">>>> FILE_PATH\\nFILE_CONTENT\"\n #[config_arg(default_value = \">>>> FILE_PATH\\nFILE_CONTENT\")]\n pub output_template: String,\n\n /// Ignore patterns\n #[config_arg(long = \"ignore-patterns\", multi_value_behavior = \"extend\")]\n pub ignore_patterns: Vec<String>,\n\n /// Unignore patterns. Yek has some built-in ignore patterns, but you can override them here.\n #[config_arg(long = \"unignore-patterns\", multi_value_behavior = \"extend\")]\n pub unignore_patterns: Vec<String>,\n\n /// Priority rules\n #[config_arg(accept_from = \"config_only\")]\n pub priority_rules: Vec<PriorityRule>,\n\n /// Binary file extensions to ignore\n #[config_arg(accept_from = \"config_only\", default_value = BINARY_FILE_EXTENSIONS)]\n pub binary_extensions: Vec<String>,\n\n /// Maximum additional boost from Git commit times (0..1000)\n #[config_arg(accept_from = \"config_only\")]\n pub git_boost_max: Option<i32>,\n\n /// True if we should stream output to stdout (computed)\n pub stream: bool,\n\n /// True if we should count tokens, not bytes (computed)\n pub token_mode: bool,\n\n /// Final resolved output file path (only used if not streaming)\n pub output_file_full_path: Option<String>,\n\n /// Maximum depth to search for Git commit times\n #[config_arg(accept_from = \"config_only\", default_value = \"100\")]\n pub max_git_depth: i32,\n}\n\n/// Provide defaults so tests or other callers can create a baseline YekConfig easily.\nimpl Default for YekConfig {\n fn default() -> Self {\n Self {\n input_paths: Vec::new(),\n version: false,\n max_size: \"10MB\".to_string(),\n tokens: String::new(),\n json: false,\n debug: false,\n output_dir: None,\n output_template: DEFAULT_OUTPUT_TEMPLATE.to_string(),\n ignore_patterns: Vec::new(),\n unignore_patterns: Vec::new(),\n priority_rules: Vec::new(),\n binary_extensions: BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect(),\n git_boost_max: Some(100),\n\n // computed fields\n stream: false,\n token_mode: false,\n output_file_full_path: None,\n max_git_depth: 100,\n }\n }\n}\n\nimpl YekConfig {\n pub fn extend_config_with_defaults(input_paths: Vec<String>, output_dir: String) -> Self {\n YekConfig {\n input_paths,\n output_dir: Some(output_dir),\n ..Default::default()\n }\n }\n}\n\nimpl YekConfig {\n /// Ensure output directory exists and is valid. Returns the resolved output directory path.\n pub fn ensure_output_dir(&self) -> Result<String> {\n if self.stream {\n return Ok(String::new());\n }\n\n let output_dir = if let Some(dir) = &self.output_dir {\n dir.clone()\n } else {\n let temp_dir = std::env::temp_dir().join(\"yek-output\");\n temp_dir.to_string_lossy().to_string()\n };\n\n let path = Path::new(&output_dir);\n if path.exists() && !path.is_dir() {\n return Err(anyhow!(\n \"output_dir: '{}' exists but is not a directory\",\n output_dir\n ));\n }\n\n std::fs::create_dir_all(path)\n .map_err(|e| anyhow!(\"output_dir: cannot create '{}': {}\", output_dir, e))?;\n\n Ok(output_dir)\n }\n\n /// Parse from CLI + config file, fill in computed fields, and validate.\n pub fn init_config() -> Self {\n // 1) parse from CLI and optional config file:\n let mut cfg = YekConfig::parse();\n\n // Handle version flag\n if cfg.version {\n println!(\"{}\", env!(\"CARGO_PKG_VERSION\"));\n std::process::exit(0);\n }\n\n // 2) compute derived fields:\n cfg.token_mode = !cfg.tokens.is_empty();\n let force_tty = std::env::var(\"FORCE_TTY\").is_ok();\n\n cfg.stream = !std::io::stdout().is_terminal() && !force_tty;\n\n // default input dirs to current dir if none:\n if cfg.input_paths.is_empty() {\n cfg.input_paths.push(\".\".to_string());\n }\n\n // Extend binary extensions with the built-in list:\n let mut merged_bins = BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n merged_bins.append(&mut cfg.binary_extensions);\n cfg.binary_extensions = merged_bins\n .into_iter()\n .collect::<std::collections::HashSet<_>>()\n .into_iter()\n .collect();\n\n // Always start with default ignore patterns, then add user's:\n let mut ignore = DEFAULT_IGNORE_PATTERNS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n ignore.extend(cfg.ignore_patterns);\n cfg.ignore_patterns = ignore;\n\n // Apply unignore patterns (turn them into negative globs \"!…\")\n cfg.ignore_patterns\n .extend(cfg.unignore_patterns.iter().map(|pat| format!(\"!{}\", pat)));\n\n // Handle output directory setup\n if !cfg.stream {\n match cfg.ensure_output_dir() {\n Ok(dir) => cfg.output_dir = Some(dir),\n Err(e) => {\n eprintln!(\"Warning: Failed to create output directory: {}\", e);\n cfg.stream = true; // Fall back to streaming mode\n }\n }\n }\n\n // By default, we start with no final output_file_full_path:\n cfg.output_file_full_path = None;\n\n // 3) Validate\n if let Err(e) = cfg.validate() {\n eprintln!(\"Error: {}\", e);\n std::process::exit(1);\n }\n\n cfg\n }\n\n /// Compute a quick checksum for the input paths (files and directories).\n /// For directories, it uses the top-level listing. For files, it uses the file metadata.\n pub fn get_checksum(input_paths: &[String]) -> String {\n let mut hasher = Sha256::new();\n for path_str in input_paths {\n let base_path = Path::new(path_str);\n if !base_path.exists() {\n continue;\n }\n\n // If it's a file, hash the file metadata directly\n if base_path.is_file() {\n if let Ok(meta) = fs::metadata(base_path) {\n hasher.update(path_str.as_bytes());\n hasher.update(meta.len().to_le_bytes());\n\n if let Ok(mod_time) = meta.modified() {\n if let Ok(dur) = mod_time.duration_since(UNIX_EPOCH) {\n hasher.update(dur.as_secs().to_le_bytes());\n hasher.update(dur.subsec_nanos().to_le_bytes());\n }\n }\n }\n continue;\n }\n\n // If it's a directory, hash its contents\n let entries = match fs::read_dir(base_path) {\n Ok(iter) => iter.filter_map(|e| e.ok()).collect::<Vec<_>>(),\n Err(_) => continue,\n };\n\n // Sort deterministically by path name\n let mut sorted = entries;\n sorted.sort_by_key(|a| a.path());\n\n for entry in sorted {\n let p = entry.path();\n if let Ok(meta) = fs::metadata(&p) {\n let path_str = p.to_string_lossy();\n hasher.update(path_str.as_bytes());\n hasher.update(meta.len().to_le_bytes());\n\n if let Ok(mod_time) = meta.modified() {\n if let Ok(dur) = mod_time.duration_since(UNIX_EPOCH) {\n hasher.update(dur.as_secs().to_le_bytes());\n hasher.update(dur.subsec_nanos().to_le_bytes());\n }\n }\n }\n }\n }\n let result = hasher.finalize();\n // Convert the 32-byte result to hex, but only keep the first 8 characters\n let hex = format!(\"{:x}\", result);\n hex[..8].to_owned()\n }\n\n /// Validate the final config.\n ", "suffix_code": "\n}\n", "middle_code": "pub fn validate(&self) -> Result<()> {\n if !self.output_template.contains(\"FILE_PATH\")\n || !self.output_template.contains(\"FILE_CONTENT\")\n {\n return Err(anyhow!(\n \"output_template: must contain FILE_PATH and FILE_CONTENT\"\n ));\n }\n if self.max_size == \"0\" {\n return Err(anyhow!(\"max_size: cannot be 0\"));\n }\n if !self.token_mode {\n ByteSize::from_str(&self.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?;\n } else if self.tokens.to_lowercase().ends_with('k') {\n let val = self.tokens[..self.tokens.len() - 1]\n .trim()\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n } else if !self.tokens.is_empty() {\n let val = self\n .tokens\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n }\n if !self.stream {\n self.ensure_output_dir()?;\n }\n for pattern in &self.ignore_patterns {\n glob::Pattern::new(pattern)\n .map_err(|e| anyhow!(\"ignore_patterns: Invalid pattern '{}': {}\", pattern, e))?;\n }\n for rule in &self.priority_rules {\n if rule.score < 0 || rule.score > 1000 {\n return Err(anyhow!(\n \"priority_rules: Priority score {} must be between 0 and 1000\",\n rule.score\n ));\n }\n glob::Pattern::new(&rule.pattern).map_err(|e| {\n anyhow!(\"priority_rules: Invalid pattern '{}': {}\", rule.pattern, e)\n })?;\n }\n Ok(())\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/yek/src/lib.rs", "use anyhow::anyhow;\nuse anyhow::Result;\nuse bytesize::ByteSize;\nuse content_inspector::{inspect, ContentType};\nuse rayon::prelude::*;\nuse std::{\n collections::HashMap,\n fs::File,\n io::{self, Read},\n path::Path,\n str::FromStr,\n sync::OnceLock,\n};\nuse tiktoken_rs::CoreBPE;\n\npub mod config;\npub mod defaults;\npub mod parallel;\npub mod priority;\n\nuse config::YekConfig;\nuse parallel::{process_files_parallel, ProcessedFile};\nuse priority::compute_recentness_boost;\n\n// Add a static BPE encoder for reuse\nstatic TOKENIZER: OnceLock<CoreBPE> = OnceLock::new();\n\nfn get_tokenizer() -> &'static CoreBPE {\n TOKENIZER.get_or_init(|| {\n tiktoken_rs::get_bpe_from_model(\"gpt-3.5-turbo\").expect(\"Failed to load tokenizer\")\n })\n}\n\n/// Check if a file is likely text or binary by reading only a small chunk.\n/// This avoids reading large files fully just to detect their type.\npub fn is_text_file(path: &Path, user_binary_extensions: &[String]) -> io::Result<bool> {\n // If extension is known to be binary, skip quickly\n if let Some(ext) = path.extension().and_then(|e| e.to_str()) {\n if user_binary_extensions.iter().any(|bin_ext| bin_ext == ext) {\n return Ok(false);\n }\n }\n\n // Short partial read to check if it's binary or text\n const INSPECTION_BYTES: usize = 8192;\n let mut file = File::open(path)?;\n let mut buf = vec![0u8; INSPECTION_BYTES];\n let n = file.read(&mut buf)?;\n buf.truncate(n);\n\n Ok(inspect(&buf) != ContentType::BINARY)\n}\n\n/// Main entrypoint for serialization, used by CLI and tests\npub fn serialize_repo(config: &YekConfig) -> Result<(String, Vec<ProcessedFile>)> {\n // Gather commit times from each input path that is a directory\n let combined_commit_times = config\n .input_paths\n .par_iter()\n .filter_map(|path_str| {\n let repo_path = Path::new(path_str);\n if repo_path.is_dir() {\n priority::get_recent_commit_times_git2(\n repo_path,\n config.max_git_depth.try_into().unwrap_or(0),\n )\n } else {\n None\n }\n })\n .flatten()\n .collect::<HashMap<String, u64>>();\n\n // Compute a recentness-based boost\n let recentness_boost =\n compute_recentness_boost(&combined_commit_times, config.git_boost_max.unwrap_or(100));\n\n // Process files in parallel for each input path\n let merged_files = config\n .input_paths\n .par_iter()\n .map(|path_str| {\n let path = Path::new(path_str);\n process_files_parallel(path, config, &recentness_boost)\n })\n .collect::<Result<Vec<Vec<ProcessedFile>>>>()?\n .into_iter()\n .flatten()\n .collect::<Vec<ProcessedFile>>();\n\n let mut files = merged_files;\n\n // Sort final (priority asc, then file_index asc)\n files.par_sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .then_with(|| a.rel_path.cmp(&b.rel_path))\n });\n\n // Build the final output string\n let output_string = concat_files(&files, config)?;\n\n // Only count tokens if debug logging is enabled\n if tracing::Level::DEBUG <= tracing::level_filters::STATIC_MAX_LEVEL {\n tracing::debug!(\"{} tokens generated\", count_tokens(&output_string));\n }\n\n Ok((output_string, files))\n}\n\npub fn concat_files(files: &[ProcessedFile], config: &YekConfig) -> anyhow::Result<String> {\n let mut accumulated = 0_usize;\n let cap = if config.token_mode {\n parse_token_limit(&config.tokens)?\n } else {\n ByteSize::from_str(&config.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?\n .as_u64() as usize\n };\n\n // Sort by priority (asc) and file_index (asc)\n let mut sorted_files: Vec<_> = files.iter().collect();\n sorted_files.sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .then_with(|| a.rel_path.cmp(&b.rel_path))\n });\n\n let mut files_to_include = Vec::new();\n for file in sorted_files {\n let content_size = if config.token_mode {\n // Format the file content with template first, then count tokens\n let formatted = if config.json {\n serde_json::to_string(&serde_json::json!({\n \"filename\": &file.rel_path,\n \"content\": &file.content,\n }))\n .map_err(|e| anyhow!(\"Failed to serialize JSON: {}\", e))?\n } else {\n config\n .output_template\n .replace(\"FILE_PATH\", &file.rel_path)\n .replace(\"FILE_CONTENT\", &file.content)\n };\n count_tokens(&formatted)\n } else {\n file.content.len()\n };\n\n if accumulated + content_size <= cap {\n accumulated += content_size;\n files_to_include.push(file);\n } else {\n break;\n }\n }\n\n if config.json {\n // JSON array of objects\n Ok(serde_json::to_string_pretty(\n &files_to_include\n .iter()\n .map(|f| {\n serde_json::json!({\n \"filename\": &f.rel_path,\n \"content\": &f.content,\n })\n })\n .collect::<Vec<_>>(),\n )?)\n } else {\n // Use the user-defined template\n Ok(files_to_include\n .iter()\n .map(|f| {\n config\n .output_template\n .replace(\"FILE_PATH\", &f.rel_path)\n .replace(\"FILE_CONTENT\", &f.content)\n // Handle both literal \"\\n\" and escaped \"\\\\n\"\n .replace(\"\\\\\\\\\\n\", \"\\n\") // First handle escaped newline\n .replace(\"\\\\\\\\n\", \"\\n\") // Then handle escaped \\n sequence\n })\n .collect::<Vec<_>>()\n .join(\"\\n\"))\n }\n}\n\n/// Parse a token limit string like \"800k\" or \"1000\" into a number\npub fn parse_token_limit(limit: &str) -> anyhow::Result<usize> {\n if limit.to_lowercase().ends_with('k') {\n limit[..limit.len() - 1]\n .trim()\n .parse::<usize>()\n .map(|n| n * 1000)\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n } else {\n limit\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n }\n}\n\n/// Count tokens using tiktoken's GPT-3.5-Turbo tokenizer for accuracy\npub fn count_tokens(text: &str) -> usize {\n get_tokenizer().encode_with_special_tokens(text).len()\n}\n"], ["/yek/src/parallel.rs", "use crate::{config::YekConfig, priority::get_file_priority, Result};\nuse content_inspector::{inspect, ContentType};\nuse glob::glob;\nuse ignore::gitignore::GitignoreBuilder;\nuse path_slash::PathBufExt;\nuse rayon::prelude::*;\nuse std::{\n collections::HashMap,\n fs,\n path::Path,\n sync::{mpsc, Arc},\n};\nuse tracing::debug;\n\n#[derive(Debug, Clone)]\npub struct ProcessedFile {\n pub priority: i32,\n pub file_index: usize,\n pub rel_path: String,\n pub content: String,\n}\n\n/// Process a single file, checking ignore patterns and reading its contents.\nfn process_single_file(\n file_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n let base_dir = file_path.parent().unwrap_or(Path::new(\"\"));\n let rel_path = normalize_path(file_path, base_dir);\n\n // Build the gitignore\n let mut gitignore_builder = GitignoreBuilder::new(base_dir);\n for pattern in &config.ignore_patterns {\n gitignore_builder.add_line(None, pattern)?;\n }\n\n // If there is a .gitignore in this folder, add it last so its \"!\" lines override prior patterns\n let gitignore_file = base_dir.join(\".gitignore\");\n if gitignore_file.exists() {\n gitignore_builder.add(&gitignore_file);\n }\n\n let gitignore = gitignore_builder.build()?;\n if gitignore.matched(file_path, false).is_ignore() {\n debug!(\"Skipping ignored file: {rel_path}\");\n return Ok(Vec::new());\n }\n\n let mut processed_files = Vec::new();\n\n match fs::read(file_path) {\n Ok(content) => {\n if inspect(&content) == ContentType::BINARY {\n debug!(\"Skipping binary file: {rel_path}\");\n } else {\n let rule_priority = get_file_priority(&rel_path, &config.priority_rules);\n let boost = boost_map.get(&rel_path).copied().unwrap_or(0);\n let combined_priority = rule_priority + boost;\n\n processed_files.push(ProcessedFile {\n priority: combined_priority,\n file_index: 0, // For a single file, the index is always 0\n rel_path,\n content: String::from_utf8_lossy(&content).to_string(),\n });\n }\n }\n Err(e) => {\n debug!(\"Failed to read {rel_path}: {e}\");\n }\n }\n\n Ok(processed_files)\n}\n\n/// Walk files in parallel (if a directory is given), skipping ignored paths,\n/// then read each file's contents in a separate thread.\n/// Return the resulting `ProcessedFile` objects.\npub fn process_files_parallel(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n // Expand globs into a list of paths\n let mut expanded_paths = Vec::new();\n let path_str = base_path.to_string_lossy();\n for entry in glob(&path_str)? {\n match entry {\n Ok(path) => expanded_paths.push(path),\n Err(e) => debug!(\"Glob entry error: {:?}\", e),\n }\n }\n\n // If it's a single file (no glob expansion or single file result), process it directly\n if expanded_paths.len() == 1 && expanded_paths[0].is_file() {\n return process_single_file(&expanded_paths[0], config, boost_map);\n }\n\n // Iterate over expanded paths, handling files and directories\n let mut all_processed_files = Vec::new();\n for path in expanded_paths {\n if path.is_file() {\n all_processed_files.extend(process_single_file(&path, config, boost_map)?);\n } else if path.is_dir() {\n // For directories, use the original recursive logic\n all_processed_files.extend(process_files_parallel_internal(&path, config, boost_map)?);\n }\n }\n\n Ok(all_processed_files)\n}\n\n/// Internal function to handle directory recursion (separated for clarity)\nfn process_files_parallel_internal(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n // It's a directory, so walk it\n let mut walk_builder = ignore::WalkBuilder::new(base_path);\n\n // Standard filters + no follow symlinks\n walk_builder\n .follow_links(false)\n .standard_filters(true)\n .require_git(false);\n\n // Build the gitignore\n let mut gitignore_builder = GitignoreBuilder::new(base_path);\n // Add our custom patterns first\n for pattern in &config.ignore_patterns {\n gitignore_builder.add_line(None, pattern)?;\n }\n\n // If there is a .gitignore in this folder, add it last so its \"!\" lines override prior patterns\n let gitignore_file = base_path.join(\".gitignore\");\n if gitignore_file.exists() {\n gitignore_builder.add(&gitignore_file);\n }\n\n let gitignore = Arc::new(gitignore_builder.build()?); // Propagate error here\n\n // This channel will carry (path, rel_path) to the processing thread\n let (processed_files_tx, processed_files_rx) = mpsc::channel::<(std::path::PathBuf, String)>();\n\n // Processing happens on a dedicated thread, to keep from blocking the main walker\n let process_thread = std::thread::spawn({\n let priority_rules = config.priority_rules.clone();\n let boost_map = boost_map.clone();\n move || {\n let mut processed = Vec::new();\n for (path, rel_path) in processed_files_rx {\n // Read entire file\n match fs::read(&path) {\n Ok(content) => {\n // Check if it's binary quickly\n if inspect(&content) == ContentType::BINARY {\n debug!(\"Skipping binary file: {rel_path}\");\n continue;\n }\n // Compute priority\n let rule_priority = get_file_priority(&rel_path, &priority_rules);\n let boost = boost_map.get(&rel_path).copied().unwrap_or(0);\n let combined = rule_priority + boost;\n processed.push(ProcessedFile {\n priority: combined,\n file_index: 0, // assigned later\n rel_path,\n content: String::from_utf8_lossy(&content).to_string(),\n });\n }\n Err(e) => {\n debug!(\"Failed to read {rel_path}: {e}\");\n }\n }\n }\n processed\n }\n });\n\n // Use ignore's parallel walker to skip ignored files\n let base_cloned = base_path.to_owned();\n let walker_tx = processed_files_tx.clone();\n\n // Now build the walker (no .gitignore custom filename)\n walk_builder.build_parallel().run(move || {\n let base_dir = base_cloned.clone();\n let processed_files_tx = walker_tx.clone();\n let gitignore = Arc::clone(&gitignore);\n\n Box::new(move |entry| {\n let entry = match entry {\n Ok(e) => e,\n Err(_) => return ignore::WalkState::Continue,\n };\n // Only process files\n if !entry.file_type().is_some_and(|ft| ft.is_file()) {\n return ignore::WalkState::Continue;\n }\n\n let path = entry.path().to_path_buf();\n let rel_path = normalize_path(&path, &base_dir);\n\n // If gitignore says skip, we do not even read\n if gitignore.matched(&path, false).is_ignore() {\n debug!(\"Skipping ignored file: {rel_path}\");\n return ignore::WalkState::Continue;\n }\n\n // Otherwise we send to processing thread\n processed_files_tx.send((path, rel_path)).ok();\n ignore::WalkState::Continue\n })\n });\n\n // Drop the sender so the thread can end\n drop(processed_files_tx);\n\n // Join the processing thread\n let mut processed_files = process_thread.join().unwrap();\n\n // Now assign file_index within each priority group\n let mut counters = HashMap::new();\n for f in &mut processed_files {\n let ctr = counters.entry(f.priority).or_insert(0);\n f.file_index = *ctr;\n *ctr += 1;\n }\n\n if config.debug {\n debug!(\n \"Processed {} files in parallel for base_path: {}\",\n processed_files.len(),\n base_path.display()\n );\n }\n\n // Sort by priority desc, then file_index\n processed_files.par_sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .reverse()\n .then_with(|| a.file_index.cmp(&b.file_index))\n });\n\n Ok(processed_files)\n}\n\n/// Create a relative, slash-normalized path\npub fn normalize_path(path: &Path, base: &Path) -> String {\n path.strip_prefix(base)\n .unwrap_or(path)\n .to_path_buf()\n .to_slash()\n .unwrap_or_default()\n .to_string()\n}\n"], ["/yek/src/priority.rs", "use git2;\nuse regex;\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, path::Path};\nuse tracing::debug;\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\npub struct PriorityRule {\n pub pattern: String,\n pub score: i32,\n}\n\n/// Determine final priority of a file by scanning the priority list\n/// in descending order of score.\npub fn get_file_priority(path: &str, rules: &[PriorityRule]) -> i32 {\n let mut priority = 0;\n for rule in rules {\n if let Ok(re) = regex::Regex::new(&rule.pattern) {\n if re.is_match(path) {\n priority += rule.score;\n }\n }\n }\n priority\n}\n\n/// Rank-based approach to compute how \"recent\" each file is (0=oldest, 1=newest).\n/// Then scale it to a user-defined or default max boost.\npub fn compute_recentness_boost(\n commit_times: &HashMap<String, u64>,\n max_boost: i32,\n) -> HashMap<String, i32> {\n if commit_times.is_empty() {\n return HashMap::new();\n }\n\n // Sort by ascending commit time => first is oldest\n let mut sorted: Vec<(&String, &u64)> = commit_times.iter().collect();\n sorted.sort_by_key(|(_, t)| **t);\n\n // If there's only one file, or zero, no boosts make sense\n if sorted.len() <= 1 {\n let mut single = HashMap::new();\n for file in commit_times.keys() {\n single.insert(file.clone(), 0);\n }\n return single;\n }\n\n let mut result = HashMap::new();\n let oldest_time = *sorted.first().unwrap().1;\n let newest_time = *sorted.last().unwrap().1;\n let time_range = newest_time.saturating_sub(oldest_time) as f64;\n\n // If all files have the same timestamp, they should all get the same boost\n if time_range == 0.0 {\n for (path, _) in sorted {\n result.insert(path.clone(), 0);\n }\n return result;\n }\n\n // Calculate boost based on time difference from oldest file\n for (path, time) in sorted {\n let time_diff = (*time - oldest_time) as f64;\n let rank = time_diff / time_range; // 0.0..1.0 (older files get lower rank)\n let boost = (rank * max_boost as f64).round() as i32; // Newer files get higher boost\n result.insert(path.clone(), boost);\n }\n result\n}\n\n/// Get the commit time of the most recent change to each file using git2.\n/// Returns a map from file path (relative to the repo root) → last commit Unix time.\n/// If Git or .git folder is missing, returns None instead of erroring.\n/// Only considers up to `max_commits` most recent commits.\npub fn get_recent_commit_times_git2(\n repo_path: &Path,\n max_commits: usize,\n) -> Option<HashMap<String, u64>> {\n // Walk up until you find a .git folder but not higher than the base of the given repo_path\n let mut current_path = repo_path.to_path_buf();\n while current_path.components().count() > 1 {\n if current_path.join(\".git\").exists() {\n break;\n }\n current_path = current_path.parent()?.to_path_buf();\n }\n\n let repo = match git2::Repository::open(&current_path) {\n Ok(repo) => repo,\n Err(_) => {\n debug!(\"Not a Git repository or unable to open: {:?}\", current_path);\n return None;\n }\n };\n\n let mut revwalk = match repo.revwalk() {\n Ok(revwalk) => revwalk,\n Err(_) => {\n debug!(\"Unable to get revwalk for: {:?}\", current_path);\n return None;\n }\n };\n\n if let Err(e) = revwalk.push_head() {\n debug!(\n \"Unable to push HEAD to revwalk: {:?} in {:?}\",\n e, current_path\n );\n return None;\n }\n revwalk.set_sorting(git2::Sort::TIME).ok()?;\n\n let mut commit_times = HashMap::new();\n for oid_result in revwalk.take(max_commits) {\n let oid = match oid_result {\n Ok(oid) => oid,\n Err(e) => {\n debug!(\"Error during revwalk iteration: {:?}\", e);\n continue;\n }\n };\n\n let commit = match repo.find_commit(oid) {\n Ok(commit) => commit,\n Err(e) => {\n debug!(\"Failed to find commit for OID {:?}: {:?}\", oid, e);\n continue;\n }\n };\n let tree = match commit.tree() {\n Ok(tree) => tree,\n Err(e) => {\n debug!(\"Failed to get tree for commit {:?}: {:?}\", oid, e);\n continue;\n }\n };\n\n let time = commit.time().seconds() as u64;\n tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {\n if let Some(name) = entry.name() {\n if entry.kind() == Some(git2::ObjectType::Blob) {\n let full_path = format!(\"{}{}\", root, name);\n commit_times.entry(full_path).or_insert(time);\n }\n }\n git2::TreeWalkResult::Ok\n })\n .ok()?;\n }\n\n Some(commit_times)\n}\n"], ["/yek/src/main.rs", "use anyhow::Result;\nuse bytesize::ByteSize;\nuse rayon::join;\nuse std::path::Path;\nuse tracing::{debug, Level};\nuse tracing_subscriber::fmt;\nuse yek::{config::YekConfig, serialize_repo};\n\nfn main() -> Result<()> {\n // 1) Parse CLI + config files:\n let mut full_config = YekConfig::init_config();\n\n let env_filter = if full_config.debug {\n \"yek=debug,ignore=off\"\n } else {\n \"yek=info,ignore=off\"\n };\n\n // 2) Initialize tracing:\n fmt::Subscriber::builder()\n .with_max_level(if full_config.debug {\n Level::DEBUG\n } else {\n Level::INFO\n })\n .with_target(false)\n .with_thread_ids(false)\n .with_thread_names(false)\n .with_file(false)\n .with_line_number(false)\n .with_level(true)\n .with_env_filter(env_filter)\n .compact()\n .init();\n\n if full_config.debug {\n let config_str = serde_json::to_string_pretty(&full_config)?;\n debug!(\"Configuration:\\n{}\", config_str);\n }\n\n // If streaming => skip checksum + read. Just do single-thread call to serialize_repo.\n // If not streaming => run checksum + repo serialization in parallel.\n if full_config.stream {\n let (output, files) = serialize_repo(&full_config)?;\n // We print actual text to stdout:\n println!(\"{}\", output);\n\n if full_config.debug {\n debug!(\"{} files processed (streaming).\", files.len());\n debug!(\"Output lines: {}\", output.lines().count());\n }\n } else {\n // Not streaming => run repo serialization & checksum in parallel\n let (serialization_res, checksum_res) = join(\n || serialize_repo(&full_config),\n || YekConfig::get_checksum(&full_config.input_paths),\n );\n\n // Handle both results\n let (output_string, files) = serialization_res?;\n let checksum = checksum_res;\n\n // Now set the final output file with the computed checksum\n let extension = if full_config.json { \"json\" } else { \"txt\" };\n let output_dir = full_config.output_dir.as_ref().ok_or_else(|| {\n anyhow::anyhow!(\"Output directory is required when not in streaming mode. This may indicate a configuration validation error.\")\n })?;\n\n let final_path = Path::new(output_dir)\n .join(format!(\"yek-output-{}.{}\", checksum, extension))\n .to_string_lossy()\n .to_string();\n full_config.output_file_full_path = Some(final_path.clone());\n\n // If debug, show stats\n if full_config.debug {\n let size = ByteSize::b(output_string.len() as u64);\n debug!(\"{} files processed\", files.len());\n debug!(\"{} generated\", size);\n debug!(\"{} lines generated\", output_string.lines().count());\n }\n\n // Actually write the final output file.\n // We'll do it right here (instead of inside `serialize_repo`) to ensure we use our new final_path:\n std::fs::write(&final_path, output_string.as_bytes())?;\n\n // Print path to stdout (like original code did)\n println!(\"{}\", final_path);\n }\n\n Ok(())\n}\n"], ["/yek/src/defaults.rs", "/// Known binary file extensions that should be skipped\n#[rustfmt::skip]\npub const BINARY_FILE_EXTENSIONS: &[&str] = &[\n // Executables, Libraries, Core Dumps\n \"exe\", \"dll\", \"so\", \"dylib\", \"ocx\", \"ax\", \"drv\", \"sys\", \"msi\", \"app\", \"ipa\", \"apk\",\n \"bin\", \"out\", \"a\", \"lib\", \"ko\", \"elf\", \"o\", \"nro\", \"core\", \"img\", \"iso\",\n\n // Java / .NET / Archives\n \"class\", \"jar\", \"war\", \"ear\",\n \"resources\", // sometimes included in Java archives\n \"nupkg\", // NuGet package\n \"exe.config\", // sometimes for .NET\n \"dll.config\",\n \n // Archives & Compressed\n \"zip\", \"tar\", \"gz\", \"tgz\", \"bz2\", \"xz\", \"7z\", \"rar\", \"lz4\", \"lz\", \"zst\", \"lzma\",\n \"cab\", \"ar\", \"cpio\", \"rpm\", \"deb\", \"pkg\", \"crx\", \"bin\", \"dmg\", \"hfs\", \"img\",\n \"cso\", // Compressed ISO\n \"bz\", \"tbz\", \"tbz2\", \"tlz\", \"txz\", \"z\", \"Z\", \"apk\", \"xapk\",\n\n // Disk & Container Images\n \"iso\", \"img\", \"dmg\", \"vhd\", \"vhdx\", \"vmdk\", \"vdi\", \"qcow\", \"qcow2\",\n \"mdf\", \"mds\", \"nrg\", \"uif\",\n\n // Documents & Office\n \"pdf\",\n \"doc\", \"docx\", \"dot\", \"dotx\", \"docm\", \"dotm\",\n \"xls\", \"xlsx\", \"xlsm\", \"xlsb\", \"xlt\", \"xltx\", \"xltm\", \"xlc\", \"xlw\",\n \"ppt\", \"pptx\", \"pptm\", \"pps\", \"ppsx\", \"pot\", \"potx\", \"potm\",\n \"pub\", // Microsoft Publisher\n \"vsd\", \"vsdx\", // Visio\n \"accdb\", \"accde\", \"mdb\", \"mde\", // Access\n \"odt\", \"ods\", \"odp\", \"odg\", \"odf\", // OpenDocument\n \"pages\", \"numbers\", \"key\", // Apple iWork\n \"rtf\", // can be binary-like depending on usage\n\n // Spreadsheets, DB, and Misc Data\n \"db\", \"sqlite\", \"db3\", \"s3db\", \"frm\", \"myd\", \"myi\", // MySQL\n \"mdb\", \"bak\", \"nsf\", // Lotus Notes\n \"gdb\", \"fdb\", // Firebird\n \"mdb\", // Access DB\n \"wdb\", // Works DB\n\n // Images\n \"jpg\", \"jpeg\", \"png\", \"gif\", \"bmp\", \"ico\", \"tiff\", \"tif\", \"webp\", \"jfif\", \"jp2\",\n \"psd\", \"psb\", \"xcf\", \"ai\", \"eps\", \"raw\", \"arw\", \"cr2\", \"nef\", \"dng\", \"raf\", \"orf\",\n \"sr2\", \"heic\", \"heif\", \"icns\", \"img\", \"bpg\",\n\n // Audio\n \"mp3\", \"mp2\", \"aac\", \"ac3\", \"wav\", \"ogg\", \"oga\", \"flac\", \"alac\", \"m4a\", \"mp4a\",\n \"wma\", \"ra\", \"ram\", \"ape\", \"opus\", \"amr\", \"awb\",\n\n // Video\n \"mp4\", \"m4v\", \"mov\", \"avi\", \"wmv\", \"mkv\", \"flv\", \"f4v\", \"f4p\", \"f4a\", \"f4b\", \"3gp\",\n \"3g2\", \"mpeg\", \"mpg\", \"mpe\", \"m1v\", \"m2v\", \"ts\", \"mts\", \"m2ts\", \"vob\", \"rm\", \"rmvb\",\n \"asf\", \"ogv\", \"ogm\", \"webm\", \"dv\", \"divx\", \"xvid\",\n\n // Font Files\n \"ttf\", \"otf\", \"woff\", \"woff2\", \"eot\", \"fon\", \"psf\",\n\n // Firmware / BIOS / ROM / Game Data\n \"rom\", \"iso\", \"bin\", \"gba\", \"gbc\", \"nds\", \"n64\", \"z64\", \"v64\", \"gcm\", \"ciso\", \"wbfs\",\n \"pak\", \"wad\", \"dat\", \"sav\", \"rpx\",\n\n // Flash / Vector\n \"swf\", \"fla\", \"svgz\", // .svgz is compressed SVG (binary)\n\n // CAD / 3D\n \"dwg\", \"dxf\", \"dwf\", \"skp\", \"ifc\",\n \"stl\", \"obj\", \"fbx\", \"dae\", \"blend\", \"3ds\", \"ase\", \"gltf\", \"glb\",\n \n // E-Books\n \"epub\", \"mobi\", \"azw\", \"azw3\", \"fb2\", \"lrf\", \"lit\", \"pdb\",\n\n // Other\n \"swp\", \"swo\", // Vim swap files\n \"pch\", // Precompiled header\n \"xex\", \"elf\", // Console executables\n \"dmp\", \"mdmp\", // Memory dump\n \"bkf\", \"bkp\", // Backup\n \"pak\", // Common game data archives\n \"idx\", \"dat\", \"vcd\", // Various binary data\n \"icns\", // macOS icon\n \"hlp\", \"chm\", // Windows help\n \"torrent\", // BitTorrent\n \"mar\", // Mozilla archive\n \"qcow\", \"qcow2\", // QEMU disk\n \"apk\", \"aab\", // Android package/bundle\n \"crx\", // Chrome extension\n \"appx\", // Windows app package\n \"xap\", // Windows Phone app\n];\n\n/// Default sets of ignore patterns (separate from .gitignore)\npub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[\n \"LICENSE\",\n \".git/**\",\n \".next/**\",\n \"node_modules/**\",\n \"vendor/**\",\n \"dist/**\",\n \"build/**\",\n \"out/**\",\n \"target/**\",\n \"bin/**\",\n \"obj/**\",\n \".idea/**\",\n \".vscode/**\",\n \".vs/**\",\n \".settings/**\",\n \".gradle/**\",\n \".mvn/**\",\n \".pytest_cache/**\",\n \"__pycache__/**\",\n \".sass-cache/**\",\n \".vercel/**\",\n \".turbo/**\",\n \"coverage/**\",\n \"test-results/**\",\n \".gitignore\",\n \"pnpm-lock.yaml\",\n \"yek.toml\",\n \"package-lock.json\",\n \"yarn.lock\",\n \"Cargo.lock\",\n \"Gemfile.lock\",\n \"composer.lock\",\n \"mix.lock\",\n \"poetry.lock\",\n \"Pipfile.lock\",\n \"packages.lock.json\",\n \"paket.lock\",\n \"*.pyc\",\n \"*.pyo\",\n \"*.pyd\",\n \"*.class\",\n \"*.o\",\n \"*.obj\",\n \"*.dll\",\n \"*.exe\",\n \"*.so\",\n \"*.dylib\",\n \"*.log\",\n \"*.tmp\",\n \"*.temp\",\n \"*.swp\",\n \"*.swo\",\n \".DS_Store\",\n \"Thumbs.db\",\n \".env*\",\n \"*.bak\",\n \"*~\",\n];\n\npub const DEFAULT_OUTPUT_TEMPLATE: &str = \">>>> FILE_PATH\\nFILE_CONTENT\";\n"]], "task_instance_info": {"created_time": "2025-08-21 01:47:53", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub fn validate (&self) -> Result<()> {}", "code_description": "This code segment functions to: Verify the integrity of configuration parameters by checking template validity, numerical constraints, directory existence, and pattern syntax while enforcing value ranges for priority scoring rules."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n pub fn validate(&self) -> Result<()> {\n // Validate input paths\n if self.input_paths.is_empty() {\n return Err(anyhow!(\"At least one input path is required\"));\n }\n\n // Validate max_size format based on mode\n if self.token_mode {\n // Token mode validation: should be number[K/M]?\n let clean = self.max_size.trim().to_lowercase();\n let (digits, suffix) = clean.split_at(\n clean.find(|c: char| !c.is_ascii_digit())\n .unwrap_or(clean.len()),\n );\n\n if digits.is_empty() {\n return Err(anyhow!(\"Invalid token max_size format '{}'\", self.max_size));\n }\n\n digits.parse::<u64>()\n .map_err(|_| anyhow!(\"Invalid token max_size format '{}'\", self.max_size))?;\n\n match suffix {\n \"\" | \"k\" | \"m\" => (),\n _ => return Err(anyhow!(\"Invalid token suffix '{}' in max_size\", suffix)),\n }\n } else {\n // Byte mode validation\n ByteSize::from_str(&self.max_size)\n .map_err(|e| anyhow!(\"Invalid byte max_size format '{}': {}\", self.max_size, e))?;\n }\n\n // Validate git boost range\n if let Some(boost) = self.git_boost_max {\n if !(0..=1000).contains(&boost) {\n return Err(anyhow!(\"git_boost_max must be between 0 and 1000\"));\n }\n }\n\n // Validate output template placeholders\n if !self.output_template.contains(\"FILE_PATH\") {\n return Err(anyhow!(\"output_template must contain FILE_PATH placeholder\"));\n }\n\n if !self.output_template.contains(\"FILE_CONTENT\") {\n return Err(anyhow!(\"output_template must contain FILE_CONTENT placeholder\"));\n }\n\n Ok(())\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 01-49-10"}, "editdistance_info": {"edit_distance": 19.8135, "calculate_time": "2025-08-21 01:49:10", "true_code_clean": "pub fn validate(&self) -> Result<()> {\n if !self.output_template.contains(\"FILE_PATH\")\n || !self.output_template.contains(\"FILE_CONTENT\")\n {\n return Err(anyhow!(\n \"output_template: must contain FILE_PATH and FILE_CONTENT\"\n ));\n }\n if self.max_size == \"0\" {\n return Err(anyhow!(\"max_size: cannot be 0\"));\n }\n if !self.token_mode {\n ByteSize::from_str(&self.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?;\n } else if self.tokens.to_lowercase().ends_with('k') {\n let val = self.tokens[..self.tokens.len() - 1]\n .trim()\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n } else if !self.tokens.is_empty() {\n let val = self\n .tokens\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n }\n if !self.stream {\n self.ensure_output_dir()?;\n }\n for pattern in &self.ignore_patterns {\n glob::Pattern::new(pattern)\n .map_err(|e| anyhow!(\"ignore_patterns: Invalid pattern '{}': {}\", pattern, e))?;\n }\n for rule in &self.priority_rules {\n if rule.score < 0 || rule.score > 1000 {\n return Err(anyhow!(\n \"priority_rules: Priority score {} must be between 0 and 1000\",\n rule.score\n ));\n }\n glob::Pattern::new(&rule.pattern).map_err(|e| {\n anyhow!(\"priority_rules: Invalid pattern '{}': {}\", rule.pattern, e)\n })?;\n }\n Ok(())\n }", "predict_code_clean": "pub fn validate(&self) -> Result<()> {\n if self.input_paths.is_empty() {\n return Err(anyhow!(\"At least one input path is required\"));\n }\n if self.token_mode {\n let clean = self.max_size.trim().to_lowercase();\n let (digits, suffix) = clean.split_at(\n clean.find(|c: char| !c.is_ascii_digit())\n .unwrap_or(clean.len()),\n );\n if digits.is_empty() {\n return Err(anyhow!(\"Invalid token max_size format '{}'\", self.max_size));\n }\n digits.parse::<u64>()\n .map_err(|_| anyhow!(\"Invalid token max_size format '{}'\", self.max_size))?;\n match suffix {\n \"\" | \"k\" | \"m\" => (),\n _ => return Err(anyhow!(\"Invalid token suffix '{}' in max_size\", suffix)),\n }\n } else {\n ByteSize::from_str(&self.max_size)\n .map_err(|e| anyhow!(\"Invalid byte max_size format '{}': {}\", self.max_size, e))?;\n }\n if let Some(boost) = self.git_boost_max {\n if !(0..=1000).contains(&boost) {\n return Err(anyhow!(\"git_boost_max must be between 0 and 1000\"));\n }\n }\n if !self.output_template.contains(\"FILE_PATH\") {\n return Err(anyhow!(\"output_template must contain FILE_PATH placeholder\"));\n }\n if !self.output_template.contains(\"FILE_CONTENT\") {\n return Err(anyhow!(\"output_template must contain FILE_CONTENT placeholder\"));\n }\n Ok(())\n }"}}
{"repo_name": "yek", "file_name": "/yek/src/lib.rs", "inference_info": {"prefix_code": "use anyhow::anyhow;\nuse anyhow::Result;\nuse bytesize::ByteSize;\nuse content_inspector::{inspect, ContentType};\nuse rayon::prelude::*;\nuse std::{\n collections::HashMap,\n fs::File,\n io::{self, Read},\n path::Path,\n str::FromStr,\n sync::OnceLock,\n};\nuse tiktoken_rs::CoreBPE;\n\npub mod config;\npub mod defaults;\npub mod parallel;\npub mod priority;\n\nuse config::YekConfig;\nuse parallel::{process_files_parallel, ProcessedFile};\nuse priority::compute_recentness_boost;\n\n// Add a static BPE encoder for reuse\nstatic TOKENIZER: OnceLock<CoreBPE> = OnceLock::new();\n\nfn get_tokenizer() -> &'static CoreBPE {\n TOKENIZER.get_or_init(|| {\n tiktoken_rs::get_bpe_from_model(\"gpt-3.5-turbo\").expect(\"Failed to load tokenizer\")\n })\n}\n\n/// Check if a file is likely text or binary by reading only a small chunk.\n/// This avoids reading large files fully just to detect their type.\npub fn is_text_file(path: &Path, user_binary_extensions: &[String]) -> io::Result<bool> {\n // If extension is known to be binary, skip quickly\n if let Some(ext) = path.extension().and_then(|e| e.to_str()) {\n if user_binary_extensions.iter().any(|bin_ext| bin_ext == ext) {\n return Ok(false);\n }\n }\n\n // Short partial read to check if it's binary or text\n const INSPECTION_BYTES: usize = 8192;\n let mut file = File::open(path)?;\n let mut buf = vec![0u8; INSPECTION_BYTES];\n let n = file.read(&mut buf)?;\n buf.truncate(n);\n\n Ok(inspect(&buf) != ContentType::BINARY)\n}\n\n/// Main entrypoint for serialization, used by CLI and tests\npub fn serialize_repo(config: &YekConfig) -> Result<(String, Vec<ProcessedFile>)> {\n // Gather commit times from each input path that is a directory\n let combined_commit_times = config\n .input_paths\n .par_iter()\n .filter_map(|path_str| {\n let repo_path = Path::new(path_str);\n if repo_path.is_dir() {\n priority::get_recent_commit_times_git2(\n repo_path,\n config.max_git_depth.try_into().unwrap_or(0),\n )\n } else {\n None\n }\n })\n .flatten()\n .collect::<HashMap<String, u64>>();\n\n // Compute a recentness-based boost\n let recentness_boost =\n compute_recentness_boost(&combined_commit_times, config.git_boost_max.unwrap_or(100));\n\n // Process files in parallel for each input path\n let merged_files = config\n .input_paths\n .par_iter()\n .map(|path_str| {\n let path = Path::new(path_str);\n process_files_parallel(path, config, &recentness_boost)\n })\n .collect::<Result<Vec<Vec<ProcessedFile>>>>()?\n .into_iter()\n .flatten()\n .collect::<Vec<ProcessedFile>>();\n\n let mut files = merged_files;\n\n // Sort final (priority asc, then file_index asc)\n files.par_sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .then_with(|| a.rel_path.cmp(&b.rel_path))\n });\n\n // Build the final output string\n let output_string = concat_files(&files, config)?;\n\n // Only count tokens if debug logging is enabled\n if tracing::Level::DEBUG <= tracing::level_filters::STATIC_MAX_LEVEL {\n tracing::debug!(\"{} tokens generated\", count_tokens(&output_string));\n }\n\n Ok((output_string, files))\n}\n\npub fn concat_files(files: &[ProcessedFile], config: &YekConfig) -> anyhow::Result<String> {\n let mut accumulated = 0_usize;\n let cap = if config.token_mode {\n parse_token_limit(&config.tokens)?\n } else {\n ByteSize::from_str(&config.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?\n .as_u64() as usize\n };\n\n // Sort by priority (asc) and file_index (asc)\n let mut sorted_files: Vec<_> = files.iter().collect();\n sorted_files.sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .then_with(|| a.rel_path.cmp(&b.rel_path))\n });\n\n let mut files_to_include = Vec::new();\n for file in sorted_files {\n let content_size = if config.token_mode {\n // Format the file content with template first, then count tokens\n let formatted = if config.json {\n serde_json::to_string(&serde_json::json!({\n \"filename\": &file.rel_path,\n \"content\": &file.content,\n }))\n .map_err(|e| anyhow!(\"Failed to serialize JSON: {}\", e))?\n } else {\n config\n .output_template\n .replace(\"FILE_PATH\", &file.rel_path)\n .replace(\"FILE_CONTENT\", &file.content)\n };\n count_tokens(&formatted)\n } else {\n file.content.len()\n };\n\n if accumulated + content_size <= cap {\n accumulated += content_size;\n files_to_include.push(file);\n } else {\n break;\n }\n }\n\n if config.json {\n // JSON array of objects\n Ok(serde_json::to_string_pretty(\n &files_to_include\n .iter()\n .map(|f| {\n serde_json::json!({\n \"filename\": &f.rel_path,\n \"content\": &f.content,\n })\n })\n .collect::<Vec<_>>(),\n )?)\n } else {\n // Use the user-defined template\n Ok(files_to_include\n .iter()\n .map(|f| {\n config\n .output_template\n .replace(\"FILE_PATH\", &f.rel_path)\n .replace(\"FILE_CONTENT\", &f.content)\n // Handle both literal \"\\n\" and escaped \"\\\\n\"\n .replace(\"\\\\\\\\\\n\", \"\\n\") // First handle escaped newline\n .replace(\"\\\\\\\\n\", \"\\n\") // Then handle escaped \\n sequence\n })\n .collect::<Vec<_>>()\n .join(\"\\n\"))\n }\n}\n\n/// Parse a token limit string like \"800k\" or \"1000\" into a number\n", "suffix_code": "\n\n/// Count tokens using tiktoken's GPT-3.5-Turbo tokenizer for accuracy\npub fn count_tokens(text: &str) -> usize {\n get_tokenizer().encode_with_special_tokens(text).len()\n}\n", "middle_code": "pub fn parse_token_limit(limit: &str) -> anyhow::Result<usize> {\n if limit.to_lowercase().ends_with('k') {\n limit[..limit.len() - 1]\n .trim()\n .parse::<usize>()\n .map(|n| n * 1000)\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n } else {\n limit\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/yek/src/config.rs", "use anyhow::{anyhow, Result};\nuse bytesize::ByteSize;\nuse clap_config_file::ClapConfigFile;\nuse sha2::{Digest, Sha256};\nuse std::io::IsTerminal;\nuse std::{fs, path::Path, str::FromStr, time::UNIX_EPOCH};\n\nuse crate::{\n defaults::{BINARY_FILE_EXTENSIONS, DEFAULT_IGNORE_PATTERNS, DEFAULT_OUTPUT_TEMPLATE},\n priority::PriorityRule,\n};\n\n#[derive(Clone, Debug, Default, clap::ValueEnum, serde::Serialize, serde::Deserialize)]\npub enum ConfigFormat {\n #[default]\n Toml,\n Yaml,\n Json,\n}\n\n#[derive(ClapConfigFile, Clone)]\n#[config_file_name = \"yek\"]\n#[config_file_formats = \"toml,yaml,json\"]\npub struct YekConfig {\n /// Input files and/or directories to process\n #[config_arg(positional)]\n pub input_paths: Vec<String>,\n\n /// Print version of yek\n #[config_arg(long = \"version\", short = 'V')]\n pub version: bool,\n\n /// Max size per chunk. e.g. \"10MB\" or \"128K\" or when using token counting mode, \"100\" or \"128K\"\n #[config_arg(default_value = \"10MB\")]\n pub max_size: String,\n\n /// Use token mode instead of byte mode\n #[config_arg()]\n pub tokens: String,\n\n /// Enable JSON output\n #[config_arg()]\n pub json: bool,\n\n /// Enable debug output\n #[config_arg()]\n pub debug: bool,\n\n /// Output directory. If none is provided & stdout is a TTY, we pick a temp dir\n #[config_arg()]\n pub output_dir: Option<String>,\n\n /// Output template. Defaults to \">>>> FILE_PATH\\nFILE_CONTENT\"\n #[config_arg(default_value = \">>>> FILE_PATH\\nFILE_CONTENT\")]\n pub output_template: String,\n\n /// Ignore patterns\n #[config_arg(long = \"ignore-patterns\", multi_value_behavior = \"extend\")]\n pub ignore_patterns: Vec<String>,\n\n /// Unignore patterns. Yek has some built-in ignore patterns, but you can override them here.\n #[config_arg(long = \"unignore-patterns\", multi_value_behavior = \"extend\")]\n pub unignore_patterns: Vec<String>,\n\n /// Priority rules\n #[config_arg(accept_from = \"config_only\")]\n pub priority_rules: Vec<PriorityRule>,\n\n /// Binary file extensions to ignore\n #[config_arg(accept_from = \"config_only\", default_value = BINARY_FILE_EXTENSIONS)]\n pub binary_extensions: Vec<String>,\n\n /// Maximum additional boost from Git commit times (0..1000)\n #[config_arg(accept_from = \"config_only\")]\n pub git_boost_max: Option<i32>,\n\n /// True if we should stream output to stdout (computed)\n pub stream: bool,\n\n /// True if we should count tokens, not bytes (computed)\n pub token_mode: bool,\n\n /// Final resolved output file path (only used if not streaming)\n pub output_file_full_path: Option<String>,\n\n /// Maximum depth to search for Git commit times\n #[config_arg(accept_from = \"config_only\", default_value = \"100\")]\n pub max_git_depth: i32,\n}\n\n/// Provide defaults so tests or other callers can create a baseline YekConfig easily.\nimpl Default for YekConfig {\n fn default() -> Self {\n Self {\n input_paths: Vec::new(),\n version: false,\n max_size: \"10MB\".to_string(),\n tokens: String::new(),\n json: false,\n debug: false,\n output_dir: None,\n output_template: DEFAULT_OUTPUT_TEMPLATE.to_string(),\n ignore_patterns: Vec::new(),\n unignore_patterns: Vec::new(),\n priority_rules: Vec::new(),\n binary_extensions: BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect(),\n git_boost_max: Some(100),\n\n // computed fields\n stream: false,\n token_mode: false,\n output_file_full_path: None,\n max_git_depth: 100,\n }\n }\n}\n\nimpl YekConfig {\n pub fn extend_config_with_defaults(input_paths: Vec<String>, output_dir: String) -> Self {\n YekConfig {\n input_paths,\n output_dir: Some(output_dir),\n ..Default::default()\n }\n }\n}\n\nimpl YekConfig {\n /// Ensure output directory exists and is valid. Returns the resolved output directory path.\n pub fn ensure_output_dir(&self) -> Result<String> {\n if self.stream {\n return Ok(String::new());\n }\n\n let output_dir = if let Some(dir) = &self.output_dir {\n dir.clone()\n } else {\n let temp_dir = std::env::temp_dir().join(\"yek-output\");\n temp_dir.to_string_lossy().to_string()\n };\n\n let path = Path::new(&output_dir);\n if path.exists() && !path.is_dir() {\n return Err(anyhow!(\n \"output_dir: '{}' exists but is not a directory\",\n output_dir\n ));\n }\n\n std::fs::create_dir_all(path)\n .map_err(|e| anyhow!(\"output_dir: cannot create '{}': {}\", output_dir, e))?;\n\n Ok(output_dir)\n }\n\n /// Parse from CLI + config file, fill in computed fields, and validate.\n pub fn init_config() -> Self {\n // 1) parse from CLI and optional config file:\n let mut cfg = YekConfig::parse();\n\n // Handle version flag\n if cfg.version {\n println!(\"{}\", env!(\"CARGO_PKG_VERSION\"));\n std::process::exit(0);\n }\n\n // 2) compute derived fields:\n cfg.token_mode = !cfg.tokens.is_empty();\n let force_tty = std::env::var(\"FORCE_TTY\").is_ok();\n\n cfg.stream = !std::io::stdout().is_terminal() && !force_tty;\n\n // default input dirs to current dir if none:\n if cfg.input_paths.is_empty() {\n cfg.input_paths.push(\".\".to_string());\n }\n\n // Extend binary extensions with the built-in list:\n let mut merged_bins = BINARY_FILE_EXTENSIONS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n merged_bins.append(&mut cfg.binary_extensions);\n cfg.binary_extensions = merged_bins\n .into_iter()\n .collect::<std::collections::HashSet<_>>()\n .into_iter()\n .collect();\n\n // Always start with default ignore patterns, then add user's:\n let mut ignore = DEFAULT_IGNORE_PATTERNS\n .iter()\n .map(|s| s.to_string())\n .collect::<Vec<_>>();\n ignore.extend(cfg.ignore_patterns);\n cfg.ignore_patterns = ignore;\n\n // Apply unignore patterns (turn them into negative globs \"!…\")\n cfg.ignore_patterns\n .extend(cfg.unignore_patterns.iter().map(|pat| format!(\"!{}\", pat)));\n\n // Handle output directory setup\n if !cfg.stream {\n match cfg.ensure_output_dir() {\n Ok(dir) => cfg.output_dir = Some(dir),\n Err(e) => {\n eprintln!(\"Warning: Failed to create output directory: {}\", e);\n cfg.stream = true; // Fall back to streaming mode\n }\n }\n }\n\n // By default, we start with no final output_file_full_path:\n cfg.output_file_full_path = None;\n\n // 3) Validate\n if let Err(e) = cfg.validate() {\n eprintln!(\"Error: {}\", e);\n std::process::exit(1);\n }\n\n cfg\n }\n\n /// Compute a quick checksum for the input paths (files and directories).\n /// For directories, it uses the top-level listing. For files, it uses the file metadata.\n pub fn get_checksum(input_paths: &[String]) -> String {\n let mut hasher = Sha256::new();\n for path_str in input_paths {\n let base_path = Path::new(path_str);\n if !base_path.exists() {\n continue;\n }\n\n // If it's a file, hash the file metadata directly\n if base_path.is_file() {\n if let Ok(meta) = fs::metadata(base_path) {\n hasher.update(path_str.as_bytes());\n hasher.update(meta.len().to_le_bytes());\n\n if let Ok(mod_time) = meta.modified() {\n if let Ok(dur) = mod_time.duration_since(UNIX_EPOCH) {\n hasher.update(dur.as_secs().to_le_bytes());\n hasher.update(dur.subsec_nanos().to_le_bytes());\n }\n }\n }\n continue;\n }\n\n // If it's a directory, hash its contents\n let entries = match fs::read_dir(base_path) {\n Ok(iter) => iter.filter_map(|e| e.ok()).collect::<Vec<_>>(),\n Err(_) => continue,\n };\n\n // Sort deterministically by path name\n let mut sorted = entries;\n sorted.sort_by_key(|a| a.path());\n\n for entry in sorted {\n let p = entry.path();\n if let Ok(meta) = fs::metadata(&p) {\n let path_str = p.to_string_lossy();\n hasher.update(path_str.as_bytes());\n hasher.update(meta.len().to_le_bytes());\n\n if let Ok(mod_time) = meta.modified() {\n if let Ok(dur) = mod_time.duration_since(UNIX_EPOCH) {\n hasher.update(dur.as_secs().to_le_bytes());\n hasher.update(dur.subsec_nanos().to_le_bytes());\n }\n }\n }\n }\n }\n let result = hasher.finalize();\n // Convert the 32-byte result to hex, but only keep the first 8 characters\n let hex = format!(\"{:x}\", result);\n hex[..8].to_owned()\n }\n\n /// Validate the final config.\n pub fn validate(&self) -> Result<()> {\n if !self.output_template.contains(\"FILE_PATH\")\n || !self.output_template.contains(\"FILE_CONTENT\")\n {\n return Err(anyhow!(\n \"output_template: must contain FILE_PATH and FILE_CONTENT\"\n ));\n }\n\n if self.max_size == \"0\" {\n return Err(anyhow!(\"max_size: cannot be 0\"));\n }\n\n if !self.token_mode {\n ByteSize::from_str(&self.max_size)\n .map_err(|e| anyhow!(\"max_size: Invalid size format: {}\", e))?;\n } else if self.tokens.to_lowercase().ends_with('k') {\n let val = self.tokens[..self.tokens.len() - 1]\n .trim()\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n } else if !self.tokens.is_empty() {\n // parse as integer\n let val = self\n .tokens\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))?;\n if val == 0 {\n return Err(anyhow!(\"tokens: cannot be 0\"));\n }\n }\n\n // If not streaming, validate output directory\n if !self.stream {\n self.ensure_output_dir()?;\n }\n\n // Validate ignore patterns\n for pattern in &self.ignore_patterns {\n glob::Pattern::new(pattern)\n .map_err(|e| anyhow!(\"ignore_patterns: Invalid pattern '{}': {}\", pattern, e))?;\n }\n\n // Validate priority rules\n for rule in &self.priority_rules {\n if rule.score < 0 || rule.score > 1000 {\n return Err(anyhow!(\n \"priority_rules: Priority score {} must be between 0 and 1000\",\n rule.score\n ));\n }\n glob::Pattern::new(&rule.pattern).map_err(|e| {\n anyhow!(\"priority_rules: Invalid pattern '{}': {}\", rule.pattern, e)\n })?;\n }\n\n Ok(())\n }\n}\n"], ["/yek/src/parallel.rs", "use crate::{config::YekConfig, priority::get_file_priority, Result};\nuse content_inspector::{inspect, ContentType};\nuse glob::glob;\nuse ignore::gitignore::GitignoreBuilder;\nuse path_slash::PathBufExt;\nuse rayon::prelude::*;\nuse std::{\n collections::HashMap,\n fs,\n path::Path,\n sync::{mpsc, Arc},\n};\nuse tracing::debug;\n\n#[derive(Debug, Clone)]\npub struct ProcessedFile {\n pub priority: i32,\n pub file_index: usize,\n pub rel_path: String,\n pub content: String,\n}\n\n/// Process a single file, checking ignore patterns and reading its contents.\nfn process_single_file(\n file_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n let base_dir = file_path.parent().unwrap_or(Path::new(\"\"));\n let rel_path = normalize_path(file_path, base_dir);\n\n // Build the gitignore\n let mut gitignore_builder = GitignoreBuilder::new(base_dir);\n for pattern in &config.ignore_patterns {\n gitignore_builder.add_line(None, pattern)?;\n }\n\n // If there is a .gitignore in this folder, add it last so its \"!\" lines override prior patterns\n let gitignore_file = base_dir.join(\".gitignore\");\n if gitignore_file.exists() {\n gitignore_builder.add(&gitignore_file);\n }\n\n let gitignore = gitignore_builder.build()?;\n if gitignore.matched(file_path, false).is_ignore() {\n debug!(\"Skipping ignored file: {rel_path}\");\n return Ok(Vec::new());\n }\n\n let mut processed_files = Vec::new();\n\n match fs::read(file_path) {\n Ok(content) => {\n if inspect(&content) == ContentType::BINARY {\n debug!(\"Skipping binary file: {rel_path}\");\n } else {\n let rule_priority = get_file_priority(&rel_path, &config.priority_rules);\n let boost = boost_map.get(&rel_path).copied().unwrap_or(0);\n let combined_priority = rule_priority + boost;\n\n processed_files.push(ProcessedFile {\n priority: combined_priority,\n file_index: 0, // For a single file, the index is always 0\n rel_path,\n content: String::from_utf8_lossy(&content).to_string(),\n });\n }\n }\n Err(e) => {\n debug!(\"Failed to read {rel_path}: {e}\");\n }\n }\n\n Ok(processed_files)\n}\n\n/// Walk files in parallel (if a directory is given), skipping ignored paths,\n/// then read each file's contents in a separate thread.\n/// Return the resulting `ProcessedFile` objects.\npub fn process_files_parallel(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n // Expand globs into a list of paths\n let mut expanded_paths = Vec::new();\n let path_str = base_path.to_string_lossy();\n for entry in glob(&path_str)? {\n match entry {\n Ok(path) => expanded_paths.push(path),\n Err(e) => debug!(\"Glob entry error: {:?}\", e),\n }\n }\n\n // If it's a single file (no glob expansion or single file result), process it directly\n if expanded_paths.len() == 1 && expanded_paths[0].is_file() {\n return process_single_file(&expanded_paths[0], config, boost_map);\n }\n\n // Iterate over expanded paths, handling files and directories\n let mut all_processed_files = Vec::new();\n for path in expanded_paths {\n if path.is_file() {\n all_processed_files.extend(process_single_file(&path, config, boost_map)?);\n } else if path.is_dir() {\n // For directories, use the original recursive logic\n all_processed_files.extend(process_files_parallel_internal(&path, config, boost_map)?);\n }\n }\n\n Ok(all_processed_files)\n}\n\n/// Internal function to handle directory recursion (separated for clarity)\nfn process_files_parallel_internal(\n base_path: &Path,\n config: &YekConfig,\n boost_map: &HashMap<String, i32>,\n) -> Result<Vec<ProcessedFile>> {\n // It's a directory, so walk it\n let mut walk_builder = ignore::WalkBuilder::new(base_path);\n\n // Standard filters + no follow symlinks\n walk_builder\n .follow_links(false)\n .standard_filters(true)\n .require_git(false);\n\n // Build the gitignore\n let mut gitignore_builder = GitignoreBuilder::new(base_path);\n // Add our custom patterns first\n for pattern in &config.ignore_patterns {\n gitignore_builder.add_line(None, pattern)?;\n }\n\n // If there is a .gitignore in this folder, add it last so its \"!\" lines override prior patterns\n let gitignore_file = base_path.join(\".gitignore\");\n if gitignore_file.exists() {\n gitignore_builder.add(&gitignore_file);\n }\n\n let gitignore = Arc::new(gitignore_builder.build()?); // Propagate error here\n\n // This channel will carry (path, rel_path) to the processing thread\n let (processed_files_tx, processed_files_rx) = mpsc::channel::<(std::path::PathBuf, String)>();\n\n // Processing happens on a dedicated thread, to keep from blocking the main walker\n let process_thread = std::thread::spawn({\n let priority_rules = config.priority_rules.clone();\n let boost_map = boost_map.clone();\n move || {\n let mut processed = Vec::new();\n for (path, rel_path) in processed_files_rx {\n // Read entire file\n match fs::read(&path) {\n Ok(content) => {\n // Check if it's binary quickly\n if inspect(&content) == ContentType::BINARY {\n debug!(\"Skipping binary file: {rel_path}\");\n continue;\n }\n // Compute priority\n let rule_priority = get_file_priority(&rel_path, &priority_rules);\n let boost = boost_map.get(&rel_path).copied().unwrap_or(0);\n let combined = rule_priority + boost;\n processed.push(ProcessedFile {\n priority: combined,\n file_index: 0, // assigned later\n rel_path,\n content: String::from_utf8_lossy(&content).to_string(),\n });\n }\n Err(e) => {\n debug!(\"Failed to read {rel_path}: {e}\");\n }\n }\n }\n processed\n }\n });\n\n // Use ignore's parallel walker to skip ignored files\n let base_cloned = base_path.to_owned();\n let walker_tx = processed_files_tx.clone();\n\n // Now build the walker (no .gitignore custom filename)\n walk_builder.build_parallel().run(move || {\n let base_dir = base_cloned.clone();\n let processed_files_tx = walker_tx.clone();\n let gitignore = Arc::clone(&gitignore);\n\n Box::new(move |entry| {\n let entry = match entry {\n Ok(e) => e,\n Err(_) => return ignore::WalkState::Continue,\n };\n // Only process files\n if !entry.file_type().is_some_and(|ft| ft.is_file()) {\n return ignore::WalkState::Continue;\n }\n\n let path = entry.path().to_path_buf();\n let rel_path = normalize_path(&path, &base_dir);\n\n // If gitignore says skip, we do not even read\n if gitignore.matched(&path, false).is_ignore() {\n debug!(\"Skipping ignored file: {rel_path}\");\n return ignore::WalkState::Continue;\n }\n\n // Otherwise we send to processing thread\n processed_files_tx.send((path, rel_path)).ok();\n ignore::WalkState::Continue\n })\n });\n\n // Drop the sender so the thread can end\n drop(processed_files_tx);\n\n // Join the processing thread\n let mut processed_files = process_thread.join().unwrap();\n\n // Now assign file_index within each priority group\n let mut counters = HashMap::new();\n for f in &mut processed_files {\n let ctr = counters.entry(f.priority).or_insert(0);\n f.file_index = *ctr;\n *ctr += 1;\n }\n\n if config.debug {\n debug!(\n \"Processed {} files in parallel for base_path: {}\",\n processed_files.len(),\n base_path.display()\n );\n }\n\n // Sort by priority desc, then file_index\n processed_files.par_sort_by(|a, b| {\n a.priority\n .cmp(&b.priority)\n .reverse()\n .then_with(|| a.file_index.cmp(&b.file_index))\n });\n\n Ok(processed_files)\n}\n\n/// Create a relative, slash-normalized path\npub fn normalize_path(path: &Path, base: &Path) -> String {\n path.strip_prefix(base)\n .unwrap_or(path)\n .to_path_buf()\n .to_slash()\n .unwrap_or_default()\n .to_string()\n}\n"], ["/yek/src/priority.rs", "use git2;\nuse regex;\nuse serde::{Deserialize, Serialize};\nuse std::{collections::HashMap, path::Path};\nuse tracing::debug;\n\n#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\npub struct PriorityRule {\n pub pattern: String,\n pub score: i32,\n}\n\n/// Determine final priority of a file by scanning the priority list\n/// in descending order of score.\npub fn get_file_priority(path: &str, rules: &[PriorityRule]) -> i32 {\n let mut priority = 0;\n for rule in rules {\n if let Ok(re) = regex::Regex::new(&rule.pattern) {\n if re.is_match(path) {\n priority += rule.score;\n }\n }\n }\n priority\n}\n\n/// Rank-based approach to compute how \"recent\" each file is (0=oldest, 1=newest).\n/// Then scale it to a user-defined or default max boost.\npub fn compute_recentness_boost(\n commit_times: &HashMap<String, u64>,\n max_boost: i32,\n) -> HashMap<String, i32> {\n if commit_times.is_empty() {\n return HashMap::new();\n }\n\n // Sort by ascending commit time => first is oldest\n let mut sorted: Vec<(&String, &u64)> = commit_times.iter().collect();\n sorted.sort_by_key(|(_, t)| **t);\n\n // If there's only one file, or zero, no boosts make sense\n if sorted.len() <= 1 {\n let mut single = HashMap::new();\n for file in commit_times.keys() {\n single.insert(file.clone(), 0);\n }\n return single;\n }\n\n let mut result = HashMap::new();\n let oldest_time = *sorted.first().unwrap().1;\n let newest_time = *sorted.last().unwrap().1;\n let time_range = newest_time.saturating_sub(oldest_time) as f64;\n\n // If all files have the same timestamp, they should all get the same boost\n if time_range == 0.0 {\n for (path, _) in sorted {\n result.insert(path.clone(), 0);\n }\n return result;\n }\n\n // Calculate boost based on time difference from oldest file\n for (path, time) in sorted {\n let time_diff = (*time - oldest_time) as f64;\n let rank = time_diff / time_range; // 0.0..1.0 (older files get lower rank)\n let boost = (rank * max_boost as f64).round() as i32; // Newer files get higher boost\n result.insert(path.clone(), boost);\n }\n result\n}\n\n/// Get the commit time of the most recent change to each file using git2.\n/// Returns a map from file path (relative to the repo root) → last commit Unix time.\n/// If Git or .git folder is missing, returns None instead of erroring.\n/// Only considers up to `max_commits` most recent commits.\npub fn get_recent_commit_times_git2(\n repo_path: &Path,\n max_commits: usize,\n) -> Option<HashMap<String, u64>> {\n // Walk up until you find a .git folder but not higher than the base of the given repo_path\n let mut current_path = repo_path.to_path_buf();\n while current_path.components().count() > 1 {\n if current_path.join(\".git\").exists() {\n break;\n }\n current_path = current_path.parent()?.to_path_buf();\n }\n\n let repo = match git2::Repository::open(&current_path) {\n Ok(repo) => repo,\n Err(_) => {\n debug!(\"Not a Git repository or unable to open: {:?}\", current_path);\n return None;\n }\n };\n\n let mut revwalk = match repo.revwalk() {\n Ok(revwalk) => revwalk,\n Err(_) => {\n debug!(\"Unable to get revwalk for: {:?}\", current_path);\n return None;\n }\n };\n\n if let Err(e) = revwalk.push_head() {\n debug!(\n \"Unable to push HEAD to revwalk: {:?} in {:?}\",\n e, current_path\n );\n return None;\n }\n revwalk.set_sorting(git2::Sort::TIME).ok()?;\n\n let mut commit_times = HashMap::new();\n for oid_result in revwalk.take(max_commits) {\n let oid = match oid_result {\n Ok(oid) => oid,\n Err(e) => {\n debug!(\"Error during revwalk iteration: {:?}\", e);\n continue;\n }\n };\n\n let commit = match repo.find_commit(oid) {\n Ok(commit) => commit,\n Err(e) => {\n debug!(\"Failed to find commit for OID {:?}: {:?}\", oid, e);\n continue;\n }\n };\n let tree = match commit.tree() {\n Ok(tree) => tree,\n Err(e) => {\n debug!(\"Failed to get tree for commit {:?}: {:?}\", oid, e);\n continue;\n }\n };\n\n let time = commit.time().seconds() as u64;\n tree.walk(git2::TreeWalkMode::PreOrder, |root, entry| {\n if let Some(name) = entry.name() {\n if entry.kind() == Some(git2::ObjectType::Blob) {\n let full_path = format!(\"{}{}\", root, name);\n commit_times.entry(full_path).or_insert(time);\n }\n }\n git2::TreeWalkResult::Ok\n })\n .ok()?;\n }\n\n Some(commit_times)\n}\n"], ["/yek/src/main.rs", "use anyhow::Result;\nuse bytesize::ByteSize;\nuse rayon::join;\nuse std::path::Path;\nuse tracing::{debug, Level};\nuse tracing_subscriber::fmt;\nuse yek::{config::YekConfig, serialize_repo};\n\nfn main() -> Result<()> {\n // 1) Parse CLI + config files:\n let mut full_config = YekConfig::init_config();\n\n let env_filter = if full_config.debug {\n \"yek=debug,ignore=off\"\n } else {\n \"yek=info,ignore=off\"\n };\n\n // 2) Initialize tracing:\n fmt::Subscriber::builder()\n .with_max_level(if full_config.debug {\n Level::DEBUG\n } else {\n Level::INFO\n })\n .with_target(false)\n .with_thread_ids(false)\n .with_thread_names(false)\n .with_file(false)\n .with_line_number(false)\n .with_level(true)\n .with_env_filter(env_filter)\n .compact()\n .init();\n\n if full_config.debug {\n let config_str = serde_json::to_string_pretty(&full_config)?;\n debug!(\"Configuration:\\n{}\", config_str);\n }\n\n // If streaming => skip checksum + read. Just do single-thread call to serialize_repo.\n // If not streaming => run checksum + repo serialization in parallel.\n if full_config.stream {\n let (output, files) = serialize_repo(&full_config)?;\n // We print actual text to stdout:\n println!(\"{}\", output);\n\n if full_config.debug {\n debug!(\"{} files processed (streaming).\", files.len());\n debug!(\"Output lines: {}\", output.lines().count());\n }\n } else {\n // Not streaming => run repo serialization & checksum in parallel\n let (serialization_res, checksum_res) = join(\n || serialize_repo(&full_config),\n || YekConfig::get_checksum(&full_config.input_paths),\n );\n\n // Handle both results\n let (output_string, files) = serialization_res?;\n let checksum = checksum_res;\n\n // Now set the final output file with the computed checksum\n let extension = if full_config.json { \"json\" } else { \"txt\" };\n let output_dir = full_config.output_dir.as_ref().ok_or_else(|| {\n anyhow::anyhow!(\"Output directory is required when not in streaming mode. This may indicate a configuration validation error.\")\n })?;\n\n let final_path = Path::new(output_dir)\n .join(format!(\"yek-output-{}.{}\", checksum, extension))\n .to_string_lossy()\n .to_string();\n full_config.output_file_full_path = Some(final_path.clone());\n\n // If debug, show stats\n if full_config.debug {\n let size = ByteSize::b(output_string.len() as u64);\n debug!(\"{} files processed\", files.len());\n debug!(\"{} generated\", size);\n debug!(\"{} lines generated\", output_string.lines().count());\n }\n\n // Actually write the final output file.\n // We'll do it right here (instead of inside `serialize_repo`) to ensure we use our new final_path:\n std::fs::write(&final_path, output_string.as_bytes())?;\n\n // Print path to stdout (like original code did)\n println!(\"{}\", final_path);\n }\n\n Ok(())\n}\n"], ["/yek/src/defaults.rs", "/// Known binary file extensions that should be skipped\n#[rustfmt::skip]\npub const BINARY_FILE_EXTENSIONS: &[&str] = &[\n // Executables, Libraries, Core Dumps\n \"exe\", \"dll\", \"so\", \"dylib\", \"ocx\", \"ax\", \"drv\", \"sys\", \"msi\", \"app\", \"ipa\", \"apk\",\n \"bin\", \"out\", \"a\", \"lib\", \"ko\", \"elf\", \"o\", \"nro\", \"core\", \"img\", \"iso\",\n\n // Java / .NET / Archives\n \"class\", \"jar\", \"war\", \"ear\",\n \"resources\", // sometimes included in Java archives\n \"nupkg\", // NuGet package\n \"exe.config\", // sometimes for .NET\n \"dll.config\",\n \n // Archives & Compressed\n \"zip\", \"tar\", \"gz\", \"tgz\", \"bz2\", \"xz\", \"7z\", \"rar\", \"lz4\", \"lz\", \"zst\", \"lzma\",\n \"cab\", \"ar\", \"cpio\", \"rpm\", \"deb\", \"pkg\", \"crx\", \"bin\", \"dmg\", \"hfs\", \"img\",\n \"cso\", // Compressed ISO\n \"bz\", \"tbz\", \"tbz2\", \"tlz\", \"txz\", \"z\", \"Z\", \"apk\", \"xapk\",\n\n // Disk & Container Images\n \"iso\", \"img\", \"dmg\", \"vhd\", \"vhdx\", \"vmdk\", \"vdi\", \"qcow\", \"qcow2\",\n \"mdf\", \"mds\", \"nrg\", \"uif\",\n\n // Documents & Office\n \"pdf\",\n \"doc\", \"docx\", \"dot\", \"dotx\", \"docm\", \"dotm\",\n \"xls\", \"xlsx\", \"xlsm\", \"xlsb\", \"xlt\", \"xltx\", \"xltm\", \"xlc\", \"xlw\",\n \"ppt\", \"pptx\", \"pptm\", \"pps\", \"ppsx\", \"pot\", \"potx\", \"potm\",\n \"pub\", // Microsoft Publisher\n \"vsd\", \"vsdx\", // Visio\n \"accdb\", \"accde\", \"mdb\", \"mde\", // Access\n \"odt\", \"ods\", \"odp\", \"odg\", \"odf\", // OpenDocument\n \"pages\", \"numbers\", \"key\", // Apple iWork\n \"rtf\", // can be binary-like depending on usage\n\n // Spreadsheets, DB, and Misc Data\n \"db\", \"sqlite\", \"db3\", \"s3db\", \"frm\", \"myd\", \"myi\", // MySQL\n \"mdb\", \"bak\", \"nsf\", // Lotus Notes\n \"gdb\", \"fdb\", // Firebird\n \"mdb\", // Access DB\n \"wdb\", // Works DB\n\n // Images\n \"jpg\", \"jpeg\", \"png\", \"gif\", \"bmp\", \"ico\", \"tiff\", \"tif\", \"webp\", \"jfif\", \"jp2\",\n \"psd\", \"psb\", \"xcf\", \"ai\", \"eps\", \"raw\", \"arw\", \"cr2\", \"nef\", \"dng\", \"raf\", \"orf\",\n \"sr2\", \"heic\", \"heif\", \"icns\", \"img\", \"bpg\",\n\n // Audio\n \"mp3\", \"mp2\", \"aac\", \"ac3\", \"wav\", \"ogg\", \"oga\", \"flac\", \"alac\", \"m4a\", \"mp4a\",\n \"wma\", \"ra\", \"ram\", \"ape\", \"opus\", \"amr\", \"awb\",\n\n // Video\n \"mp4\", \"m4v\", \"mov\", \"avi\", \"wmv\", \"mkv\", \"flv\", \"f4v\", \"f4p\", \"f4a\", \"f4b\", \"3gp\",\n \"3g2\", \"mpeg\", \"mpg\", \"mpe\", \"m1v\", \"m2v\", \"ts\", \"mts\", \"m2ts\", \"vob\", \"rm\", \"rmvb\",\n \"asf\", \"ogv\", \"ogm\", \"webm\", \"dv\", \"divx\", \"xvid\",\n\n // Font Files\n \"ttf\", \"otf\", \"woff\", \"woff2\", \"eot\", \"fon\", \"psf\",\n\n // Firmware / BIOS / ROM / Game Data\n \"rom\", \"iso\", \"bin\", \"gba\", \"gbc\", \"nds\", \"n64\", \"z64\", \"v64\", \"gcm\", \"ciso\", \"wbfs\",\n \"pak\", \"wad\", \"dat\", \"sav\", \"rpx\",\n\n // Flash / Vector\n \"swf\", \"fla\", \"svgz\", // .svgz is compressed SVG (binary)\n\n // CAD / 3D\n \"dwg\", \"dxf\", \"dwf\", \"skp\", \"ifc\",\n \"stl\", \"obj\", \"fbx\", \"dae\", \"blend\", \"3ds\", \"ase\", \"gltf\", \"glb\",\n \n // E-Books\n \"epub\", \"mobi\", \"azw\", \"azw3\", \"fb2\", \"lrf\", \"lit\", \"pdb\",\n\n // Other\n \"swp\", \"swo\", // Vim swap files\n \"pch\", // Precompiled header\n \"xex\", \"elf\", // Console executables\n \"dmp\", \"mdmp\", // Memory dump\n \"bkf\", \"bkp\", // Backup\n \"pak\", // Common game data archives\n \"idx\", \"dat\", \"vcd\", // Various binary data\n \"icns\", // macOS icon\n \"hlp\", \"chm\", // Windows help\n \"torrent\", // BitTorrent\n \"mar\", // Mozilla archive\n \"qcow\", \"qcow2\", // QEMU disk\n \"apk\", \"aab\", // Android package/bundle\n \"crx\", // Chrome extension\n \"appx\", // Windows app package\n \"xap\", // Windows Phone app\n];\n\n/// Default sets of ignore patterns (separate from .gitignore)\npub const DEFAULT_IGNORE_PATTERNS: &[&str] = &[\n \"LICENSE\",\n \".git/**\",\n \".next/**\",\n \"node_modules/**\",\n \"vendor/**\",\n \"dist/**\",\n \"build/**\",\n \"out/**\",\n \"target/**\",\n \"bin/**\",\n \"obj/**\",\n \".idea/**\",\n \".vscode/**\",\n \".vs/**\",\n \".settings/**\",\n \".gradle/**\",\n \".mvn/**\",\n \".pytest_cache/**\",\n \"__pycache__/**\",\n \".sass-cache/**\",\n \".vercel/**\",\n \".turbo/**\",\n \"coverage/**\",\n \"test-results/**\",\n \".gitignore\",\n \"pnpm-lock.yaml\",\n \"yek.toml\",\n \"package-lock.json\",\n \"yarn.lock\",\n \"Cargo.lock\",\n \"Gemfile.lock\",\n \"composer.lock\",\n \"mix.lock\",\n \"poetry.lock\",\n \"Pipfile.lock\",\n \"packages.lock.json\",\n \"paket.lock\",\n \"*.pyc\",\n \"*.pyo\",\n \"*.pyd\",\n \"*.class\",\n \"*.o\",\n \"*.obj\",\n \"*.dll\",\n \"*.exe\",\n \"*.so\",\n \"*.dylib\",\n \"*.log\",\n \"*.tmp\",\n \"*.temp\",\n \"*.swp\",\n \"*.swo\",\n \".DS_Store\",\n \"Thumbs.db\",\n \".env*\",\n \"*.bak\",\n \"*~\",\n];\n\npub const DEFAULT_OUTPUT_TEMPLATE: &str = \">>>> FILE_PATH\\nFILE_CONTENT\";\n"]], "task_instance_info": {"created_time": "2025-08-21 01:47:37", "created_task_model": "DeepSeek-R1", "function_skeleton": "pub fn parse_token_limit (limit: &str) -> anyhow::Result<usize> {}", "code_description": "This code segment functions to: Convert a string-based token limit specification into its numerical equivalent, supporting optional magnitude suffixes for scaled value interpretation."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\npub fn parse_token_limit(limit: &str) -> anyhow::Result<usize> {\n let s = limit.trim().to_lowercase();\n if s.is_empty() {\n return Err(anyhow!(\"Empty token limit string\"));\n }\n\n let last_char = s.chars().last().unwrap(); // Safe since we checked empty\n match last_char {\n 'k' | 'm' => {\n let num_str = &s[..s.len() - 1];\n if num_str.is_empty() {\n return Err(anyhow!(\"Missing numeric value before suffix '{}'\", last_char));\n }\n let num: f64 = num_str.parse()\n .map_err(|e| anyhow!(\"Invalid numeric format '{}': {}\", num_str, e))?;\n \n let factor = match last_char {\n 'k' => 1e3,\n 'm' => 1e6,\n _ => unreachable!(),\n };\n \n let total = num * factor;\n if total.fract() != 0.0 {\n return Err(anyhow!(\n \"Non-integer token limit after applying suffix: {} * {} = {}\",\n num,\n factor,\n total\n ));\n }\n \n if total < 0.0 {\n return Err(anyhow!(\"Token limit cannot be negative\"));\n }\n \n Ok(total as usize)\n }\n _ => {\n s.parse::<usize>()\n .map_err(|e| anyhow!(\"Invalid token limit format '{}': {}\", s, e))\n }\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-49-11"}, "editdistance_info": {"edit_distance": 19.8697, "calculate_time": "2025-08-21 01:49:11", "true_code_clean": "pub fn parse_token_limit(limit: &str) -> anyhow::Result<usize> {\n if limit.to_lowercase().ends_with('k') {\n limit[..limit.len() - 1]\n .trim()\n .parse::<usize>()\n .map(|n| n * 1000)\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n } else {\n limit\n .parse::<usize>()\n .map_err(|e| anyhow!(\"tokens: Invalid token size: {}\", e))\n }\n}", "predict_code_clean": "pub fn parse_token_limit(limit: &str) -> anyhow::Result<usize> {\n let s = limit.trim().to_lowercase();\n if s.is_empty() {\n return Err(anyhow!(\"Empty token limit string\"));\n }\n let last_char = s.chars().last().unwrap(); \n match last_char {\n 'k' | 'm' => {\n let num_str = &s[..s.len() - 1];\n if num_str.is_empty() {\n return Err(anyhow!(\"Missing numeric value before suffix '{}'\", last_char));\n }\n let num: f64 = num_str.parse()\n .map_err(|e| anyhow!(\"Invalid numeric format '{}': {}\", num_str, e))?;\n let factor = match last_char {\n 'k' => 1e3,\n 'm' => 1e6,\n _ => unreachable!(),\n };\n let total = num * factor;\n if total.fract() != 0.0 {\n return Err(anyhow!(\n \"Non-integer token limit after applying suffix: {} * {} = {}\",\n num,\n factor,\n total\n ));\n }\n if total < 0.0 {\n return Err(anyhow!(\"Token limit cannot be negative\"));\n }\n Ok(total as usize)\n }\n _ => {\n s.parse::<usize>()\n .map_err(|e| anyhow!(\"Invalid token limit format '{}': {}\", s, e))\n }\n }\n}"}}