codegraph_python/relationships/
imports.rs1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
5pub struct ImportEntity {
6 pub imported_items: Vec<String>,
8
9 pub from_module: String,
11
12 pub line: usize,
14
15 pub is_wildcard: bool,
17}
18
19impl ImportEntity {
20 pub fn new(from_module: impl Into<String>, imported_items: Vec<String>, line: usize) -> Self {
22 Self {
23 imported_items,
24 from_module: from_module.into(),
25 line,
26 is_wildcard: false,
27 }
28 }
29
30 pub fn wildcard(from_module: impl Into<String>, line: usize) -> Self {
32 Self {
33 imported_items: vec![],
34 from_module: from_module.into(),
35 line,
36 is_wildcard: true,
37 }
38 }
39
40 pub fn imports_name(&self, name: &str) -> bool {
42 if self.is_wildcard {
43 true } else {
45 self.imported_items.iter().any(|item| item == name)
46 }
47 }
48
49 pub fn add_item(mut self, item: impl Into<String>) -> Self {
51 self.imported_items.push(item.into());
52 self
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 #[test]
61 fn test_import_entity_new() {
62 let import = ImportEntity::new("os", vec!["path".to_string()], 1);
63 assert_eq!(import.from_module, "os");
64 assert_eq!(import.imported_items, vec!["path"]);
65 assert_eq!(import.line, 1);
66 assert!(!import.is_wildcard);
67 }
68
69 #[test]
70 fn test_wildcard_import() {
71 let import = ImportEntity::wildcard("os", 1);
72 assert_eq!(import.from_module, "os");
73 assert!(import.imported_items.is_empty());
74 assert!(import.is_wildcard);
75 }
76
77 #[test]
78 fn test_imports_name() {
79 let import = ImportEntity::new("os", vec!["path".to_string(), "environ".to_string()], 1);
80 assert!(import.imports_name("path"));
81 assert!(import.imports_name("environ"));
82 assert!(!import.imports_name("getcwd"));
83
84 let wildcard = ImportEntity::wildcard("os", 1);
85 assert!(wildcard.imports_name("anything"));
86 }
87}