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!("ios.sh");
const SCRIPT_PATH: &str = "Library/Caches/runnables/ios.sh";
#[derive(Debug, PartialEq)]
struct XcodeProject {
dir: PathBuf,
name: String,
container: String,
apps: Vec<String>,
tests: bool,
xcodegen: bool,
}
pub(crate) fn groups(
root: &Path,
specs: &[PathBuf],
projects: &[PathBuf],
workspaces: &[PathBuf],
) -> Vec<Group> {
if !cfg!(target_os = "macos") {
return Vec::new();
}
let found = find(specs, projects, workspaces);
if !found.is_empty() {
write_script();
}
found.iter().map(|project| group(root, project)).collect()
}
fn find(specs: &[PathBuf], projects: &[PathBuf], workspaces: &[PathBuf]) -> Vec<XcodeProject> {
let mut found = Vec::new();
for spec in specs {
let Some(dir) = spec.parent() else { continue };
let Ok(text) = fs::read_to_string(spec) else {
continue;
};
let Some((name, apps, tests)) = parse_xcodegen(&text) else {
continue;
};
found.push(XcodeProject {
dir: dir.to_path_buf(),
container: container(dir, &name, workspaces),
name,
apps,
tests,
xcodegen: true,
});
}
for project in projects {
let Some(dir) = project.parent() else {
continue;
};
if found.iter().any(|known| known.dir == dir) {
continue;
}
let Ok(text) = fs::read_to_string(project.join("project.pbxproj")) else {
continue;
};
let (apps, tests) = parse_pbxproj(&text);
if apps.is_empty() {
continue;
}
let name = stem(project);
found.push(XcodeProject {
dir: dir.to_path_buf(),
container: container(dir, &name, workspaces),
name,
apps,
tests,
xcodegen: false,
});
}
found.sort_by(|a, b| a.dir.cmp(&b.dir));
found
}
fn stem(path: &Path) -> String {
path.file_stem()
.map(|stem| stem.to_string_lossy().into_owned())
.unwrap_or_default()
}
fn container(dir: &Path, name: &str, workspaces: &[PathBuf]) -> String {
workspaces
.iter()
.filter(|workspace| workspace.parent() == Some(dir))
.min_by_key(|workspace| stem(workspace) != name)
.and_then(|workspace| workspace.file_name())
.map_or_else(
|| format!("{name}.xcodeproj"),
|file| file.to_string_lossy().into_owned(),
)
}
fn parse_xcodegen(text: &str) -> Option<(String, Vec<String>, bool)> {
let mut name = None;
let mut in_targets = false;
let mut targets: Vec<(String, bool, bool)> = Vec::new();
let mut tests = false;
for line in text.lines() {
let content = line.split(" #").next().unwrap_or("").trim_end();
if content.trim().is_empty() || content.trim_start().starts_with('#') {
continue;
}
let indent = content.len() - content.trim_start().len();
let content = content.trim();
if indent == 0 {
in_targets = content == "targets:";
if let Some(value) = content.strip_prefix("name:") {
name = Some(unquote(value));
}
continue;
}
if !in_targets {
continue;
}
if indent == 2 {
if let Some(target) = content.strip_suffix(':') {
targets.push((unquote(target), false, false));
}
continue;
}
let Some((_, app, ios)) = targets.last_mut() else {
continue;
};
if let Some(value) = content.strip_prefix("type:") {
let value = unquote(value);
*app = value == "application";
tests |=
value.starts_with("bundle.unit-test") || value.starts_with("bundle.ui-testing");
} else if let Some(value) = content.strip_prefix("platform:") {
*ios = value.contains("iOS");
} else if content.starts_with("supportedDestinations:") {
*ios |= content.contains("iOS");
} else if content == "- iOS" {
*ios = true;
}
}
let apps: Vec<String> = targets
.into_iter()
.filter(|(_, app, ios)| *app && *ios)
.map(|(target, _, _)| target)
.collect();
if apps.is_empty() {
return None;
}
Some((name?, apps, tests))
}
fn unquote(value: &str) -> String {
value.trim().trim_matches(['"', '\'']).to_string()
}
fn parse_pbxproj(text: &str) -> (Vec<String>, bool) {
if !text.contains("iphoneos") {
return (Vec::new(), false);
}
let tests = text.contains("com.apple.product-type.bundle.unit-test")
|| text.contains("com.apple.product-type.bundle.ui-testing");
let mut apps = Vec::new();
let mut object: Vec<&str> = Vec::new();
for line in text.lines() {
let trimmed = line.trim();
if trimmed.ends_with("= {") && line.starts_with("\t\t") && !line.starts_with("\t\t\t") {
object.clear();
}
object.push(trimmed);
if trimmed == "};" && line.starts_with("\t\t") && !line.starts_with("\t\t\t") {
let native = object.contains(&"isa = PBXNativeTarget;");
let app = object.contains(&"productType = \"com.apple.product-type.application\";");
let name = object.iter().find_map(|line| {
line.strip_prefix("name = ")
.and_then(|rest| rest.strip_suffix(';'))
.map(unquote)
});
if let (true, true, Some(name)) = (native, app, name) {
apps.push(name);
}
object.clear();
}
}
(apps, tests)
}
fn script_command() -> String {
format!("sh ~/{SCRIPT_PATH}")
}
fn write_script() {
let Some(home) = std::env::var_os("HOME") else {
return;
};
let path = Path::new(&home).join(SCRIPT_PATH);
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: &XcodeProject) -> Group {
let place = relative(root, &project.dir);
let script = script_command();
let container = quote(&project.container);
let command = |mode: &str, scheme: &str| {
in_dir(
root,
&project.dir,
format!("{script} {mode} {container} {}", quote(scheme)),
)
};
let several = project.apps.len() > 1;
let mut tasks = Vec::new();
for app in &project.apps {
let suffix = if several {
format!(" · {app}")
} else {
String::new()
};
tasks.push(RunTask::new(
format!("ios:{place}:{app}:simulator"),
app,
&format!("Run on Simulator{suffix}"),
command("simulator", app),
TaskIcon::Run,
));
tasks.push(RunTask::new(
format!("ios:{place}:{app}:device"),
app,
&format!("Run on Device{suffix}"),
command("device", app),
TaskIcon::Device,
));
tasks.push(
RunTask::new(
format!("ios:{place}:{app}:archive"),
app,
&format!("Build Release{suffix}"),
command("archive", app),
TaskIcon::Release,
)
.one_shot(),
);
}
if project.tests {
let scheme = &project.apps[0];
tasks.push(
RunTask::new(
format!("ios:{place}:{scheme}:test"),
"Tests",
"Test on Simulator",
command("test", scheme),
TaskIcon::Test,
)
.one_shot(),
);
}
tasks.push(
RunTask::new(
format!("ios:{place}:xcode"),
&project.name,
"Open in Xcode",
command("xcode", &project.apps[0]),
TaskIcon::Open,
)
.one_shot(),
);
Group {
title: project.name.clone(),
detail: if project.xcodegen {
"iOS · XcodeGen".into()
} else {
"iOS · Xcode".into()
},
kind: ProjectKind::Mobile,
tasks,
incidental: is_incidental(&place),
main: true,
dir: crate::folder(place),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn xcodegen_lists_ios_apps_and_skips_extensions() {
let spec = "name: Rustedit\noptions:\n bundleIdPrefix: dev.rustedit\ntargets:\n Rustedit:\n type: application\n platform: iOS\n sources:\n - path: App\n RusteditNotifications:\n type: app-extension\n platform: iOS\n RusteditUITests:\n type: bundle.ui-testing\n platform: iOS\n MacTool:\n type: application\n platform: macOS\n";
let (name, apps, tests) = parse_xcodegen(spec).unwrap();
assert_eq!(name, "Rustedit");
assert_eq!(apps, ["Rustedit"]);
assert!(tests);
assert!(
parse_xcodegen("name: Tool\ntargets:\n Tool:\n type: tool\n platform: macOS\n")
.is_none()
);
}
#[test]
fn pbxproj_lists_application_targets() {
let text = "\t\tAAA /* Shop */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tname = Shop;\n\t\t\tproductType = \"com.apple.product-type.application\";\n\t\t};\n\t\tBBB /* Widget */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tname = Widget;\n\t\t\tproductType = \"com.apple.product-type.app-extension\";\n\t\t};\n\t\t\t\tSDKROOT = iphoneos;\n";
assert_eq!(parse_pbxproj(text), (vec!["Shop".to_string()], false));
assert!(
parse_pbxproj(&text.replace("iphoneos", "macosx"))
.0
.is_empty()
);
}
#[test]
fn a_workspace_next_to_the_project_wins() {
let dir = Path::new("/r/app");
let workspaces = [
dir.join("Shop.xcworkspace"),
PathBuf::from("/r/Other.xcworkspace"),
];
assert_eq!(container(dir, "Shop", &workspaces), "Shop.xcworkspace");
assert_eq!(container(dir, "Shop", &workspaces[1..]), "Shop.xcodeproj");
}
#[test]
fn tasks_run_the_script_in_the_project_folder() {
let project = XcodeProject {
dir: PathBuf::from("/r/ios"),
name: "Rustedit".into(),
container: "Rustedit.xcodeproj".into(),
apps: vec!["Rustedit".into()],
tests: true,
xcodegen: true,
};
let group = group(Path::new("/r"), &project);
assert_eq!(group.detail, "iOS · XcodeGen");
let labels: Vec<_> = group.tasks.iter().map(|task| task.label.as_str()).collect();
assert_eq!(
labels,
[
"Run on Simulator",
"Run on Device",
"Build Release",
"Test on Simulator",
"Open in Xcode"
]
);
assert_eq!(
group.tasks[0].command,
crate::in_dir(
Path::new("/r"),
Path::new("/r/ios"),
"sh ~/Library/Caches/runnables/ios.sh simulator Rustedit.xcodeproj Rustedit".into()
)
);
assert!(!group.tasks[1].one_shot);
assert!(group.tasks[3].one_shot);
}
}