alef 0.81.0

Opinionated polyglot binding generator for Rust libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use super::resolve_workspace_root;
use crate::backends::php::layout::{php_package_psr4_target, php_psr4_target};
use crate::core::config::ResolvedCrateConfig;
use crate::core::config::extras::Language;
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

/// Validate that all package manifests are ready for publishing.
///
/// Checks:
/// - All required package directories exist
/// - Key manifest files are present (pyproject.toml, package.json, gemspec, etc.)
/// - Cargo.toml version can be read
pub fn validate(config: &ResolvedCrateConfig, languages: &[Language]) -> Result<Vec<String>> {
    let mut issues = Vec::new();
    let workspace_root = resolve_workspace_root(config);
    let workspace_path = Path::new(&workspace_root);

    if config.resolved_version().is_none() {
        issues.push(format!("cannot read version from {}", config.version_from));
    }

    for &lang in languages {
        let pkg_dir = config.package_dir(lang);
        let pkg_path = workspace_path.join(&pkg_dir);

        if matches!(lang, Language::Rust | Language::Ffi | Language::Jni) {
            continue;
        }

        if !pkg_path.exists() {
            issues.push(format!("{lang}: package directory {pkg_dir} does not exist"));
            continue;
        }

        let expected_files: Vec<&str> = match lang {
            Language::Python => vec!["pyproject.toml"],
            Language::Node => vec!["package.json"],
            Language::Ruby => vec![],
            // ~keep PHP has NO package-local manifest to require. `scaffold_php` emits exactly one
            // `composer.json` per layout (c159e2dc0), and the layout a real consumer resolves is
            // always the co-located one: that branch keys off `output_paths.contains_key("php")`,
            // and `resolve_output_paths` inserts an entry for every ENABLED language, so the key is
            // present whenever php is enabled -- which `resolve_languages` requires before php can
            // be generated at all. Requiring `{pkg_dir}/composer.json` here therefore reported a
            // file the generator no longer writes: it failed every repository that had been
            // regenerated since c159e2dc0, and passed only where a pre-c159e2dc0 leftover happened
            // to survive. The manifest that does exist is the repository-root one, and
            // `validate_php_manifests` is what checks it.
            Language::Php => vec![],
            Language::Elixir => vec!["mix.exs"],
            Language::Go => vec!["go.mod"],
            Language::Java => vec!["pom.xml"],
            Language::Csharp => vec![],
            Language::Wasm => vec![],
            Language::R => vec!["DESCRIPTION"],
            Language::Kotlin => vec!["build.gradle.kts"],
            Language::Gleam => vec!["gleam.toml"],
            Language::Zig => vec!["build.zig"],
            Language::Dart => vec!["pubspec.yaml"],
            Language::Swift => vec!["Package.swift"],
            _ => vec![],
        };

        for file in expected_files {
            if !pkg_path.join(file).exists() {
                issues.push(format!("{lang}: missing {pkg_dir}/{file}"));
            }
        }

        if lang == Language::Ruby {
            validate_ruby_gemspecs(&pkg_path, &pkg_dir, &mut issues);
        }
        validate_language_manifest(config, lang, workspace_path, &pkg_dir, &pkg_path, &mut issues);
    }

    Ok(issues)
}

fn validate_language_manifest(
    config: &ResolvedCrateConfig,
    lang: Language,
    workspace_root: &Path,
    pkg_dir: &str,
    pkg_path: &Path,
    issues: &mut Vec<String>,
) {
    match lang {
        Language::Elixir => validate_elixir_manifest(config, pkg_dir, pkg_path, issues),
        Language::Php => validate_php_manifests(config, pkg_dir, pkg_path, workspace_root, issues),
        Language::Csharp => validate_csharp_project(config, workspace_root, pkg_dir, issues),
        Language::Go => validate_go_module(config, pkg_dir, pkg_path, issues),
        Language::Java => validate_java_manifest(config, pkg_dir, pkg_path, issues),
        Language::Dart => validate_dart_manifest(config, pkg_dir, pkg_path, issues),
        Language::Swift => validate_swift_manifest(pkg_dir, pkg_path, issues),
        Language::Zig => validate_zig_manifest(config, pkg_dir, pkg_path, issues),
        _ => {}
    }
}

fn validate_elixir_manifest(config: &ResolvedCrateConfig, pkg_dir: &str, pkg_path: &Path, issues: &mut Vec<String>) {
    let mix_path = pkg_path.join("mix.exs");
    let Ok(content) = std::fs::read_to_string(&mix_path) else {
        return;
    };
    let expected = elixir_nif_targets(config);
    if parse_mix_nif_targets(&content).as_deref() != Some(expected.as_slice()) {
        issues.push(format!(
            "elixir: {pkg_dir}/mix.exs rustler_crates targets must match configured nif_targets: {targets}",
            targets = expected.join(" ")
        ));
    }
}

/// Extract the `rustler_crates` NIF target list from a `mix.exs`.
///
/// The Elixir scaffold renders the list as a multi-line list of quoted strings
/// (`targets: [\n  "aarch64-apple-darwin",\n  ...\n]`), so a literal comparison against a
/// single-line `~w(...)` sigil never matches generated output. Both spellings are accepted
/// here: the sigil form still appears in hand-maintained manifests predating the scaffold.
fn parse_mix_nif_targets(content: &str) -> Option<Vec<String>> {
    let after_crates = content.split_once("rustler_crates")?.1;
    let after_targets = after_crates.split_once("targets:")?.1.trim_start();

    if let Some(sigil_body) = after_targets.strip_prefix("~w(") {
        let inner = sigil_body.split_once(')')?.0;
        return Some(inner.split_whitespace().map(str::to_string).collect());
    }

    let list_body = after_targets.strip_prefix('[')?;
    let inner = list_body.split_once(']')?.0;
    Some(
        inner
            .split(',')
            .map(|entry| entry.trim().trim_matches('"').to_string())
            .filter(|entry| !entry.is_empty())
            .collect(),
    )
}

/// Validate the `composer.json` a PHP layout actually has, plus any package-local manifest that
/// is still on disk.
///
/// ~keep The repository-root manifest is read FIRST and checked unconditionally. This function
/// used to bail out early when `{pkg_dir}/composer.json` could not be read, and since
/// `scaffold_php` stopped emitting that file for the co-located layout (c159e2dc0) -- the only
/// layout a real consumer resolves -- every check below that early `return` silently never ran:
/// the missing-root report, the root PSR-4 check, and the root/package metadata comparison alike.
/// The root manifest is the published package (Packagist reads the repository root), so it is the
/// one this must never skip.
///
/// The package-local block stays conditional on the file being present, and that is not the same
/// dead branch: the co-located layout genuinely has nothing there to check -- the classes live in
/// `pkg_dir` itself, the root manifest autoloads them directly, and `php_package_psr4_target`
/// returns `None` by design -- while a nested class directory (`[crates.php.stubs] output` under
/// `pkg_dir`) does have a package-local manifest worth validating.
fn validate_php_manifests(
    config: &ResolvedCrateConfig,
    pkg_dir: &str,
    pkg_path: &Path,
    workspace_root: &Path,
    issues: &mut Vec<String>,
) {
    let root_manifest = workspace_root.join("composer.json");
    let Ok(root_json) = read_json(&root_manifest) else {
        issues.push("php: missing root composer.json".to_string());
        return;
    };

    let expected_root_psr4 = php_psr4_target(config);
    if psr4_path(&root_json) != Some(expected_root_psr4.as_str()) {
        issues.push(format!(
            "php: root composer.json PSR-4 path must be {expected_root_psr4}"
        ));
    }

    let package_manifest = pkg_path.join("composer.json");
    let Ok(package_json) = read_json(&package_manifest) else {
        return;
    };

    if let Some(expected_package_psr4) = php_package_psr4_target(config, pkg_dir)
        && psr4_path(&package_json) != Some(expected_package_psr4.as_str())
    {
        issues.push(format!(
            "php: {pkg_dir}/composer.json PSR-4 path must be {expected_package_psr4}"
        ));
    }

    let mut package_without_autoload = package_json.clone();
    let mut root_without_autoload = root_json.clone();
    if let Some(obj) = package_without_autoload.as_object_mut() {
        obj.remove("autoload");
    }
    if let Some(obj) = root_without_autoload.as_object_mut() {
        obj.remove("autoload");
    }
    if package_without_autoload != root_without_autoload {
        issues.push(format!(
            "php: root composer.json metadata must stay in sync with {pkg_dir}/composer.json"
        ));
    }
}

fn validate_csharp_project(
    config: &ResolvedCrateConfig,
    workspace_root: &Path,
    pkg_dir: &str,
    issues: &mut Vec<String>,
) {
    let namespace = config.csharp_namespace();
    let configured_project_file = config
        .project_file_for_language(Language::Csharp)
        .map(PathBuf::from)
        .filter(|path| path.extension().is_some_and(|ext| ext == "csproj"));
    let nested = PathBuf::from(pkg_dir)
        .join(&namespace)
        .join(format!("{namespace}.csproj"));
    let root = PathBuf::from(pkg_dir).join(format!("{namespace}.csproj"));
    let nested_path = workspace_root.join(&nested);
    let root_path = workspace_root.join(&root);
    let project_file = configured_project_file.unwrap_or_else(|| {
        if nested_path.exists() {
            nested.clone()
        } else {
            root.clone()
        }
    });
    let project_path = if project_file.is_absolute() {
        project_file.clone()
    } else {
        workspace_root.join(&project_file)
    };

    if root_path.exists() && nested_path.exists() {
        issues.push(format!(
            "csharp: stale root project {pkg_dir}/{namespace}.csproj exists; keep only {pkg_dir}/{namespace}/{namespace}.csproj"
        ));
    }
    let Ok(content) = std::fs::read_to_string(&project_path) else {
        issues.push(format!("csharp: missing {}", project_file.display()));
        return;
    };
    // The meta csproj is deliberately THIN: it packs the managed assembly plus `runtime.json`
    // (NuGet's RID-fallback graph) and no native payload. Packing `runtimes/**` here pushes the
    // package past NuGet's size limit and the upload fails with HTTP 413; the native closures
    // ship in the per-RID `<PackageId>.runtime.<rid>` packages instead. Keep this list in sync
    // with `scaffold::render_csharp_csproj`, which is what actually renders the file. ~keep
    for required in [
        r#"<None Include="../../../LICENSE" Pack="true" PackagePath="/" />"#,
        r#"<None Include="runtime.json" Pack="true" PackagePath="/" Condition="Exists('runtime.json')" />"#,
        r#"<Compile Include="../src/**/*.cs" />"#,
    ] {
        if !content.contains(required) {
            issues.push(format!("csharp: {namespace}.csproj missing expected item: {required}"));
        }
    }
    if content.contains(r#"Include="runtimes/**""#) {
        issues.push(format!(
            "csharp: {namespace}.csproj must not pack the runtimes/** native payload; \
             the meta-package exceeds NuGet's size limit (HTTP 413) with it. \
             Natives ship in the per-RID runtime packages."
        ));
    }
}

fn validate_go_module(config: &ResolvedCrateConfig, pkg_dir: &str, pkg_path: &Path, issues: &mut Vec<String>) {
    let go_mod = pkg_path.join("go.mod");
    let Ok(content) = std::fs::read_to_string(&go_mod) else {
        return;
    };
    let module = content
        .lines()
        .find_map(|line| line.strip_prefix("module ").map(str::trim));
    let expected = config.go_module();
    if module != Some(expected.as_str()) {
        issues.push(format!("go: {pkg_dir}/go.mod module must be {expected}"));
        return;
    }
    if let Some(major) = go_major_suffix(&expected) {
        let expected_dir = format!("packages/go/{major}");
        if pkg_dir != expected_dir {
            issues.push(format!(
                "go: module path {expected} requires package directory {expected_dir}; set go scaffold output or use a non-/vN module path"
            ));
        }
    }
}

fn validate_java_manifest(config: &ResolvedCrateConfig, pkg_dir: &str, pkg_path: &Path, issues: &mut Vec<String>) {
    let pom = pkg_path.join("pom.xml");
    let Ok(content) = std::fs::read_to_string(&pom) else {
        return;
    };
    let group_id = config.java_group_id();
    let artifact_id = config.java_artifact_id();
    if !content.contains(&format!("<groupId>{group_id}</groupId>")) {
        issues.push(format!("java: {pkg_dir}/pom.xml groupId must be {group_id}"));
    }
    if !content.contains(&format!("<artifactId>{artifact_id}</artifactId>")) {
        issues.push(format!("java: {pkg_dir}/pom.xml artifactId must be {artifact_id}"));
    }
}

fn validate_dart_manifest(config: &ResolvedCrateConfig, pkg_dir: &str, pkg_path: &Path, issues: &mut Vec<String>) {
    let pubspec = pkg_path.join("pubspec.yaml");
    let Ok(content) = std::fs::read_to_string(&pubspec) else {
        return;
    };
    let Ok(yaml) = serde_saphyr::from_str::<serde_json::Value>(&content) else {
        issues.push(format!("dart: {pkg_dir}/pubspec.yaml is not valid YAML"));
        return;
    };
    let name = yaml.get("name").and_then(|v| v.as_str());
    let expected = config.dart_pubspec_name();
    if name != Some(expected.as_str()) {
        issues.push(format!("dart: {pkg_dir}/pubspec.yaml name must be {expected}"));
    }
    for required in ["version", "description", "repository"] {
        if yaml.get(required).is_none() {
            issues.push(format!("dart: {pkg_dir}/pubspec.yaml missing {required}"));
        }
    }
}

fn validate_swift_manifest(pkg_dir: &str, pkg_path: &Path, issues: &mut Vec<String>) {
    let pkg_manifest = pkg_path.join("Package.swift");
    if let Ok(content) = std::fs::read_to_string(&pkg_manifest)
        && !content.contains("Sources/RustBridge")
    {
        issues.push(format!(
            "swift: {pkg_dir}/Package.swift must include RustBridge source targets"
        ));
    }
}

fn validate_zig_manifest(config: &ResolvedCrateConfig, pkg_dir: &str, pkg_path: &Path, issues: &mut Vec<String>) {
    let zon = pkg_path.join("build.zig.zon");
    let Ok(content) = std::fs::read_to_string(&zon) else {
        issues.push(format!("zig: missing {pkg_dir}/build.zig.zon"));
        return;
    };
    let expected_name = format!(".name = .{}", config.zig_module_name());
    if !content.contains(&expected_name) {
        issues.push(format!(
            "zig: {pkg_dir}/build.zig.zon name must be {}",
            config.zig_module_name()
        ));
    }
    for path in ["\"build.zig\"", "\"build.zig.zon\"", "\"src\""] {
        if !content.contains(path) {
            issues.push(format!("zig: {pkg_dir}/build.zig.zon paths must include {path}"));
        }
    }
}

fn read_json(path: &Path) -> Result<serde_json::Value> {
    let content = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    serde_json::from_str(&content).with_context(|| format!("parsing {}", path.display()))
}

fn psr4_path(json: &serde_json::Value) -> Option<&str> {
    json.get("autoload")?
        .get("psr-4")?
        .as_object()?
        .values()
        .next()?
        .as_str()
}

fn go_major_suffix(module: &str) -> Option<String> {
    let suffix = module.rsplit('/').next()?;
    let major = suffix.strip_prefix('v')?;
    if !major.is_empty() && major.chars().all(|c| c.is_ascii_digit()) && major.parse::<u32>().ok()? >= 2 {
        Some(suffix.to_string())
    } else {
        None
    }
}

fn elixir_nif_targets(config: &ResolvedCrateConfig) -> Vec<String> {
    config
        .elixir
        .as_ref()
        .filter(|elixir| !elixir.nif_targets.is_empty())
        .map(|elixir| elixir.nif_targets.clone())
        .unwrap_or_else(|| {
            [
                "aarch64-apple-darwin",
                "aarch64-unknown-linux-gnu",
                "x86_64-unknown-linux-gnu",
                "x86_64-pc-windows-gnu",
            ]
            .into_iter()
            .map(str::to_string)
            .collect()
        })
}

fn validate_ruby_gemspecs(pkg_path: &Path, pkg_dir: &str, issues: &mut Vec<String>) {
    let mut root_gemspecs = Vec::new();
    let mut nested_gemspecs = Vec::new();
    collect_gemspecs(pkg_path, pkg_path, &mut root_gemspecs, &mut nested_gemspecs);

    if root_gemspecs.is_empty() {
        issues.push(format!("ruby: missing {pkg_dir}/*.gemspec"));
    }
    for nested in nested_gemspecs {
        issues.push(format!(
            "ruby: stale nested gemspec {} (only {pkg_dir}/*.gemspec should remain)",
            nested.display()
        ));
    }
}

fn collect_gemspecs(root: &Path, dir: &Path, root_gemspecs: &mut Vec<PathBuf>, nested_gemspecs: &mut Vec<PathBuf>) {
    if dir
        .strip_prefix(root)
        .ok()
        .is_some_and(|rel| rel.components().any(|component| component.as_os_str() == "vendor"))
    {
        return;
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let Ok(file_type) = entry.file_type() else {
            continue;
        };
        if file_type.is_dir() {
            collect_gemspecs(root, &path, root_gemspecs, nested_gemspecs);
            continue;
        }
        if !file_type.is_file() || path.extension().is_none_or(|ext| ext != "gemspec") {
            continue;
        }
        if path.parent() == Some(root) {
            root_gemspecs.push(path);
        } else {
            nested_gemspecs.push(path);
        }
    }
}