style: apply cargo fmt across entire Rust codebase

- Remove Rust formatting check from CI workflow since formatting is now applied
- Standardize import ordering and organization throughout codebase
- Fix indentation, spacing, and line breaks for consistency
- Clean up trailing whitespace and formatting inconsistencies
- Apply rustfmt to all Rust source files including checkpoint, sandbox, commands, and test modules

This establishes a consistent code style baseline for the project.
This commit is contained in:
Mufeed VH
2025-06-25 03:45:59 +05:30
parent bb48a32784
commit bcffce0a08
41 changed files with 3617 additions and 2662 deletions

View File

@@ -1,12 +1,12 @@
use anyhow::Result;
use log::{debug, error, info, warn};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
/// Shared module for detecting Claude Code binary installations
/// Supports NVM installations, aliased paths, and version-based selection
use std::path::PathBuf;
use std::process::Command;
use log::{info, warn, debug, error};
use anyhow::Result;
use std::cmp::Ordering;
use tauri::Manager;
use serde::{Serialize, Deserialize};
/// Represents a Claude installation with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -23,7 +23,7 @@ pub struct ClaudeInstallation {
/// Checks database first, then discovers all installations and selects the best one
pub fn find_claude_binary(app_handle: &tauri::AppHandle) -> Result<String, String> {
info!("Searching for claude binary...");
// First check if we have a stored path in the database
if let Ok(app_data_dir) = app_handle.path().app_data_dir() {
let db_path = app_data_dir.join("agents.db");
@@ -45,24 +45,26 @@ pub fn find_claude_binary(app_handle: &tauri::AppHandle) -> Result<String, Strin
}
}
}
// Discover all available installations
let installations = discover_all_installations();
if installations.is_empty() {
error!("Could not find claude binary in any location");
return Err("Claude Code not found. Please ensure it's installed in one of these locations: PATH, /usr/local/bin, /opt/homebrew/bin, ~/.nvm/versions/node/*/bin, ~/.claude/local, ~/.local/bin".to_string());
}
// Log all found installations
for installation in &installations {
info!("Found Claude installation: {:?}", installation);
}
// Select the best installation (highest version)
if let Some(best) = select_best_installation(installations) {
info!("Selected Claude installation: path={}, version={:?}, source={}",
best.path, best.version, best.source);
info!(
"Selected Claude installation: path={}, version={:?}, source={}",
best.path, best.version, best.source
);
Ok(best.path)
} else {
Err("No valid Claude installation found".to_string())
@@ -73,9 +75,9 @@ pub fn find_claude_binary(app_handle: &tauri::AppHandle) -> Result<String, Strin
/// This allows UI to show a version selector
pub fn discover_claude_installations() -> Vec<ClaudeInstallation> {
info!("Discovering all Claude installations...");
let installations = discover_all_installations();
// Sort by version (highest first), then by source preference
let mut sorted = installations;
sorted.sort_by(|a, b| {
@@ -87,15 +89,15 @@ pub fn discover_claude_installations() -> Vec<ClaudeInstallation> {
// If versions are equal, prefer by source
source_preference(a).cmp(&source_preference(b))
}
other => other
other => other,
}
}
(Some(_), None) => Ordering::Less, // Version comes before no version
(None, Some(_)) => Ordering::Greater,
(None, None) => source_preference(a).cmp(&source_preference(b))
(None, None) => source_preference(a).cmp(&source_preference(b)),
}
});
sorted
}
@@ -121,57 +123,58 @@ fn source_preference(installation: &ClaudeInstallation) -> u8 {
/// Discovers all Claude installations on the system
fn discover_all_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
// 1. Try 'which' command first (now works in production)
if let Some(installation) = try_which_command() {
installations.push(installation);
}
// 2. Check NVM paths
installations.extend(find_nvm_installations());
// 3. Check standard paths
installations.extend(find_standard_installations());
// Remove duplicates by path
let mut unique_paths = std::collections::HashSet::new();
installations.retain(|install| unique_paths.insert(install.path.clone()));
installations
}
/// Try using the 'which' command to find Claude
fn try_which_command() -> Option<ClaudeInstallation> {
debug!("Trying 'which claude' to find binary...");
match Command::new("which").arg("claude").output() {
Ok(output) if output.status.success() => {
let output_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
if output_str.is_empty() {
return None;
}
// Parse aliased output: "claude: aliased to /path/to/claude"
let path = if output_str.starts_with("claude:") && output_str.contains("aliased to") {
output_str.split("aliased to")
output_str
.split("aliased to")
.nth(1)
.map(|s| s.trim().to_string())
} else {
Some(output_str)
}?;
debug!("'which' found claude at: {}", path);
// Verify the path exists
if !PathBuf::from(&path).exists() {
warn!("Path from 'which' does not exist: {}", path);
return None;
}
// Get version
let version = get_claude_version(&path).ok().flatten();
Some(ClaudeInstallation {
path,
version,
@@ -185,26 +188,29 @@ fn try_which_command() -> Option<ClaudeInstallation> {
/// Find Claude installations in NVM directories
fn find_nvm_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
if let Ok(home) = std::env::var("HOME") {
let nvm_dir = PathBuf::from(&home).join(".nvm").join("versions").join("node");
let nvm_dir = PathBuf::from(&home)
.join(".nvm")
.join("versions")
.join("node");
debug!("Checking NVM directory: {:?}", nvm_dir);
if let Ok(entries) = std::fs::read_dir(&nvm_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let claude_path = entry.path().join("bin").join("claude");
if claude_path.exists() && claude_path.is_file() {
let path_str = claude_path.to_string_lossy().to_string();
let node_version = entry.file_name().to_string_lossy().to_string();
debug!("Found Claude in NVM node {}: {}", node_version, path_str);
// Get Claude version
let version = get_claude_version(&path_str).ok().flatten();
installations.push(ClaudeInstallation {
path: path_str,
version,
@@ -215,46 +221,64 @@ fn find_nvm_installations() -> Vec<ClaudeInstallation> {
}
}
}
installations
}
/// Check standard installation paths
fn find_standard_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
// Common installation paths for claude
let mut paths_to_check: Vec<(String, String)> = vec![
("/usr/local/bin/claude".to_string(), "system".to_string()),
("/opt/homebrew/bin/claude".to_string(), "homebrew".to_string()),
(
"/opt/homebrew/bin/claude".to_string(),
"homebrew".to_string(),
),
("/usr/bin/claude".to_string(), "system".to_string()),
("/bin/claude".to_string(), "system".to_string()),
];
// Also check user-specific paths
if let Ok(home) = std::env::var("HOME") {
paths_to_check.extend(vec![
(format!("{}/.claude/local/claude", home), "claude-local".to_string()),
(format!("{}/.local/bin/claude", home), "local-bin".to_string()),
(format!("{}/.npm-global/bin/claude", home), "npm-global".to_string()),
(
format!("{}/.claude/local/claude", home),
"claude-local".to_string(),
),
(
format!("{}/.local/bin/claude", home),
"local-bin".to_string(),
),
(
format!("{}/.npm-global/bin/claude", home),
"npm-global".to_string(),
),
(format!("{}/.yarn/bin/claude", home), "yarn".to_string()),
(format!("{}/.bun/bin/claude", home), "bun".to_string()),
(format!("{}/bin/claude", home), "home-bin".to_string()),
// Check common node_modules locations
(format!("{}/node_modules/.bin/claude", home), "node-modules".to_string()),
(format!("{}/.config/yarn/global/node_modules/.bin/claude", home), "yarn-global".to_string()),
(
format!("{}/node_modules/.bin/claude", home),
"node-modules".to_string(),
),
(
format!("{}/.config/yarn/global/node_modules/.bin/claude", home),
"yarn-global".to_string(),
),
]);
}
// Check each path
for (path, source) in paths_to_check {
let path_buf = PathBuf::from(&path);
if path_buf.exists() && path_buf.is_file() {
debug!("Found claude at standard path: {} ({})", path, source);
// Get version
let version = get_claude_version(&path).ok().flatten();
installations.push(ClaudeInstallation {
path,
version,
@@ -262,13 +286,13 @@ fn find_standard_installations() -> Vec<ClaudeInstallation> {
});
}
}
// Also check if claude is available in PATH (without full path)
if let Ok(output) = Command::new("claude").arg("--version").output() {
if output.status.success() {
debug!("claude is available in PATH");
let version = extract_version_from_output(&output.stdout);
installations.push(ClaudeInstallation {
path: "claude".to_string(),
version,
@@ -276,7 +300,7 @@ fn find_standard_installations() -> Vec<ClaudeInstallation> {
});
}
}
installations
}
@@ -300,13 +324,13 @@ fn get_claude_version(path: &str) -> Result<Option<String>, String> {
/// Extract version string from command output
fn extract_version_from_output(stdout: &[u8]) -> Option<String> {
let output_str = String::from_utf8_lossy(stdout);
// Extract version: first token before whitespace that looks like a version
output_str.split_whitespace()
output_str
.split_whitespace()
.find(|token| {
// Version usually contains dots and numbers
token.chars().any(|c| c == '.') &&
token.chars().any(|c| c.is_numeric())
token.chars().any(|c| c == '.') && token.chars().any(|c| c.is_numeric())
})
.map(|s| s.to_string())
}
@@ -320,34 +344,34 @@ fn select_best_installation(installations: Vec<ClaudeInstallation>) -> Option<Cl
// prefer binaries with version information when it is available so that
// in development builds we keep the previous behaviour of picking the
// most recent version.
installations.into_iter()
.max_by(|a, b| {
match (&a.version, &b.version) {
// If both have versions, compare them semantically.
(Some(v1), Some(v2)) => compare_versions(v1, v2),
// Prefer the entry that actually has version information.
(Some(_), None) => Ordering::Greater,
(None, Some(_)) => Ordering::Less,
// Neither have version info: prefer the one that is not just
// the bare "claude" lookup from PATH, because that may fail
// at runtime if PATH is sandbox-stripped.
(None, None) => {
if a.path == "claude" && b.path != "claude" {
Ordering::Less
} else if a.path != "claude" && b.path == "claude" {
Ordering::Greater
} else {
Ordering::Equal
}
installations.into_iter().max_by(|a, b| {
match (&a.version, &b.version) {
// If both have versions, compare them semantically.
(Some(v1), Some(v2)) => compare_versions(v1, v2),
// Prefer the entry that actually has version information.
(Some(_), None) => Ordering::Greater,
(None, Some(_)) => Ordering::Less,
// Neither have version info: prefer the one that is not just
// the bare "claude" lookup from PATH, because that may fail
// at runtime if PATH is sandbox-stripped.
(None, None) => {
if a.path == "claude" && b.path != "claude" {
Ordering::Less
} else if a.path != "claude" && b.path == "claude" {
Ordering::Greater
} else {
Ordering::Equal
}
}
})
}
})
}
/// Compare two version strings
fn compare_versions(a: &str, b: &str) -> Ordering {
// Simple semantic version comparison
let a_parts: Vec<u32> = a.split('.')
let a_parts: Vec<u32> = a
.split('.')
.filter_map(|s| {
// Handle versions like "1.0.17-beta" by taking only numeric part
s.chars()
@@ -357,8 +381,9 @@ fn compare_versions(a: &str, b: &str) -> Ordering {
.ok()
})
.collect();
let b_parts: Vec<u32> = b.split('.')
let b_parts: Vec<u32> = b
.split('.')
.filter_map(|s| {
s.chars()
.take_while(|c| c.is_numeric())
@@ -367,7 +392,7 @@ fn compare_versions(a: &str, b: &str) -> Ordering {
.ok()
})
.collect();
// Compare each part
for i in 0..std::cmp::max(a_parts.len(), b_parts.len()) {
let a_val = a_parts.get(i).unwrap_or(&0);
@@ -377,7 +402,7 @@ fn compare_versions(a: &str, b: &str) -> Ordering {
other => return other,
}
}
Ordering::Equal
}
@@ -385,19 +410,28 @@ fn compare_versions(a: &str, b: &str) -> Ordering {
/// This ensures commands like Claude can find Node.js and other dependencies
pub fn create_command_with_env(program: &str) -> Command {
let mut cmd = Command::new(program);
// Inherit essential environment variables from parent process
for (key, value) in std::env::vars() {
// Pass through PATH and other essential environment variables
if key == "PATH" || key == "HOME" || key == "USER"
|| key == "SHELL" || key == "LANG" || key == "LC_ALL" || key.starts_with("LC_")
|| key == "NODE_PATH" || key == "NVM_DIR" || key == "NVM_BIN"
|| key == "HOMEBREW_PREFIX" || key == "HOMEBREW_CELLAR" {
if key == "PATH"
|| key == "HOME"
|| key == "USER"
|| key == "SHELL"
|| key == "LANG"
|| key == "LC_ALL"
|| key.starts_with("LC_")
|| key == "NODE_PATH"
|| key == "NVM_DIR"
|| key == "NVM_BIN"
|| key == "HOMEBREW_PREFIX"
|| key == "HOMEBREW_CELLAR"
{
debug!("Inheriting env var: {}={}", key, value);
cmd.env(&key, &value);
}
}
// Add NVM support if the program is in an NVM directory
if program.contains("/.nvm/versions/node/") {
if let Some(node_bin_dir) = std::path::Path::new(program).parent() {
@@ -411,6 +445,6 @@ pub fn create_command_with_env(program: &str) -> Command {
}
}
}
cmd
}
}