runnables 0.1.0

What a folder can run: apps, tests, watchers, simulators, databases and deploys, found from its files. A library, a CLI, and an MCP server for coding agents.
Documentation
// Copyright (c) Pavel Sich.
// Licensed under the MIT License.

//! Android apps: a Gradle project whose modules apply the Android application
//! plugin. Each runs through `android.sh`, which picks the emulator or the
//! connected device when it starts, since either can change after the scan.

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

use super::{Group, ProjectKind, RunTask, TaskIcon, in_dir, is_incidental, quote, relative};

const SCRIPT: &str = include_str!("android.sh");

/// One Gradle build and its app modules.
#[derive(Debug, PartialEq)]
struct GradleProject {
    dir: PathBuf,
    name: String,
    apps: Vec<AppModule>,
}

#[derive(Debug, PartialEq)]
struct AppModule {
    /// The Gradle path, like `:app`.
    path: String,
    /// Whether it has instrumented tests to run on a device.
    tests: bool,
}

pub(crate) fn groups(root: &Path, settings: &[PathBuf]) -> Vec<Group> {
    // The script is POSIX sh; Windows runs it with Git for Windows' bash.
    if cfg!(windows) && git_bash().is_none() {
        return Vec::new();
    }
    let found: Vec<GradleProject> = settings.iter().filter_map(|file| find(file)).collect();
    if !found.is_empty() {
        write_script();
    }
    found.iter().map(|project| group(root, project)).collect()
}

fn find(settings: &Path) -> Option<GradleProject> {
    let dir = settings.parent()?;
    let text = fs::read_to_string(settings).ok()?;
    let (name, modules) = parse_settings(&text);
    let apps: Vec<AppModule> = modules
        .into_iter()
        .filter_map(|path| {
            let module_dir = dir.join(path.trim_start_matches(':').replace(':', "/"));
            is_app(&module_dir).then(|| AppModule {
                tests: module_dir.join("src/androidTest").is_dir(),
                path,
            })
        })
        .collect();
    if apps.is_empty() {
        return None;
    }
    let name = name.unwrap_or_else(|| {
        dir.file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_default()
    });
    Some(GradleProject {
        dir: dir.to_path_buf(),
        name,
        apps,
    })
}

/// `rootProject.name` and every module `include` names, like `:app`.
fn parse_settings(text: &str) -> (Option<String>, Vec<String>) {
    let mut name = None;
    let mut modules = Vec::new();
    let mut in_include = false;
    for line in text.lines() {
        let line = line.split("//").next().unwrap_or("").trim();
        if let Some(rest) = line.strip_prefix("rootProject.name") {
            let value = rest.trim_start().trim_start_matches('=').trim();
            name = quoted(value).into_iter().next();
            continue;
        }
        let starts = line.starts_with("include(") || line.starts_with("include ");
        if !starts && !in_include {
            continue;
        }
        modules.extend(
            quoted(line)
                .into_iter()
                .filter(|module| module.starts_with(':')),
        );
        in_include = if starts {
            line.contains('(') && !line.contains(')')
        } else {
            !line.contains(')')
        };
    }
    (name, modules)
}

/// The strings in quotes on a line.
fn quoted(line: &str) -> Vec<String> {
    let mut found = Vec::new();
    let mut rest = line;
    while let Some(start) = rest.find(['"', '\'']) {
        let quote = rest.as_bytes()[start] as char;
        let after = &rest[start + 1..];
        let Some(end) = after.find(quote) else { break };
        found.push(after[..end].to_string());
        rest = &after[end + 1..];
    }
    found
}

/// Whether the module's build file applies the Android application plugin,
/// by its id or by a version catalog alias like `libs.plugins.android.application`.
fn is_app(dir: &Path) -> bool {
    ["build.gradle.kts", "build.gradle"].iter().any(|file| {
        fs::read_to_string(dir.join(file)).is_ok_and(|text| {
            text.lines().any(|line| {
                let line = line.split("//").next().unwrap_or("");
                let plain: String = line
                    .chars()
                    .filter(|ch| !".-_".contains(*ch))
                    .collect::<String>()
                    .to_lowercase();
                plain.contains("androidapplication")
            })
        })
    })
}

/// Where the script is kept: the user's cache folder.
fn script_path() -> Option<PathBuf> {
    let var = |name: &str| std::env::var_os(name).map(PathBuf::from);
    let cache = if cfg!(target_os = "macos") {
        var("HOME")?.join("Library/Caches")
    } else if cfg!(windows) {
        var("LOCALAPPDATA")?
    } else {
        var("XDG_CACHE_HOME").or_else(|| var("HOME").map(|home| home.join(".cache")))?
    };
    Some(cache.join("runnables").join("android.sh"))
}

/// Git for Windows' bash, beside its `git.exe`. Never `System32\bash.exe`,
/// which starts WSL.
pub fn git_bash() -> Option<PathBuf> {
    let from_git = super::find_executable("git", &[])
        .and_then(|git| Some(git.parent()?.parent()?.join("bin").join("bash.exe")));
    let installed = std::env::var_os("ProgramFiles")
        .map(|programs| PathBuf::from(programs).join("Git").join("bin").join("bash.exe"));
    [from_git, installed].into_iter().flatten().find(|bash| bash.is_file())
}

fn script_command() -> String {
    if cfg!(target_os = "macos") {
        return "sh ~/Library/Caches/runnables/android.sh".into();
    }
    let path = script_path().map_or_else(
        || "~/.cache/runnables/android.sh".into(),
        |path| quote(&path.to_string_lossy()),
    );
    match cfg!(windows).then(git_bash).flatten() {
        Some(bash) => format!("& {} {path}", quote(&bash.to_string_lossy())),
        None => format!("sh {path}"),
    }
}

fn write_script() {
    let Some(path) = script_path() else {
        return;
    };
    if fs::read_to_string(&path).is_ok_and(|text| text == SCRIPT) {
        return;
    }
    if let Some(dir) = path.parent() {
        _ = fs::create_dir_all(dir);
    }
    _ = fs::write(&path, SCRIPT);
}

fn group(root: &Path, project: &GradleProject) -> Group {
    let place = relative(root, &project.dir);
    let script = script_command();
    let command = |mode: &str, module: &str| {
        in_dir(
            root,
            &project.dir,
            format!("{script} {mode} {}", quote(module)),
        )
    };
    let several = project.apps.len() > 1;
    let mut tasks = Vec::new();
    for app in &project.apps {
        let module = app.path.trim_start_matches(':');
        let suffix = if several {
            format!(" ยท {module}")
        } else {
            String::new()
        };
        tasks.push(RunTask::new(
            format!("android:{place}:{module}:emulator"),
            module,
            &format!("Run on Emulator{suffix}"),
            command("emulator", &app.path),
            TaskIcon::Run,
        ));
        tasks.push(RunTask::new(
            format!("android:{place}:{module}:device"),
            module,
            &format!("Run on Device{suffix}"),
            command("device", &app.path),
            TaskIcon::Device,
        ));
        tasks.push(
            RunTask::new(
                format!("android:{place}:{module}:release"),
                module,
                &format!("Build Release{suffix}"),
                command("release", &app.path),
                TaskIcon::Release,
            )
            .one_shot(),
        );
    }
    for app in project.apps.iter().filter(|app| app.tests) {
        let module = app.path.trim_start_matches(':');
        let suffix = if several {
            format!(" ยท {module}")
        } else {
            String::new()
        };
        tasks.push(
            RunTask::new(
                format!("android:{place}:{module}:test"),
                "Tests",
                &format!("Test on Emulator{suffix}"),
                command("test", &app.path),
                TaskIcon::Test,
            )
            .one_shot(),
        );
    }
    tasks.push(
        RunTask::new(
            format!("android:{place}:studio"),
            &project.name,
            "Open in Android Studio",
            command("studio", &project.apps[0].path),
            TaskIcon::Open,
        )
        .one_shot(),
    );
    Group {
        title: project.name.clone(),
        detail: "Android ยท Gradle".into(),
        kind: ProjectKind::Mobile,
        tasks,
        incidental: is_incidental(&place),
        main: true,
        dir: crate::folder(place),
    }
}

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

    #[test]
    fn settings_name_the_project_and_its_modules() {
        let kts = "pluginManagement {\n    repositories { google() }\n}\nrootProject.name = \"Rustedit\"\ninclude(\":remotekit\", \":app\")\n";
        assert_eq!(
            parse_settings(kts),
            (
                Some("Rustedit".into()),
                vec![":remotekit".into(), ":app".into()]
            )
        );
        let groovy = "rootProject.name = 'Shop'\ninclude ':app', ':core:data'\n// include ':old'\ninclude(\n    \":wear\",\n    \":tv\"\n)\n";
        assert_eq!(
            parse_settings(groovy),
            (
                Some("Shop".into()),
                vec![
                    ":app".into(),
                    ":core:data".into(),
                    ":wear".into(),
                    ":tv".into()
                ]
            )
        );
    }

    #[test]
    fn finds_app_modules_and_their_tests() {
        let root = std::env::temp_dir().join(format!("edit-run-android-{}", std::process::id()));
        let app = root.join("app");
        let lib = root.join("core/data");
        fs::create_dir_all(app.join("src/androidTest")).unwrap();
        fs::create_dir_all(&lib).unwrap();
        fs::write(
            root.join("settings.gradle.kts"),
            "rootProject.name = \"Shop\"\ninclude(\":app\", \":core:data\")\n",
        )
        .unwrap();
        fs::write(
            app.join("build.gradle.kts"),
            "plugins {\n    alias(libs.plugins.android.application)\n}\n",
        )
        .unwrap();
        fs::write(
            lib.join("build.gradle"),
            "plugins {\n    id 'com.android.library'\n}\n",
        )
        .unwrap();
        let project = find(&root.join("settings.gradle.kts")).unwrap();
        _ = fs::remove_dir_all(&root);
        assert_eq!(project.name, "Shop");
        assert_eq!(
            project.apps,
            [AppModule {
                path: ":app".into(),
                tests: true
            }]
        );
    }

    #[test]
    fn tasks_run_the_script_in_the_project_folder() {
        let project = GradleProject {
            dir: PathBuf::from("/r/android"),
            name: "Rustedit".into(),
            apps: vec![AppModule {
                path: ":app".into(),
                tests: true,
            }],
        };
        let group = group(Path::new("/r"), &project);
        assert_eq!(group.detail, "Android ยท Gradle");
        let labels: Vec<_> = group.tasks.iter().map(|task| task.label.as_str()).collect();
        assert_eq!(
            labels,
            [
                "Run on Emulator",
                "Run on Device",
                "Build Release",
                "Test on Emulator",
                "Open in Android Studio"
            ]
        );
        let command = &group.tasks[0].command;
        if crate::POWERSHELL {
            // Git for Windows' bash runs the script, in the project's folder.
            assert!(command.starts_with("Push-Location -LiteralPath android; try { & "), "{command}");
            assert!(command.contains("android.sh' emulator :app }"), "{command}");
        } else {
            assert!(command.starts_with("(cd android && sh "), "{command}");
            assert!(command.ends_with("runnables/android.sh emulator :app)"), "{command}");
        }
        assert!(!group.tasks[1].one_shot);
        assert!(group.tasks[3].one_shot);
    }
}