This Rust tool will search SVN commit messages. It starts by finding the current working copy's repository URL, then recursively fetches logs and svn:externals definitions from that repository and any linked externals, searching all messages for a given regular expression pattern.
Features:
- Search Commit Messages: Uses
svn log --xml to fetch commit messages.
- Handle Externals: Parses
svn:externals properties using svn proplist --xml and recursively searches those repositories.
- Recursive Search: Traverses external dependencies to find messages across the entire linked repository graph.
- Regular Expression Matching: Allows flexible search patterns.
- Prevents Infinite Loops: Uses a
HashSet to keep track of visited repository URLs to avoid re-processing the same repository or falling into cycles.
- Command Line Interface: Uses
clap for easy argument parsing.
- Robust Error Handling: Uses
anyhow for simplified error propagation.
Prerequisites
You need to have svn command-line client installed and accessible in your system's PATH.
Project Structure
svn-log-search/
├── Cargo.toml
└── src/
├── main.rs
├── cli.rs
├── svn.rs
└── parser.rs
Code Implementation
1. Cargo.toml
[package]
name = "svn-log-search"
version = "0.1.0"
edition = "2021"
[dependencies]
clap = { version = "4.0", features = ["derive"] }
regex = "1.5"
quick-xml = { version = "0.29", features = ["serialize"] } # For parsing XML
serde = { version = "1.0", features = ["derive"] }
anyhow = "1.0" # For simplified error handling
url = "2.2" # For resolving external URLs
2. src/main.rs
mod cli;
mod svn;
mod parser;
use anyhow::{anyhow, Result};
use clap::Parser;
use regex::Regex;
use std::collections::HashSet;
use std::path::PathBuf;
use std::env;
#[tokio::main] // Using tokio for async operations, specifically for futures::join_all
async fn main() -> Result<()> {
let args = cli::Cli::parse();
// Compile the regex pattern
let search_pattern = Regex::new(&args.pattern)?;
// Get the current working directory as the starting point for SVN info
let current_dir = env::current_dir()?;
// Get the URL of the current working copy
println!("Determining base SVN repository URL from: {:?}", current_dir);
let base_repo_url_str = svn::get_svn_info_url(¤t_dir)
.await
.map_err(|e| anyhow!("Could not get SVN info from current directory. Is it an SVN working copy?\nError: {}", e))?;
let base_repo_url = url::Url::parse(&base_repo_url_str)?;
println!("Base SVN repository URL: {}", base_repo_url);
let mut visited_repos: HashSet<String> = HashSet::new();
let mut all_found_logs = Vec::new();
println!("\nStarting recursive SVN log search...\n");
svn::search_repo_recursively(
base_repo_url,
&search_pattern,
&mut visited_repos,
&mut all_found_logs,
).await?;
// Print results
if all_found_logs.is_empty() {
println!("No matching commit messages found.");
} else {
println!("\n--- Matching Commit Messages ---");
for log in &all_found_logs {
println!("Repository: {}", log.repo_url);
println!(" Rev: r{}", log.revision);
println!(" Author: {}", log.author);
println!(" Date: {}", log.date);
println!(" Message:\n{}\n", textwrap::indent(&log.message, " "));
}
println!("Total matches: {}", all_found_logs.len());
}
Ok(())
}
3. src/cli.rs
use clap::Parser;
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
/// Regular expression pattern to search for in commit messages.
/// Example: "bugfix|feature-XYZ" (case-sensitive by default)
#[arg(short, long)]
pub pattern: String,
}
4. src/svn.rs
This module handles executing SVN commands and orchestrating the recursive search.
use crate::parser::{self, LogEntry, SvnInfo, SvnPropertyList};
use anyhow::{anyhow, Context, Result};
use regex::Regex;
use std::collections::HashSet;
use std::path::Path;
use tokio::process::Command;
use tokio::join; // For async concurrency
use url::Url;
// Public structure to represent a log entry found, including its source repository
pub struct FoundLogEntry {
pub repo_url: String,
pub revision: u64,
pub author: String,
pub date: String,
pub message: String,
}
/// Fetches SVN info XML from a given path and parses the repository URL.
pub async fn get_svn_info_url(path: &Path) -> Result<String> {
let output = Command::new("svn")
.arg("info")
.arg("--xml")
.arg("--non-interactive")
.arg(path)
.output()
.await
.with_context(|| format!("Failed to execute 'svn info' for path: {:?}", path))?;
if !output.status.success() {
return Err(anyhow!(
"'svn info' failed with status: {}. Error: {}",
output.status,
String::from_utf8_lossy(&output.stderr)
));
}
let xml_output = String::from_utf8_lossy(&output.stdout).into_owned();
let info: SvnInfo = serde_xml_rs::from_str(&xml_output)?;
// The <url> tag is directly under <entry> in svn info --xml output
info.entry.url.ok_or_else(|| anyhow!("Could not find URL in 'svn info' output."))
}
/// Fetches SVN log XML for a given repository URL and parses it.
async fn get_svn_logs(repo_url: &Url) -> Result<Vec<LogEntry>> {
println!(" Fetching logs from: {}", repo_url);
let output = Command::new("svn")
.arg("log")
.arg("--xml")
.arg("--non-interactive")
// Use a very large limit to try and get all logs.
// For extremely large repos, this might still be an issue.
// A more advanced solution would be to fetch in chunks by revision.
.arg("--limit")
.arg("1000000000") // A practical max limit for most use cases
.arg("--quiet") // Don't print merge info or path changes unless explicitly needed (not for this tool)
.arg(repo_url.as_str())
.output()
.await
.with_context(|| format!("Failed to execute 'svn log' for URL: {}", repo_url))?;
if !output.status.success() {
return Err(anyhow!(
"'svn log' failed for {}. Status: {}. Error: {}",
repo_url,
output.status,
String::from_utf8_lossy(&output.stderr)
));
}
let xml_output = String::from_utf8_lossy(&output.stdout).into_owned();
parser::parse_log_xml(&xml_output)
}
/// Fetches SVN properties for a given repository URL and parses externals.
async fn get_svn_externals(repo_url: &Url) -> Result<Vec<parser::ExternalDefinition>> {
println!(" Checking externals for: {}", repo_url);
let output = Command::new("svn")
.arg("proplist")
.arg("--xml")
.arg("--non-interactive")
.arg("--depth") // Only get properties of the directory itself
.arg("immediates")
.arg(repo_url.as_str())
.output()
.await
.with_context(|| format!("Failed to execute 'svn proplist' for URL: {}", repo_url))?;
if !output.status.success() {
// proplist returns non-zero if no properties, which is fine
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.contains("has no properties") && !stderr.contains("is not a working copy") && !stderr.is_empty() {
eprintln!(
"Warning: 'svn proplist' failed for {}. Status: {}. Error: {}",
repo_url, output.status, stderr
);
}
return Ok(vec![]); // No externals found or command failed gracefully
}
let xml_output = String::from_utf8_lossy(&output.stdout).into_owned();
parser::parse_externals_xml(&xml_output)
}
/// Recursively searches SVN logs and externals for a given pattern.
pub async fn search_repo_recursively(
repo_url: Url,
search_pattern: &Regex,
visited_repos: &mut HashSet<String>,
all_found_logs: &mut Vec<FoundLogEntry>,
) -> Result<()> {
let repo_url_str = repo_url.to_string();
// Prevent infinite recursion and redundant work
if !visited_repos.insert(repo_url_str.clone()) {
println!(" Skipping already visited repository: {}", repo_url_str);
return Ok(());
}
println!("\nSearching repository: {}", repo_url_str);
// Fetch logs and externals concurrently for the current repo
let (logs_result, externals_result) = join!(
get_svn_logs(&repo_url),
get_svn_externals(&repo_url)
);
// Process logs
match logs_result {
Ok(log_entries) => {
for log_entry in log_entries {
if search_pattern.is_match(&log_entry.message) {
all_found_logs.push(FoundLogEntry {
repo_url: repo_url_str.clone(),
revision: log_entry.revision,
author: log_entry.author,
date: log_entry.date,
message: log_entry.message,
});
}
}
},
Err(e) => {
eprintln!("Error fetching logs for {}: {}", repo_url_str, e);
// Continue with externals even if logs failed for this repo
}
}
// Process externals
match externals_result {
Ok(externals) => {
let mut tasks = Vec::new();
for ext in externals {
// Resolve external URL relative to the current repository's URL
let resolved_external_url = match Url::parse(&ext.url) {
Ok(absolute_url) => absolute_url, // It's already an absolute URL
Err(_) => {
// Attempt to resolve as relative. SVN relative URLs can be complex:
// ^/path (relative to repository root)
// ../path (relative to parent of current URL)
if ext.url.starts_with('^') {
// Relative to repository root
if let Some(root_url) = get_repository_root(&repo_url) {
root_url.join(&ext.url[1..])?
} else {
eprintln!("Warning: Could not determine repository root for relative external '{}' from '{}'. Skipping.", ext.url, repo_url);
continue;
}
} else {
// Standard relative path (e.g., ../foo, bar/baz)
repo_url.join(&ext.url)?
}
}
};
// Spawn a new task for each external to process them concurrently
let pattern_clone = search_pattern.clone();
let mut visited_repos_clone = visited_repos.clone(); // Clone for each task
let mut all_found_logs_clone = all_found_logs.clone(); // Clone for each task
tasks.push(tokio::spawn(async move {
let result = search_repo_recursively(
resolved_external_url,
&pattern_clone,
&mut visited_repos_clone,
&mut all_found_logs_clone,
).await;
(result, visited_repos_clone, all_found_logs_clone)
}));
}
// Await all spawned tasks and merge their results
for task in tasks {
let (result, task_visited_repos, task_found_logs) = task.await?;
result?; // Propagate errors from sub-tasks
visited_repos.extend(task_visited_repos); // Merge visited repos
all_found_logs.extend(task_found_logs); // Merge found logs
}
},
Err(e) => {
eprintln!("Error fetching externals for {}: {}", repo_url_str, e);
// Continue without externals for this repo
}
}
Ok(())
}
/// Attempts to get the repository root URL from a given URL.
/// Example: "http://example.com/svn/repo/trunk/project" -> "http://example.com/svn/repo"
/// This is a heuristic and might not be perfect for all SVN setups.
fn get_repository_root(url: &Url) -> Option<Url> {
let mut parts: Vec<&str> = url.path_segments()?.collect();
// Common SVN root structures: /trunk, /branches, /tags
while let Some(segment) = parts.last() {
if ["trunk", "branches", "tags"].contains(&segment.to_ascii_lowercase().as_str()) {
parts.pop(); // Remove the structure segment
} else {
break; // Not a common structure segment, assume this is part of the repository name
}
}
// Reconstruct the URL up to the assumed root
let mut root_url = url.clone();
root_url.set_path(&format!("/{}", parts.join("/")));
Some(root_url)
}
5. src/parser.rs
This module contains the logic for parsing the XML output from SVN commands.
use anyhow::{anyhow, Result};
use quick_xml::de::from_str;
use serde::Deserialize;
// --- Structures for svn log --xml parsing ---
#[derive(Debug, Deserialize)]
#[serde(rename = "logentry")]
pub struct LogEntry {
#[serde(rename = "@revision")]
pub revision: u64,
pub author: String,
pub date: String,
pub msg: String,
// Paths are ignored for simplicity as we only care about the message
// #[serde(rename = "paths")]
// pub paths: Option<Vec<PathEntry>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename = "log")]
struct SvnLog {
#[serde(rename = "logentry")]
pub entries: Vec<LogEntry>,
}
/// Parses the XML output of `svn log --xml`.
pub fn parse_log_xml(xml: &str) -> Result<Vec<LogEntry>> {
let log: SvnLog = from_str(xml)?;
Ok(log.entries)
}
// --- Structures for svn info --xml parsing ---
#[derive(Debug, Deserialize)]
#[serde(rename = "entry")]
pub struct SvnInfoEntry {
#[serde(rename = "url")]
pub url: Option<String>,
// Other fields like root, uuid, revision, kind, etc. are ignored
}
#[derive(Debug, Deserialize)]
#[serde(rename = "info")]
pub struct SvnInfo {
#[serde(rename = "entry")]
pub entry: SvnInfoEntry,
}
// --- Structures for svn proplist --xml parsing ---
#[derive(Debug, Deserialize)]
#[serde(rename = "property")]
pub struct Property {
#[serde(rename = "@name")]
pub name: String,
#[serde(rename = "$value")]
pub value: String, // The content of the property
}
#[derive(Debug, Deserialize)]
#[serde(rename = "target")]
pub struct Target {
#[serde(rename = "property")]
pub properties: Option<Vec<Property>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename = "proplist")]
pub struct SvnPropertyList {
#[serde(rename = "target")]
pub target: Option<Target>,
}
/// Represents a parsed SVN external definition.
#[derive(Debug)]
pub struct ExternalDefinition {
pub local_path: String,
pub url: String,
pub revision: Option<String>, // Can be empty or explicit
}
/// Parses the XML output of `svn proplist --xml` to extract externals.
pub fn parse_externals_xml(xml: &str) -> Result<Vec<ExternalDefinition>> {
let proplist: SvnPropertyList = from_str(xml)?;
let mut externals = Vec::new();
if let Some(target) = proplist.target {
if let Some(properties) = target.properties {
for prop in properties {
if prop.name == "svn:externals" {
// svn:externals value is multi-line: "local_path URL [@rev]"
for line in prop.value.lines() {
let trimmed_line = line.trim();
if trimmed_line.is_empty() || trimmed_line.starts_with('#') {
continue; // Skip empty lines and comments
}
let parts: Vec<&str> = trimmed_line.split_whitespace().collect();
if parts.len() >= 2 {
let local_path = parts[0].to_string();
let url_or_path = parts[1].to_string();
let revision = if parts.len() > 2 {
Some(parts[2].to_string())
} else {
None
};
externals.push(ExternalDefinition {
local_path,
url: url_or_path,
revision,
});
} else {
eprintln!("Warning: Malformed svn:externals line: '{}'", trimmed_line);
}
}
}
}
}
}
Ok(externals)
}
How to Build and Run
-
Save the files: Create the directory structure svn-log-search/src/ and place the respective .rs files inside src/. Place Cargo.toml in the svn-log-search/ root.
-
Navigate to the project root:
cd svn-log-search
-
Build the project:
cargo build --release
-
Run the tool:
Go to an SVN working copy directory (or a subdirectory within one) and run the compiled executable:
# Example: Search for "bugfix" in commit messages
# From within your SVN working copy:
/path/to/svn-log-search/target/release/svn-log-search --pattern "bugfix"
# Example: Search for a specific ticket number (case-insensitive)
/path/to/svn-log-search/target/release/svn-log-search --pattern "(?i)ticket-123"
# Example: Search for author "John Doe" (requires regex for authors, current tool searches msg)
# The current tool only searches messages. For author, date, you'd need to extend parsing and filtering.
# To search "John Doe" in message:
/path/to/svn-log-search/target/release/svn-log-search --pattern "John Doe"
Replace /path/to/svn-log-search with the actual path to your svn-log-search directory. You can also add target/release to your PATH or move the executable to a known location.
Important Considerations and Limitations
- SVN Client: This tool relies on the
svn command-line client being installed and configured for authentication (if required by your SVN server). It uses --non-interactive, so it won't prompt for credentials. Ensure your svn client is set up with cached credentials or an appropriate auth directory.
- Large Repositories: For extremely large repositories with millions of commits,
svn log --limit 1000000000 might still be slow or hit server limits. A more robust solution for such cases would involve fetching logs in smaller revision chunks.
- Relative Externals (
^/ and ../): The tool attempts to resolve ^/ (relative to repository root) and ../ (relative to current path) externals using url::Url::join and a heuristic for get_repository_root. This heuristic might not cover all possible SVN repository layouts. Absolute URLs are handled directly.
- Performance: The tool uses
tokio::join! for concurrent svn log and svn proplist calls on the current repository. For recursing into externals, it spawns tokio::spawn tasks. This provides some parallelism.
- Deep Externals: If an external points to another repository, which in turn has its own externals, the tool will follow this chain recursively.
- SVN Protocol: It assumes standard
svn://, http://, or https:// URLs for repositories. file:// URLs might work but are less common for multi-repo setups with externals.
- Error Reporting: Errors during
svn command execution or XML parsing are reported using anyhow.
- Regex Case Sensitivity: By default, Rust's
regex crate is case-sensitive. Use (?i) at the start of your pattern for case-insensitive matching (e.g., --pattern "(?i)bugfix").