offline-generator 0.4.0

Project scaffolding engine for the Offline Protocol CLI (Tera-based)
Documentation
//! Recognise an existing Python, Swift or Gradle (Kotlin/Java) project, so
//! `offline init` and the MCP `init_project` tool can wire projects that have
//! no `package.json`.
//!
//! Detection only reads files: the manifest names the platform, the project
//! name comes from the manifest or the folder, and an Offline Protocol package
//! counts as installed when its name or an alias appears in a manifest.

use std::path::{Path, PathBuf};

use offline_registry::{PackageManifest, Registry};

const DOCS_BASE: &str = "https://www.offlineprotocol.com/docs";

/// A non-JavaScript project found in a directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeProject {
    /// Registry platform: `python`, `ios-native`, `android-native` or `java`.
    pub platform: &'static str,
    /// Human name of the toolchain, for messages (`Python`, `Swift`, ...).
    pub language: &'static str,
    /// Project name from the manifest, else the folder name.
    pub name: String,
    /// Manifest files that were read, relative to the project directory.
    pub manifests: Vec<PathBuf>,
    text: String,
}

impl NativeProject {
    /// Registry packages for this platform that the manifests mention.
    pub fn installed_packages(&self, registry: &Registry) -> Vec<String> {
        let haystack = normalise(&self.text);
        registry
            .packages()
            .filter(|p| p.platforms.iter().any(|pl| pl == self.platform))
            .filter(|p| {
                std::iter::once(&p.name)
                    .chain(p.aliases.iter())
                    .any(|n| haystack.contains(&normalise(n)))
            })
            .map(|p| p.name.clone())
            .collect()
    }

    /// The SDK package a project on this platform starts with.
    pub fn sdk_package<'r>(&self, registry: &'r Registry) -> Option<&'r PackageManifest> {
        let name = match self.platform {
            "python" => "offline-protocol-sdk",
            "ios-native" => "offline-protocol-swift",
            "android-native" => "offline-protocol-android",
            "java" => "offline-protocol-java",
            _ => return None,
        };
        registry.package(name)
    }

    /// How to add the SDK package to this project.
    pub fn install_hint(&self, package: &PackageManifest) -> String {
        match (&package.install, package.registry.as_str()) {
            (Some(install), _) => install.clone(),
            (None, "pypi") => format!("pip install {}=={}", package.name, package.version),
            (None, _) => package.name.clone(),
        }
    }

    /// Docs page for the SDK on this platform.
    pub fn docs_url(&self) -> String {
        let page = match self.platform {
            "python" => "mesh-sdk/python",
            "java" => "mesh-sdk/java",
            _ => "mesh-sdk/native",
        };
        format!("{DOCS_BASE}/{page}")
    }
}

/// Recognise a Swift, Gradle or Python project in `dir`. Returns `None` when
/// none of their manifests is there. Callers check `package.json` first.
pub fn detect_native(dir: &Path) -> Option<NativeProject> {
    detect_swift(dir)
        .or_else(|| detect_gradle(dir))
        .or_else(|| detect_python(dir))
}

/// Message for a directory with no manifest `offline init` understands.
pub fn unsupported_message(dir: &Path) -> String {
    format!(
        "no project found in {}: `offline init` looks for package.json (JavaScript/TypeScript), \
pyproject.toml, requirements.txt or setup.py (Python), Package.swift or an .xcodeproj (Swift), \
or settings.gradle / build.gradle (Kotlin or Java). For a new app, use `offline create`; \
for other languages see {DOCS_BASE}/getting-started/platforms",
        dir.display()
    )
}

fn detect_python(dir: &Path) -> Option<NativeProject> {
    let manifests = existing(
        dir,
        &[
            "pyproject.toml",
            "setup.py",
            "setup.cfg",
            "requirements.txt",
            "Pipfile",
        ],
    );
    if manifests.is_empty() {
        return None;
    }
    let text = read_all(dir, &manifests);
    let name = read(dir, "pyproject.toml")
        .and_then(|t| toml_name(&t))
        .or_else(|| read(dir, "setup.cfg").and_then(|t| key_value(&t, "name")))
        .unwrap_or_else(|| folder_name(dir));
    Some(NativeProject {
        platform: "python",
        language: "Python",
        name,
        manifests,
        text,
    })
}

fn detect_swift(dir: &Path) -> Option<NativeProject> {
    let mut manifests = existing(dir, &["Package.swift", "Package.resolved"]);
    let mut xcode_name = None;
    for entry in std::fs::read_dir(dir).ok()?.flatten() {
        let path = entry.path();
        let ext = path.extension().and_then(|e| e.to_str());
        if !matches!(ext, Some("xcodeproj") | Some("xcworkspace")) || !path.is_dir() {
            continue;
        }
        if ext == Some("xcodeproj") && xcode_name.is_none() {
            xcode_name = path
                .file_stem()
                .and_then(|s| s.to_str())
                .map(str::to_string);
        }
        for inner in [
            "project.pbxproj",
            "project.xcworkspace/xcshareddata/swiftpm/Package.resolved",
            "xcshareddata/swiftpm/Package.resolved",
        ] {
            let candidate = path.join(inner);
            if candidate.is_file() {
                if let Ok(rel) = candidate.strip_prefix(dir) {
                    manifests.push(rel.to_path_buf());
                }
            }
        }
    }
    if manifests.is_empty() && xcode_name.is_none() {
        return None;
    }
    let text = read_all(dir, &manifests);
    let name = read(dir, "Package.swift")
        .and_then(|t| swift_package_name(&t))
        .or(xcode_name)
        .unwrap_or_else(|| folder_name(dir));
    Some(NativeProject {
        platform: "ios-native",
        language: "Swift",
        name,
        manifests,
        text,
    })
}

fn detect_gradle(dir: &Path) -> Option<NativeProject> {
    let manifests = existing(
        dir,
        &[
            "settings.gradle.kts",
            "settings.gradle",
            "build.gradle.kts",
            "build.gradle",
            "app/build.gradle.kts",
            "app/build.gradle",
            "gradle/libs.versions.toml",
        ],
    );
    if manifests.is_empty() {
        return None;
    }
    let text = read_all(dir, &manifests);
    let android = text.contains("com.android.application")
        || text.contains("com.android.library")
        || text.contains("android.application")
        || text.contains("android.library");
    let name = read(dir, "settings.gradle.kts")
        .or_else(|| read(dir, "settings.gradle"))
        .and_then(|t| key_value(&t, "rootProject.name"))
        .unwrap_or_else(|| folder_name(dir));
    Some(NativeProject {
        platform: if android { "android-native" } else { "java" },
        language: if text.contains("kotlin") {
            "Kotlin"
        } else {
            "Java"
        },
        name,
        manifests,
        text,
    })
}

fn existing(dir: &Path, names: &[&str]) -> Vec<PathBuf> {
    names
        .iter()
        .map(PathBuf::from)
        .filter(|p| dir.join(p).is_file())
        .collect()
}

fn read(dir: &Path, name: &str) -> Option<String> {
    std::fs::read_to_string(dir.join(name)).ok()
}

fn read_all(dir: &Path, files: &[PathBuf]) -> String {
    files
        .iter()
        .filter_map(|f| std::fs::read_to_string(dir.join(f)).ok())
        .collect::<Vec<_>>()
        .join("\n")
}

fn folder_name(dir: &Path) -> String {
    dir.canonicalize()
        .ok()
        .and_then(|p| p.file_name().and_then(|n| n.to_str()).map(str::to_string))
        .unwrap_or_else(|| "offline-app".to_string())
}

/// Lowercase, with `_` and `.` read as `-`, so `offline_protocol_sdk` matches
/// `offline-protocol-sdk` the way pip does.
fn normalise(s: &str) -> String {
    s.to_lowercase().replace(['_', '.'], "-")
}

/// `name = "x"` under `[project]` or `[tool.poetry]` in a pyproject.toml.
fn toml_name(text: &str) -> Option<String> {
    let mut in_section = false;
    for line in text.lines() {
        let line = line.trim();
        if line.starts_with('[') {
            in_section = line == "[project]" || line == "[tool.poetry]";
            continue;
        }
        if in_section {
            if let Some(v) = key_value(line, "name") {
                return Some(v);
            }
        }
    }
    None
}

/// The value of `key = value` (quotes stripped) on the first line that sets it.
fn key_value(text: &str, key: &str) -> Option<String> {
    text.lines().find_map(|line| {
        let (k, v) = line.trim().split_once('=')?;
        if k.trim() != key {
            return None;
        }
        let v = v.trim().trim_matches(|c| c == '"' || c == '\'').trim();
        (!v.is_empty()).then(|| v.to_string())
    })
}

/// `name: "X"` in the `Package(...)` of a Package.swift.
fn swift_package_name(text: &str) -> Option<String> {
    let start = text.find("Package(")?;
    let rest = &text[start..];
    let after = &rest[rest.find("name:")? + "name:".len()..];
    let open = after.find('"')?;
    let close = after[open + 1..].find('"')?;
    Some(after[open + 1..open + 1 + close].to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn registry() -> Registry {
        Registry::load_embedded().unwrap()
    }

    fn write(dir: &Path, name: &str, body: &str) {
        let path = dir.join(name);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, body).unwrap();
    }

    #[test]
    fn python_project_from_pyproject() {
        let tmp = tempfile::tempdir().unwrap();
        write(
            tmp.path(),
            "pyproject.toml",
            "[build-system]\nrequires = [\"hatchling\"]\n\n[project]\nname = \"field-gateway\"\ndependencies = [\"offline_protocol_sdk>=0.33\"]\n",
        );
        let project = detect_native(tmp.path()).unwrap();
        assert_eq!(project.platform, "python");
        assert_eq!(project.name, "field-gateway");
        assert_eq!(
            project.installed_packages(&registry()),
            ["offline-protocol-sdk"]
        );
    }

    #[test]
    fn python_project_without_the_sdk_gets_a_pip_hint() {
        let tmp = tempfile::tempdir().unwrap();
        write(tmp.path(), "requirements.txt", "requests==2.32.0\n");
        let project = detect_native(tmp.path()).unwrap();
        let registry = registry();
        assert!(project.installed_packages(&registry).is_empty());
        let sdk = project.sdk_package(&registry).unwrap();
        assert!(project
            .install_hint(sdk)
            .starts_with("pip install offline-protocol-sdk=="));
        assert!(project.docs_url().ends_with("/mesh-sdk/python"));
    }

    #[test]
    fn swift_package_with_the_sdk() {
        let tmp = tempfile::tempdir().unwrap();
        write(
            tmp.path(),
            "Package.swift",
            "// 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",
        );
        let project = detect_native(tmp.path()).unwrap();
        assert_eq!(project.platform, "ios-native");
        assert_eq!(project.name, "TrailBeacon");
        assert_eq!(
            project.installed_packages(&registry()),
            ["offline-protocol-swift"]
        );
    }

    #[test]
    fn xcode_project_name_comes_from_the_xcodeproj() {
        let tmp = tempfile::tempdir().unwrap();
        write(
            tmp.path(),
            "Muster.xcodeproj/project.pbxproj",
            "// !$*UTF8*$!\n",
        );
        let project = detect_native(tmp.path()).unwrap();
        assert_eq!(project.platform, "ios-native");
        assert_eq!(project.language, "Swift");
        assert_eq!(project.name, "Muster");
    }

    #[test]
    fn android_kotlin_project() {
        let tmp = tempfile::tempdir().unwrap();
        write(
            tmp.path(),
            "settings.gradle.kts",
            "rootProject.name = \"Relay Board\"\ninclude(\":app\")\n",
        );
        write(
            tmp.path(),
            "app/build.gradle.kts",
            "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",
        );
        let project = detect_native(tmp.path()).unwrap();
        assert_eq!(project.platform, "android-native");
        assert_eq!(project.language, "Kotlin");
        assert_eq!(project.name, "Relay Board");
        assert_eq!(
            project.installed_packages(&registry()),
            ["offline-protocol-android"]
        );
    }

    #[test]
    fn plain_jvm_gradle_project_is_java_platform() {
        let tmp = tempfile::tempdir().unwrap();
        write(
            tmp.path(),
            "build.gradle.kts",
            "plugins { kotlin(\"jvm\") version \"2.0.0\" }\n",
        );
        let project = detect_native(tmp.path()).unwrap();
        assert_eq!(project.platform, "java");
        assert_eq!(
            project.sdk_package(&registry()).unwrap().name,
            "offline-protocol-java"
        );
        assert!(project.docs_url().ends_with("/mesh-sdk/java"));
    }

    #[test]
    fn empty_directory_is_not_a_project() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(detect_native(tmp.path()).is_none());
        assert!(unsupported_message(tmp.path()).contains("pyproject.toml"));
    }
}