Skip to main content

offline_generator/
project_detect.rs

1//! Recognise an existing Python, Swift or Gradle (Kotlin/Java) project, so
2//! `offline init` and the MCP `init_project` tool can wire projects that have
3//! no `package.json`.
4//!
5//! Detection only reads files: the manifest names the platform, the project
6//! name comes from the manifest or the folder, and an Offline Protocol package
7//! counts as installed when its name or an alias appears in a manifest.
8
9use std::path::{Path, PathBuf};
10
11use offline_registry::{PackageManifest, Registry};
12
13const DOCS_BASE: &str = "https://www.offlineprotocol.com/docs";
14
15/// A non-JavaScript project found in a directory.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct NativeProject {
18    /// Registry platform: `python`, `ios-native`, `android-native` or `java`.
19    pub platform: &'static str,
20    /// Human name of the toolchain, for messages (`Python`, `Swift`, ...).
21    pub language: &'static str,
22    /// Project name from the manifest, else the folder name.
23    pub name: String,
24    /// Manifest files that were read, relative to the project directory.
25    pub manifests: Vec<PathBuf>,
26    text: String,
27}
28
29impl NativeProject {
30    /// Registry packages for this platform that the manifests mention.
31    pub fn installed_packages(&self, registry: &Registry) -> Vec<String> {
32        let haystack = normalise(&self.text);
33        registry
34            .packages()
35            .filter(|p| p.platforms.iter().any(|pl| pl == self.platform))
36            .filter(|p| {
37                std::iter::once(&p.name)
38                    .chain(p.aliases.iter())
39                    .any(|n| haystack.contains(&normalise(n)))
40            })
41            .map(|p| p.name.clone())
42            .collect()
43    }
44
45    /// The SDK package a project on this platform starts with.
46    pub fn sdk_package<'r>(&self, registry: &'r Registry) -> Option<&'r PackageManifest> {
47        let name = match self.platform {
48            "python" => "offline-protocol-sdk",
49            "ios-native" => "offline-protocol-swift",
50            "android-native" => "offline-protocol-android",
51            "java" => "offline-protocol-java",
52            _ => return None,
53        };
54        registry.package(name)
55    }
56
57    /// How to add the SDK package to this project.
58    pub fn install_hint(&self, package: &PackageManifest) -> String {
59        match (&package.install, package.registry.as_str()) {
60            (Some(install), _) => install.clone(),
61            (None, "pypi") => format!("pip install {}=={}", package.name, package.version),
62            (None, _) => package.name.clone(),
63        }
64    }
65
66    /// Docs page for the SDK on this platform.
67    pub fn docs_url(&self) -> String {
68        let page = match self.platform {
69            "python" => "mesh-sdk/python",
70            "java" => "mesh-sdk/java",
71            _ => "mesh-sdk/native",
72        };
73        format!("{DOCS_BASE}/{page}")
74    }
75}
76
77/// Recognise a Swift, Gradle or Python project in `dir`. Returns `None` when
78/// none of their manifests is there. Callers check `package.json` first.
79pub fn detect_native(dir: &Path) -> Option<NativeProject> {
80    detect_swift(dir)
81        .or_else(|| detect_gradle(dir))
82        .or_else(|| detect_python(dir))
83}
84
85/// Message for a directory with no manifest `offline init` understands.
86pub fn unsupported_message(dir: &Path) -> String {
87    format!(
88        "no project found in {}: `offline init` looks for package.json (JavaScript/TypeScript), \
89pyproject.toml, requirements.txt or setup.py (Python), Package.swift or an .xcodeproj (Swift), \
90or settings.gradle / build.gradle (Kotlin or Java). For a new app, use `offline create`; \
91for other languages see {DOCS_BASE}/getting-started/platforms",
92        dir.display()
93    )
94}
95
96fn detect_python(dir: &Path) -> Option<NativeProject> {
97    let manifests = existing(
98        dir,
99        &[
100            "pyproject.toml",
101            "setup.py",
102            "setup.cfg",
103            "requirements.txt",
104            "Pipfile",
105        ],
106    );
107    if manifests.is_empty() {
108        return None;
109    }
110    let text = read_all(dir, &manifests);
111    let name = read(dir, "pyproject.toml")
112        .and_then(|t| toml_name(&t))
113        .or_else(|| read(dir, "setup.cfg").and_then(|t| key_value(&t, "name")))
114        .unwrap_or_else(|| folder_name(dir));
115    Some(NativeProject {
116        platform: "python",
117        language: "Python",
118        name,
119        manifests,
120        text,
121    })
122}
123
124fn detect_swift(dir: &Path) -> Option<NativeProject> {
125    let mut manifests = existing(dir, &["Package.swift", "Package.resolved"]);
126    let mut xcode_name = None;
127    for entry in std::fs::read_dir(dir).ok()?.flatten() {
128        let path = entry.path();
129        let ext = path.extension().and_then(|e| e.to_str());
130        if !matches!(ext, Some("xcodeproj") | Some("xcworkspace")) || !path.is_dir() {
131            continue;
132        }
133        if ext == Some("xcodeproj") && xcode_name.is_none() {
134            xcode_name = path
135                .file_stem()
136                .and_then(|s| s.to_str())
137                .map(str::to_string);
138        }
139        for inner in [
140            "project.pbxproj",
141            "project.xcworkspace/xcshareddata/swiftpm/Package.resolved",
142            "xcshareddata/swiftpm/Package.resolved",
143        ] {
144            let candidate = path.join(inner);
145            if candidate.is_file() {
146                if let Ok(rel) = candidate.strip_prefix(dir) {
147                    manifests.push(rel.to_path_buf());
148                }
149            }
150        }
151    }
152    if manifests.is_empty() && xcode_name.is_none() {
153        return None;
154    }
155    let text = read_all(dir, &manifests);
156    let name = read(dir, "Package.swift")
157        .and_then(|t| swift_package_name(&t))
158        .or(xcode_name)
159        .unwrap_or_else(|| folder_name(dir));
160    Some(NativeProject {
161        platform: "ios-native",
162        language: "Swift",
163        name,
164        manifests,
165        text,
166    })
167}
168
169fn detect_gradle(dir: &Path) -> Option<NativeProject> {
170    let manifests = existing(
171        dir,
172        &[
173            "settings.gradle.kts",
174            "settings.gradle",
175            "build.gradle.kts",
176            "build.gradle",
177            "app/build.gradle.kts",
178            "app/build.gradle",
179            "gradle/libs.versions.toml",
180        ],
181    );
182    if manifests.is_empty() {
183        return None;
184    }
185    let text = read_all(dir, &manifests);
186    let android = text.contains("com.android.application")
187        || text.contains("com.android.library")
188        || text.contains("android.application")
189        || text.contains("android.library");
190    let name = read(dir, "settings.gradle.kts")
191        .or_else(|| read(dir, "settings.gradle"))
192        .and_then(|t| key_value(&t, "rootProject.name"))
193        .unwrap_or_else(|| folder_name(dir));
194    Some(NativeProject {
195        platform: if android { "android-native" } else { "java" },
196        language: if text.contains("kotlin") {
197            "Kotlin"
198        } else {
199            "Java"
200        },
201        name,
202        manifests,
203        text,
204    })
205}
206
207fn existing(dir: &Path, names: &[&str]) -> Vec<PathBuf> {
208    names
209        .iter()
210        .map(PathBuf::from)
211        .filter(|p| dir.join(p).is_file())
212        .collect()
213}
214
215fn read(dir: &Path, name: &str) -> Option<String> {
216    std::fs::read_to_string(dir.join(name)).ok()
217}
218
219fn read_all(dir: &Path, files: &[PathBuf]) -> String {
220    files
221        .iter()
222        .filter_map(|f| std::fs::read_to_string(dir.join(f)).ok())
223        .collect::<Vec<_>>()
224        .join("\n")
225}
226
227fn folder_name(dir: &Path) -> String {
228    dir.canonicalize()
229        .ok()
230        .and_then(|p| p.file_name().and_then(|n| n.to_str()).map(str::to_string))
231        .unwrap_or_else(|| "offline-app".to_string())
232}
233
234/// Lowercase, with `_` and `.` read as `-`, so `offline_protocol_sdk` matches
235/// `offline-protocol-sdk` the way pip does.
236fn normalise(s: &str) -> String {
237    s.to_lowercase().replace(['_', '.'], "-")
238}
239
240/// `name = "x"` under `[project]` or `[tool.poetry]` in a pyproject.toml.
241fn toml_name(text: &str) -> Option<String> {
242    let mut in_section = false;
243    for line in text.lines() {
244        let line = line.trim();
245        if line.starts_with('[') {
246            in_section = line == "[project]" || line == "[tool.poetry]";
247            continue;
248        }
249        if in_section {
250            if let Some(v) = key_value(line, "name") {
251                return Some(v);
252            }
253        }
254    }
255    None
256}
257
258/// The value of `key = value` (quotes stripped) on the first line that sets it.
259fn key_value(text: &str, key: &str) -> Option<String> {
260    text.lines().find_map(|line| {
261        let (k, v) = line.trim().split_once('=')?;
262        if k.trim() != key {
263            return None;
264        }
265        let v = v.trim().trim_matches(|c| c == '"' || c == '\'').trim();
266        (!v.is_empty()).then(|| v.to_string())
267    })
268}
269
270/// `name: "X"` in the `Package(...)` of a Package.swift.
271fn swift_package_name(text: &str) -> Option<String> {
272    let start = text.find("Package(")?;
273    let rest = &text[start..];
274    let after = &rest[rest.find("name:")? + "name:".len()..];
275    let open = after.find('"')?;
276    let close = after[open + 1..].find('"')?;
277    Some(after[open + 1..open + 1 + close].to_string())
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    fn registry() -> Registry {
285        Registry::load_embedded().unwrap()
286    }
287
288    fn write(dir: &Path, name: &str, body: &str) {
289        let path = dir.join(name);
290        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
291        std::fs::write(path, body).unwrap();
292    }
293
294    #[test]
295    fn python_project_from_pyproject() {
296        let tmp = tempfile::tempdir().unwrap();
297        write(
298            tmp.path(),
299            "pyproject.toml",
300            "[build-system]\nrequires = [\"hatchling\"]\n\n[project]\nname = \"field-gateway\"\ndependencies = [\"offline_protocol_sdk>=0.33\"]\n",
301        );
302        let project = detect_native(tmp.path()).unwrap();
303        assert_eq!(project.platform, "python");
304        assert_eq!(project.name, "field-gateway");
305        assert_eq!(
306            project.installed_packages(&registry()),
307            ["offline-protocol-sdk"]
308        );
309    }
310
311    #[test]
312    fn python_project_without_the_sdk_gets_a_pip_hint() {
313        let tmp = tempfile::tempdir().unwrap();
314        write(tmp.path(), "requirements.txt", "requests==2.32.0\n");
315        let project = detect_native(tmp.path()).unwrap();
316        let registry = registry();
317        assert!(project.installed_packages(&registry).is_empty());
318        let sdk = project.sdk_package(&registry).unwrap();
319        assert!(project
320            .install_hint(sdk)
321            .starts_with("pip install offline-protocol-sdk=="));
322        assert!(project.docs_url().ends_with("/mesh-sdk/python"));
323    }
324
325    #[test]
326    fn swift_package_with_the_sdk() {
327        let tmp = tempfile::tempdir().unwrap();
328        write(
329            tmp.path(),
330            "Package.swift",
331            "// swift-tools-version:5.9\nimport PackageDescription\nlet package = Package(\n    name: \"TrailBeacon\",\n    dependencies: [.package(url: \"https://github.com/Offline-Protocol/offline-protocol-swift.git\", from: \"0.33.0\")]\n)\n",
332        );
333        let project = detect_native(tmp.path()).unwrap();
334        assert_eq!(project.platform, "ios-native");
335        assert_eq!(project.name, "TrailBeacon");
336        assert_eq!(
337            project.installed_packages(&registry()),
338            ["offline-protocol-swift"]
339        );
340    }
341
342    #[test]
343    fn xcode_project_name_comes_from_the_xcodeproj() {
344        let tmp = tempfile::tempdir().unwrap();
345        write(
346            tmp.path(),
347            "Muster.xcodeproj/project.pbxproj",
348            "// !$*UTF8*$!\n",
349        );
350        let project = detect_native(tmp.path()).unwrap();
351        assert_eq!(project.platform, "ios-native");
352        assert_eq!(project.language, "Swift");
353        assert_eq!(project.name, "Muster");
354    }
355
356    #[test]
357    fn android_kotlin_project() {
358        let tmp = tempfile::tempdir().unwrap();
359        write(
360            tmp.path(),
361            "settings.gradle.kts",
362            "rootProject.name = \"Relay Board\"\ninclude(\":app\")\n",
363        );
364        write(
365            tmp.path(),
366            "app/build.gradle.kts",
367            "plugins {\n    id(\"com.android.application\")\n    id(\"org.jetbrains.kotlin.android\")\n}\ndependencies {\n    implementation(\"com.offlineprotocol:offline-protocol-sdk:0.33.0\")\n}\n",
368        );
369        let project = detect_native(tmp.path()).unwrap();
370        assert_eq!(project.platform, "android-native");
371        assert_eq!(project.language, "Kotlin");
372        assert_eq!(project.name, "Relay Board");
373        assert_eq!(
374            project.installed_packages(&registry()),
375            ["offline-protocol-android"]
376        );
377    }
378
379    #[test]
380    fn plain_jvm_gradle_project_is_java_platform() {
381        let tmp = tempfile::tempdir().unwrap();
382        write(
383            tmp.path(),
384            "build.gradle.kts",
385            "plugins { kotlin(\"jvm\") version \"2.0.0\" }\n",
386        );
387        let project = detect_native(tmp.path()).unwrap();
388        assert_eq!(project.platform, "java");
389        assert_eq!(
390            project.sdk_package(&registry()).unwrap().name,
391            "offline-protocol-java"
392        );
393        assert!(project.docs_url().ends_with("/mesh-sdk/java"));
394    }
395
396    #[test]
397    fn empty_directory_is_not_a_project() {
398        let tmp = tempfile::tempdir().unwrap();
399        assert!(detect_native(tmp.path()).is_none());
400        assert!(unsupported_message(tmp.path()).contains("pyproject.toml"));
401    }
402}