1use std::collections::HashMap;
24use std::path::Path;
25
26use anyhow::Context;
27use model_core::{
28 Descriptor, EntityId, EntityKind, KindId, LanguageId, ModelBuilder, Provenance, RelationKind,
29 SymbolKey,
30};
31
32mod detect;
33#[cfg(test)]
34mod tests;
35
36pub use detect::{Endpoint, Framework, endpoints};
37
38pub const HTTP_ENDPOINT: &str = "http.endpoint";
40
41pub const IGNORED_DIRS: &[&str] = &[
43 ".git",
44 "node_modules",
45 "__pycache__",
46 ".venv",
47 "venv",
48 "site-packages",
49];
50
51#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
52pub struct PythonStats {
53 pub files: usize,
55 pub endpoints: usize,
56 pub resolved_views: usize,
58}
59
60fn language() -> LanguageId {
61 LanguageId::new("python")
62}
63
64pub fn declare_kinds(b: &mut ModelBuilder) -> KindId {
67 let id = b.define_kind(
68 HTTP_ENDPOINT,
69 EntityKind::Variable,
70 model_traits::mask(&["Named"]),
71 None,
72 );
73 b.set_kind_concept(id, Some("HttpEndpoint"), Some("httpEndpoints"));
74 id
75}
76
77struct Index {
80 at: HashMap<(String, u32, u32), EntityId>,
81 by_name: HashMap<String, Vec<EntityId>>,
82}
83
84impl Index {
85 fn new(b: &ModelBuilder) -> Index {
86 let mut at = HashMap::new();
87 let mut by_name: HashMap<String, Vec<EntityId>> = HashMap::new();
88 for id in b.ids() {
89 if b.external(id) {
90 continue;
91 }
92 let (Some(file), Some(r)) = (b.file(id), b.name_range(id)) else {
93 continue;
94 };
95 at.insert((file.to_string(), r.start_line, r.start_col), id);
96 let kind = b.kind(id);
97 if kind.is_callable() || kind.is_type() {
98 by_name.entry(b.name(id).to_string()).or_default().push(id);
99 }
100 }
101 Index { at, by_name }
102 }
103}
104
105pub fn enrich_sources(b: &mut ModelBuilder, files: &[(String, String)]) -> PythonStats {
107 let kind = declare_kinds(b);
108 let index = Index::new(b);
109 let lang = language();
110 let mut stats = PythonStats::default();
111 let mut seen: HashMap<String, u32> = HashMap::new();
112 let mut files: Vec<&(String, String)> =
113 files.iter().filter(|(p, _)| p.ends_with(".py")).collect();
114 files.sort_by(|a, b| a.0.cmp(&b.0));
115 for (path, src) in files {
116 stats.files += 1;
117 let file_key = SymbolKey::for_file(&lang, path);
118 let file_id = b.get(&file_key.to_string());
119 for e in endpoints(src) {
120 let handler = e
121 .handler_name_at
122 .and_then(|r| index.at.get(&(path.clone(), r.start_line, r.start_col)))
123 .copied();
124 let (parent, parent_key) = match handler {
125 Some(h) => (Some(h), b.key(h).to_string()),
126 None => (file_id, file_key.to_string()),
127 };
128 let name = format!("{} {}", e.method, e.path);
129 let mut key = format!("{parent_key}{}", Descriptor::Meta(name.clone()));
130 let n = seen.entry(key.clone()).or_insert(0);
131 if *n > 0 {
132 key = format!("{parent_key}{}", Descriptor::Meta(format!("{name}+{n}")));
133 }
134 *n += 1;
135 let id = b.entity_of_kind(&key, kind, &name);
136 b.set_language(id, &lang);
137 b.set_source(id, path, e.site, None);
138 b.set_parent(id, parent);
139 if let Some(p) = parent {
140 b.occurrence(
141 &RelationKind::Other("http.endpoints".to_string()),
142 p,
143 id,
144 Provenance::Frontend,
145 e.site,
146 );
147 }
148 b.set_prop(id, "http.framework", e.framework.as_str());
149 b.set_prop(id, "http.verb", e.method.as_str());
150 b.set_prop(id, "http.path", e.path.as_str());
151 if let Some(h) = handler {
152 b.set_prop(id, "http.handler", b.name(h).to_string());
153 }
154 if let Some(r) = &e.route_name {
155 b.set_prop(id, "http.route_name", r.as_str());
156 }
157 if let Some(view) = &e.handler_ref {
158 let last = view.rsplit('.').next().unwrap_or(view);
159 b.set_prop(id, "http.handler", last);
160 if let Some([only]) = index.by_name.get(last).map(Vec::as_slice) {
161 b.occurrence(
162 &RelationKind::Calls,
163 id,
164 *only,
165 Provenance::Frontend,
166 e.site,
167 );
168 stats.resolved_views += 1;
169 }
170 }
171 stats.endpoints += 1;
172 }
173 }
174 stats
175}
176
177pub fn enrich(
180 b: &mut ModelBuilder,
181 root: &Path,
182 keep: &dyn Fn(&str) -> bool,
183 warnings: &mut Vec<String>,
184) -> anyhow::Result<PythonStats> {
185 let mut files = Vec::new();
186 let walker = ignore::WalkBuilder::new(root)
187 .filter_entry(|e| {
188 !e.file_type().is_some_and(|t| t.is_dir())
189 || !IGNORED_DIRS.contains(&e.file_name().to_string_lossy().as_ref())
190 })
191 .build();
192 for entry in walker {
193 let entry = entry.with_context(|| format!("walking {}", root.display()))?;
194 let p = entry.path();
195 if p.extension().and_then(|e| e.to_str()) != Some("py") || !p.is_file() {
196 continue;
197 }
198 let rel = p
199 .strip_prefix(root)
200 .unwrap_or(p)
201 .to_string_lossy()
202 .replace('\\', "/");
203 if !keep(&rel) {
204 continue;
205 }
206 match std::fs::read_to_string(p) {
207 Ok(src) => files.push((rel, src)),
208 Err(e) => warnings.push(format!("cannot read {}: {e}", p.display())),
209 }
210 }
211 Ok(enrich_sources(b, &files))
212}