Files
gitks/repository/search_files.rs
T
zhenyi 10a4398e81 refactor(bare): enhance security and performance optimizations
- Remove unnecessary sorting in advertise_refs for deterministic output
- Add path traversal detection and validation in bare_dir construction
- Implement symlink resolution checks to prevent security vulnerabilities
- Refactor cache system with CRC validation and improved metrics
- Integrate repo-specific cache invalidation using indexed keys
- Add comprehensive unit tests for commit operations and diff functionality
- Move configuration constants to centralized config module
- Optimize string operations in disk cache random value generation
- Enhance license detection algorithm with cleaner matching logic
- Streamline argument processing in various git operations
- Update dependencies including crc32fast and flate2 for performance
- Add signal handling capability to tokio runtime configuration
2026-06-12 15:04:12 +08:00

168 lines
5.3 KiB
Rust

use crate::bare::GitBare;
use crate::error::GitResult;
use crate::pb::*;
const MAX_SEARCH_RESULTS: u32 = 1000;
impl GitBare {
/// Search file contents with a regex pattern.
pub fn search_files_by_content(
&self,
request: SearchFilesByContentRequest,
) -> GitResult<SearchFilesByContentResponse> {
let revision = if request.revision.is_empty() {
"HEAD"
} else {
&request.revision
};
crate::sanitize::validate_revision(revision)?;
if request.query.is_empty() {
return Err(crate::error::GitError::InvalidArgument(
"search query cannot be empty".into(),
));
}
let max_results = if request.max_results == 0 {
100
} else {
request.max_results.min(MAX_SEARCH_RESULTS)
};
let mut args = vec![
"--git-dir".to_string(),
self.bare_dir.to_string_lossy().into_owned(),
"grep".to_string(),
"-F".to_string(),
"-I".to_string(),
"--line-number".to_string(),
"--column".to_string(),
];
if !request.case_sensitive {
args.push("-i".to_string());
}
args.push(format!("--max-count={}", max_results));
args.push("-e".to_string());
args.push(request.query.clone());
args.push(revision.to_string());
let output = std::process::Command::new("git")
.args(&args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.map_err(|e| crate::error::GitError::CommandFailed {
status_code: None,
stderr: e.to_string(),
})?;
// git grep returns exit code 1 when no matches found — that's not an error
if !output.status.success() && output.status.code() != Some(1) {
return Err(crate::error::GitError::CommandFailed {
status_code: output.status.code(),
stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
});
}
let stdout = String::from_utf8_lossy(&output.stdout);
let mut results = Vec::new();
for line in stdout.lines() {
if let Some((path_and_rest, matched)) = line.rsplit_once(':') {
let prefix_parts: Vec<&str> = path_and_rest.rsplitn(3, ':').collect();
if prefix_parts.len() >= 3
&& let Ok(line_num) = prefix_parts[1].parse::<u32>()
{
results.push(SearchResult {
path: prefix_parts[2].to_string(),
line: line_num,
matched_text: matched.to_string(),
});
if results.len() >= max_results as usize {
break;
}
}
}
}
Ok(SearchFilesByContentResponse { results })
}
/// Search file names matching a pattern.
pub fn search_files_by_name(
&self,
request: SearchFilesByNameRequest,
) -> GitResult<SearchFilesByNameResponse> {
let revision = if request.revision.is_empty() {
"HEAD"
} else {
&request.revision
};
crate::sanitize::validate_revision(revision)?;
let max_results = if request.max_results == 0 {
100
} else {
request.max_results.min(MAX_SEARCH_RESULTS)
};
let mut args = vec![
"--git-dir".to_string(),
self.bare_dir.to_string_lossy().into_owned(),
"ls-tree".to_string(),
];
if request.recursive {
args.push("-r".to_string());
}
args.push("--name-only".to_string());
args.push(revision.to_string());
let output = std::process::Command::new("git")
.args(&args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output()
.map_err(|e| crate::error::GitError::CommandFailed {
status_code: None,
stderr: e.to_string(),
})?;
if !output.status.success() {
return Err(crate::error::GitError::CommandFailed {
status_code: output.status.code(),
stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
});
}
let stdout = String::from_utf8_lossy(&output.stdout);
let mut results = Vec::new();
for line in stdout.lines() {
let path = line.trim();
if path.is_empty() || crate::sanitize::validate_file_path(path).is_err() {
continue;
}
let query = &request.query;
let matched = if query.is_empty() {
true
} else {
path.to_lowercase().contains(&query.to_lowercase())
};
if matched {
results.push(SearchResult {
path: path.to_string(),
line: 0,
matched_text: String::new(),
});
if results.len() >= max_results as usize {
break;
}
}
}
Ok(SearchFilesByNameResponse { results })
}
}