use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct CrateIdentifier {
pub name: String,
pub version: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub struct Dependency {
pub name: String,
pub version_req: String,
pub resolved_version: Option<String>,
pub kind: String,
pub optional: bool,
pub features: Vec<String>,
pub target: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct GetDependenciesOutput {
pub crate_info: CrateIdentifier,
pub direct_dependencies: Vec<Dependency>,
pub dependency_tree: Option<serde_json::Value>,
pub total_dependencies: usize,
}
impl GetDependenciesOutput {
pub fn to_json(&self) -> String {
serde_json::to_string(self)
.unwrap_or_else(|_| r#"{"error":"Failed to serialize response"}"#.to_string())
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct DepsErrorOutput {
pub error: String,
}
impl DepsErrorOutput {
pub fn new(message: impl Into<String>) -> Self {
Self {
error: message.into(),
}
}
pub fn to_json(&self) -> String {
serde_json::to_string(self)
.unwrap_or_else(|_| r#"{"error":"Failed to serialize error"}"#.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_dependencies_output_serialization() {
let output = GetDependenciesOutput {
crate_info: CrateIdentifier {
name: "test-crate".to_string(),
version: "1.0.0".to_string(),
},
direct_dependencies: vec![Dependency {
name: "serde".to_string(),
version_req: "^1.0".to_string(),
resolved_version: Some("1.0.193".to_string()),
kind: "normal".to_string(),
optional: false,
features: vec!["derive".to_string()],
target: None,
}],
dependency_tree: None,
total_dependencies: 1,
};
let json = output.to_json();
let deserialized: GetDependenciesOutput = serde_json::from_str(&json).unwrap();
assert_eq!(output, deserialized);
}
#[test]
fn test_deps_error_output() {
let output = DepsErrorOutput::new("Dependencies not available");
let json = output.to_json();
let deserialized: DepsErrorOutput = serde_json::from_str(&json).unwrap();
assert_eq!(output, deserialized);
}
}