use std::sync::Arc;
use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;
use crate::ir::{Address, Span};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EdgeKind {
ExplicitDependsOn,
AttrRef,
ModuleInput,
TerragruntDependency,
}
impl EdgeKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::ExplicitDependsOn => "explicit_depends_on",
Self::AttrRef => "attr_ref",
Self::ModuleInput => "module_input",
Self::TerragruntDependency => "terragrunt_dependency",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, TypedBuilder)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
#[builder(field_defaults(setter(into)))]
pub struct Edge {
pub from: Address,
pub to: Address,
pub kind: EdgeKind,
#[builder(default)]
pub attr: Option<Arc<str>>,
pub span: Span,
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use std::sync::Arc;
use super::*;
use crate::ir::Span;
#[test]
fn test_edge_kind_string_form_is_stable() {
assert_eq!(EdgeKind::ExplicitDependsOn.as_str(), "explicit_depends_on");
assert_eq!(EdgeKind::AttrRef.as_str(), "attr_ref");
assert_eq!(EdgeKind::ModuleInput.as_str(), "module_input");
assert_eq!(
EdgeKind::TerragruntDependency.as_str(),
"terragrunt_dependency"
);
}
#[test]
fn test_should_build_minimal_edge() {
let e = Edge::builder()
.from(Address::new("aws_iam_role.r").unwrap())
.to(Address::new("aws_iam_policy.p").unwrap())
.kind(EdgeKind::AttrRef)
.attr(Some(Arc::<str>::from("policy")))
.span(Span::synthetic())
.build();
assert_eq!(e.from.as_str(), "aws_iam_role.r");
assert_eq!(e.kind, EdgeKind::AttrRef);
}
#[test]
fn test_should_serde_round_trip_edge() {
let e = Edge::builder()
.from(Address::new("aws_iam_role.r").unwrap())
.to(Address::new("aws_iam_policy.p").unwrap())
.kind(EdgeKind::AttrRef)
.span(Span::synthetic())
.build();
let json = serde_json::to_string(&e).unwrap();
let back: Edge = serde_json::from_str(&json).unwrap();
assert_eq!(e, back);
}
}