Skip to main content

rust_anything/
package.rs

1//! Step 6: turn a gated port into packages end users install, the way maturin and
2//! `@napi-rs/cli` lay them out. Writes files only: it never builds for other platforms (the
3//! generated GitHub Actions workflow does) and never publishes.
4//!
5//! - PyO3: a self-contained maturin project (abi3 wheel, importable under the original's module
6//!   name) and a workflow that builds wheels for macOS, Linux (manylinux) and Windows.
7//! - napi-rs: a main npm package whose loader picks `<name>-<platform>` from its
8//!   `optionalDependencies` and falls back to the original JS, one package per platform holding
9//!   one `.node`, and a workflow that builds and packs them.
10//! - wasm-bindgen: one npm package with the built `pkg/`, the same on every platform.
11//! - A CLI front door (`rust/app`) of an npm CLI: a main package whose command runs this
12//!   platform's front door binary, with the original pinned as a dependency for every case the
13//!   port does not cover, and one package per platform holding the binary (`cli.rs`).
14
15use std::path::{Component, Path, PathBuf};
16
17use anyhow::{Context, Result, bail};
18use serde::{Deserialize, Serialize};
19use serde_json::json;
20
21use crate::bridge::{Kind, Manifest};
22
23mod cli;
24
25/// Written into the output folder; lists what the last run wrote, so a rerun replaces only that.
26pub const STAMP: &str = "rust-anything-package.json";
27const STAMP_SCHEMA: &str = "rust-anything/package@1";
28
29pub struct Options<'a> {
30    pub crate_dir: &'a Path,
31    /// Package name on npm or PyPI; defaults to the crate name.
32    pub name: Option<String>,
33    /// Package version; defaults to the original package's.
34    pub version: Option<String>,
35    /// Output folder; defaults to `<crate>/package`.
36    pub out: Option<PathBuf>,
37    /// List what would be written, write nothing.
38    pub dry_run: bool,
39    /// napi: the module the loader requires when no binary fits the platform.
40    pub fallback: Option<String>,
41    /// CLI: the commands the package installs; defaults to the package name without its scope.
42    pub bin: Vec<String>,
43    /// CLI: the original npm package the front door falls back to, as `name@version`; defaults
44    /// to the one in `node_modules` of the repository the front door belongs to.
45    pub original: Option<String>,
46}
47
48/// What a package folder holds.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "lowercase")]
51pub enum Layout {
52    Napi,
53    Wasm,
54    Pyo3,
55    /// A front door's binary per platform behind an npm command.
56    Cli,
57}
58
59impl From<Kind> for Layout {
60    fn from(kind: Kind) -> Self {
61        match kind {
62            Kind::Wasm => Layout::Wasm,
63            Kind::Pyo3 => Layout::Pyo3,
64            _ => Layout::Napi,
65        }
66    }
67}
68
69#[derive(Debug, Serialize)]
70pub struct Outcome {
71    pub kind: Layout,
72    pub name: String,
73    pub version: String,
74    pub out: PathBuf,
75    /// Python: the module the wheel installs (`import <module>`).
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub module: Option<String>,
78    /// napi: the platform packages, `<name>-<key>`.
79    #[serde(skip_serializing_if = "Vec::is_empty")]
80    pub platforms: Vec<String>,
81    /// CLI: the commands the package installs.
82    #[serde(skip_serializing_if = "Vec::is_empty")]
83    pub bin: Vec<String>,
84    /// CLI: the original the package depends on, `name@version`.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub original: Option<String>,
87    pub files: Vec<String>,
88    pub dry_run: bool,
89    pub notes: Vec<String>,
90}
91
92#[derive(Serialize, Deserialize)]
93struct Stamp {
94    schema: String,
95    kind: Layout,
96    name: String,
97    version: String,
98    files: Vec<String>,
99}
100
101enum Content {
102    Text(String),
103    Copy(PathBuf),
104}
105
106/// A platform a napi port ships a binary for: the npm key napi-rs uses, the Rust target, and
107/// the runner that builds it.
108pub struct Platform {
109    pub key: &'static str,
110    pub target: &'static str,
111    os: &'static str,
112    cpu: &'static str,
113    libc: Option<&'static str>,
114    runner: &'static str,
115    /// Whether the runner can load what it built (no cross-compiled check).
116    native: bool,
117}
118
119pub const PLATFORMS: &[Platform] = &[
120    Platform {
121        key: "darwin-arm64",
122        target: "aarch64-apple-darwin",
123        os: "darwin",
124        cpu: "arm64",
125        libc: None,
126        runner: "macos-latest",
127        native: true,
128    },
129    Platform {
130        key: "darwin-x64",
131        target: "x86_64-apple-darwin",
132        os: "darwin",
133        cpu: "x64",
134        libc: None,
135        runner: "macos-latest",
136        native: false,
137    },
138    Platform {
139        key: "linux-x64-gnu",
140        target: "x86_64-unknown-linux-gnu",
141        os: "linux",
142        cpu: "x64",
143        libc: Some("glibc"),
144        runner: "ubuntu-22.04",
145        native: true,
146    },
147    Platform {
148        key: "linux-arm64-gnu",
149        target: "aarch64-unknown-linux-gnu",
150        os: "linux",
151        cpu: "arm64",
152        libc: Some("glibc"),
153        runner: "ubuntu-22.04-arm",
154        native: true,
155    },
156    Platform {
157        key: "win32-x64-msvc",
158        target: "x86_64-pc-windows-msvc",
159        os: "win32",
160        cpu: "x64",
161        libc: None,
162        runner: "windows-latest",
163        native: true,
164    },
165];
166
167/// The napi key of the machine running rust-anything, if a package is built for it.
168pub fn host_key() -> Option<&'static str> {
169    let target = match (std::env::consts::OS, std::env::consts::ARCH) {
170        ("macos", "aarch64") => "aarch64-apple-darwin",
171        ("macos", "x86_64") => "x86_64-apple-darwin",
172        ("linux", "x86_64") if cfg!(target_env = "gnu") => "x86_64-unknown-linux-gnu",
173        ("linux", "aarch64") if cfg!(target_env = "gnu") => "aarch64-unknown-linux-gnu",
174        ("windows", "x86_64") if cfg!(target_env = "msvc") => "x86_64-pc-windows-msvc",
175        _ => return None,
176    };
177    PLATFORMS.iter().find(|p| p.target == target).map(|p| p.key)
178}
179
180pub fn package(opts: &Options) -> Result<Outcome> {
181    let crate_dir = std::path::absolute(opts.crate_dir)?;
182    if cli::is_front_door(&crate_dir) {
183        return cli::package(&crate_dir, opts);
184    }
185    let manifest = Manifest::load(&crate_dir)?;
186    let out = match &opts.out {
187        Some(out) => std::path::absolute(out)?,
188        None => crate_dir.join("package"),
189    };
190    let name = match &opts.name {
191        Some(name) => name.clone(),
192        None => manifest.crate_name.clone(),
193    };
194    let mut notes = Vec::new();
195    let version = match &opts.version {
196        Some(v) => v.clone(),
197        None => original_version(&manifest).unwrap_or_else(|| {
198            let v = cargo_version(&crate_dir).unwrap_or_else(|| "0.1.0".into());
199            notes.push(format!(
200                "No version found in the original package; using {v}. Pass --version to set one."
201            ));
202            v
203        }),
204    };
205    let mut files: Vec<(String, Content)> = Vec::new();
206    let mut module = None;
207    let mut platforms = Vec::new();
208    match manifest.kind {
209        Kind::Pyo3 => {
210            let m = python_module(&manifest);
211            python_files(&crate_dir, &manifest, &name, &version, &m, &out, &mut files)?;
212            notes.push(format!(
213                "pip install {0} builds the wheel locally (maturin, from PyPI); `maturin build \
214                 --release` in {0} writes it to target/wheels. The wheel installs `import {m}`.",
215                out.display()
216            ));
217            module = Some(m);
218        }
219        Kind::Napi => {
220            validate_npm_name(&name)?;
221            platforms = PLATFORMS
222                .iter()
223                .map(|p| format!("{name}-{}", p.key))
224                .collect();
225            napi_files(
226                &crate_dir, &manifest, &name, &version, opts, &out, &mut files, &mut notes,
227            )?;
228        }
229        Kind::Wasm => {
230            validate_npm_name(&name)?;
231            wasm_files(&crate_dir, &manifest, &name, &version, &mut files)?;
232            notes.push(format!(
233                "npm pack {} gives one tarball that runs on every platform.",
234                out.display()
235            ));
236        }
237        Kind::CAbi | Kind::Ffi => bail!(
238            "package covers napi-rs, wasm-bindgen and PyO3 crates; this one is {:?}",
239            manifest.kind
240        ),
241    }
242    if matches!(manifest.kind, Kind::Pyo3 | Kind::Napi) {
243        let (workflow, note) = workflow_file(&manifest, &name, &version, &crate_dir, &out)?;
244        files.push(workflow);
245        notes.push(note);
246    }
247    notes.push("Nothing was published.".into());
248    let listed: Vec<String> = files.iter().map(|(p, _)| p.clone()).collect();
249    if !opts.dry_run {
250        write(&out, manifest.kind.into(), &name, &version, files)?;
251    }
252    Ok(Outcome {
253        kind: manifest.kind.into(),
254        name,
255        version,
256        out,
257        module,
258        platforms,
259        bin: Vec::new(),
260        original: None,
261        files: listed,
262        dry_run: opts.dry_run,
263        notes,
264    })
265}
266
267fn write(
268    out: &Path,
269    kind: Layout,
270    name: &str,
271    version: &str,
272    files: Vec<(String, Content)>,
273) -> Result<()> {
274    let stamp_path = out.join(STAMP);
275    if stamp_path.exists() {
276        let text = std::fs::read_to_string(&stamp_path)?;
277        let old: Stamp = serde_json::from_str(&text)
278            .with_context(|| format!("parsing {}", stamp_path.display()))?;
279        for file in old.files {
280            let path = out.join(&file);
281            if safe_relative(&file) && path.is_file() {
282                std::fs::remove_file(&path)?;
283            }
284        }
285    } else if out.exists() && std::fs::read_dir(out)?.next().is_some() {
286        bail!(
287            "{} is not empty and was not written by `rust-anything package`; pass --out with an \
288             empty or new folder",
289            out.display()
290        );
291    }
292    for (path, content) in &files {
293        let target = out.join(path);
294        if let Some(parent) = target.parent() {
295            std::fs::create_dir_all(parent)?;
296        }
297        match content {
298            Content::Text(text) => std::fs::write(&target, text),
299            Content::Copy(from) => std::fs::copy(from, &target).map(|_| ()),
300        }
301        .with_context(|| format!("writing {}", target.display()))?;
302    }
303    let stamp = Stamp {
304        schema: STAMP_SCHEMA.into(),
305        kind,
306        name: name.into(),
307        version: version.into(),
308        files: files.into_iter().map(|(p, _)| p).collect(),
309    };
310    std::fs::write(&stamp_path, serde_json::to_string_pretty(&stamp)? + "\n")?;
311    Ok(())
312}
313
314fn safe_relative(path: &str) -> bool {
315    Path::new(path)
316        .components()
317        .all(|c| matches!(c, Component::Normal(_)))
318}
319
320fn validate_npm_name(name: &str) -> Result<()> {
321    let bare = name
322        .strip_prefix('@')
323        .and_then(|n| n.split_once('/'))
324        .map_or(name, |(_, n)| n);
325    let ok = !bare.is_empty()
326        && name.len() <= 214
327        && !name.starts_with('.')
328        && !name.starts_with('_')
329        && name.chars().all(|c| {
330            c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '.' | '_' | '@' | '/')
331        });
332    if !ok {
333        bail!("`{name}` is not a valid npm package name (lowercase, URL-safe); pass --name");
334    }
335    Ok(())
336}
337
338/// The version of the package the unit belongs to: the nearest `package.json` for JS, the
339/// `pyproject.toml` (or `setup.cfg`, or `__version__`) for Python.
340pub fn original_version(manifest: &Manifest) -> Option<String> {
341    let root = &manifest.root;
342    let unit = root.join(manifest.unit.trim_end_matches('/'));
343    match manifest.language {
344        crate::lang::Lang::Python => python_version(root, &unit),
345        _ => {
346            let mut dir = unit.parent()?.to_path_buf();
347            loop {
348                let pkg = dir.join("package.json");
349                if let Ok(text) = std::fs::read_to_string(&pkg)
350                    && let Ok(value) = serde_json::from_str::<serde_json::Value>(&text)
351                    && let Some(v) = value["version"].as_str()
352                {
353                    return Some(v.to_string());
354                }
355                if dir == *root || !dir.pop() || !dir.starts_with(root) {
356                    return None;
357                }
358            }
359        }
360    }
361}
362
363fn python_version(root: &Path, unit: &Path) -> Option<String> {
364    if let Ok(text) = std::fs::read_to_string(root.join("pyproject.toml"))
365        && let Ok(doc) = text.parse::<toml_edit::DocumentMut>()
366    {
367        let v = doc
368            .get("project")
369            .and_then(|p| p.get("version"))
370            .or_else(|| {
371                doc.get("tool")
372                    .and_then(|t| t.get("poetry"))
373                    .and_then(|p| p.get("version"))
374            })
375            .and_then(|v| v.as_str());
376        if let Some(v) = v {
377            return Some(v.to_string());
378        }
379    }
380    if let Ok(text) = std::fs::read_to_string(root.join("setup.cfg")) {
381        let mut in_metadata = false;
382        for line in text.lines() {
383            let line = line.trim();
384            if line.starts_with('[') {
385                in_metadata = line == "[metadata]";
386            } else if in_metadata
387                && let Some((key, value)) = line.split_once('=')
388                && key.trim() == "version"
389                && !value.trim().starts_with("attr:")
390            {
391                return Some(value.trim().to_string());
392            }
393        }
394    }
395    let init = if unit.is_dir() {
396        unit.join("__init__.py")
397    } else {
398        unit.parent()?.join("__init__.py")
399    };
400    let text = std::fs::read_to_string(init).ok()?;
401    text.lines().find_map(|l| {
402        let rest = l.trim().strip_prefix("__version__")?.trim_start();
403        let rest = rest.strip_prefix('=')?.trim();
404        let quote = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?;
405        rest[1..].split(quote).next().map(str::to_string)
406    })
407}
408
409fn cargo_version(crate_dir: &Path) -> Option<String> {
410    let text = std::fs::read_to_string(crate_dir.join("Cargo.toml")).ok()?;
411    let doc = text.parse::<toml_edit::DocumentMut>().ok()?;
412    Some(doc.get("package")?.get("version")?.as_str()?.to_string())
413}
414
415/// The dotted module the original unit is imported as: `src/textkit/` is `textkit`,
416/// `src/textkit/words.py` is `textkit.words`. Folders above count while they are packages
417/// (hold `__init__.py`); without the sources, a leading `src/` or `lib/` is dropped.
418pub fn python_module(manifest: &Manifest) -> String {
419    let unit = manifest.unit.trim_end_matches('/');
420    let unit = unit.strip_suffix("/__init__.py").unwrap_or(unit);
421    let unit = unit.strip_suffix(".py").unwrap_or(unit);
422    let parts: Vec<&str> = unit.split('/').filter(|p| !p.is_empty()).collect();
423    let root = &manifest.root;
424    let mut start = parts.len().saturating_sub(1);
425    if root.join(unit).exists() || root.join(format!("{unit}.py")).exists() {
426        while start > 0
427            && root
428                .join(parts[..start].join("/"))
429                .join("__init__.py")
430                .exists()
431        {
432            start -= 1;
433        }
434    } else {
435        start = usize::from(matches!(parts.first(), Some(&"src" | &"lib")) && parts.len() > 1);
436    }
437    parts[start..].join(".")
438}
439
440#[allow(clippy::too_many_arguments)]
441fn python_files(
442    crate_dir: &Path,
443    manifest: &Manifest,
444    name: &str,
445    version: &str,
446    module: &str,
447    out: &Path,
448    files: &mut Vec<(String, Content)>,
449) -> Result<()> {
450    if out.starts_with(crate_dir.join("src")) || out.starts_with(crate_dir.join("python")) {
451        bail!("--out cannot be inside the crate's src/ or python/ folder");
452    }
453    let (wrapper_dir, wrapper_name) = crate::harness_py::package(crate_dir, manifest);
454    let wrapper = wrapper_dir.join(&wrapper_name);
455    if !wrapper.join("__init__.py").exists() {
456        bail!(
457            "{} has no __init__.py; run `rust-anything refresh {}`",
458            wrapper.display(),
459            crate_dir.display()
460        );
461    }
462    let cargo =
463        std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
464    let mut doc: toml_edit::DocumentMut = cargo.parse().context("parsing Cargo.toml")?;
465    if !doc.contains_key("workspace") {
466        doc.insert("workspace", toml_edit::Item::Table(toml_edit::Table::new()));
467    }
468    files.push(("Cargo.toml".into(), Content::Text(doc.to_string())));
469    for extra in ["Cargo.lock", "build.rs"] {
470        if crate_dir.join(extra).exists() {
471            files.push((extra.into(), Content::Copy(crate_dir.join(extra))));
472        }
473    }
474    for file in tree(&crate_dir.join("src"))? {
475        files.push((
476            format!("src/{}", slash(&file)),
477            Content::Copy(crate_dir.join("src").join(&file)),
478        ));
479    }
480    let module_dir = format!("python/{}", module.replace('.', "/"));
481    for file in tree(&wrapper)? {
482        let file_name = file.file_name().unwrap_or_default().to_string_lossy();
483        if file_name.starts_with("_native.")
484            || file.components().any(|c| c.as_os_str() == "__pycache__")
485        {
486            continue;
487        }
488        files.push((
489            format!("{module_dir}/{}", slash(&file)),
490            Content::Copy(wrapper.join(&file)),
491        ));
492    }
493    files.push((
494        "pyproject.toml".into(),
495        Content::Text(pyproject(manifest, name, version, module)),
496    ));
497    files.push((
498        ".gitignore".into(),
499        Content::Text("target/\ndist/\n*.so\n*.pyd\n__pycache__/\n".into()),
500    ));
501    Ok(())
502}
503
504fn pyproject(manifest: &Manifest, name: &str, version: &str, module: &str) -> String {
505    format!(
506        "[build-system]\nrequires = [\"maturin>=1.7,<2\"]\nbuild-backend = \"maturin\"\n\n\
507         [project]\nname = \"{name}\"\nversion = \"{version}\"\n\
508         description = \"Rust port of `{unit}`, generated by rust-anything\"\n\
509         requires-python = \">=3.9\"\n\
510         classifiers = [\"Programming Language :: Rust\", \"Programming Language :: Python :: Implementation :: CPython\"]\n\n\
511         [tool.maturin]\nbindings = \"pyo3\"\nmodule-name = \"{module}._native\"\npython-source = \"python\"\n",
512        unit = manifest.unit
513    )
514}
515
516#[allow(clippy::too_many_arguments)]
517fn napi_files(
518    crate_dir: &Path,
519    manifest: &Manifest,
520    name: &str,
521    version: &str,
522    opts: &Options,
523    out: &Path,
524    files: &mut Vec<(String, Content)>,
525    notes: &mut Vec<String>,
526) -> Result<()> {
527    let lib = manifest.lib_name();
528    let index = std::fs::read_to_string(crate_dir.join("index.cjs")).with_context(|| {
529        format!(
530            "reading index.cjs (run `rust-anything refresh {}`)",
531            crate_dir.display()
532        )
533    })?;
534    let load = format!("require('./{lib}.node')");
535    if !index.contains(&load) {
536        bail!(
537            "index.cjs does not load `./{lib}.node`; run `rust-anything refresh {}` to regenerate it",
538            crate_dir.display()
539        );
540    }
541    files.push((
542        "binding.cjs".into(),
543        Content::Text(index.replacen(&load, "require('./native.cjs').load().binding", 1)),
544    ));
545    files.push(("native.cjs".into(), Content::Text(native_cjs(name, &lib))));
546
547    let mut shipped = vec!["index.cjs", "binding.cjs", "native.cjs"];
548    let fallback = match &opts.fallback {
549        Some(spec) => Some(spec.clone()),
550        None => match original_fallback(manifest) {
551            Ok((file, path)) => {
552                files.push((format!("fallback/{file}"), Content::Copy(path)));
553                shipped.push("fallback/");
554                Some(format!("./fallback/{file}"))
555            }
556            Err(why) => {
557                notes.push(format!(
558                    "No fallback: {why}. On a platform without a binary the package throws; pass \
559                     --fallback <module> (e.g. the original npm package) to load it instead."
560                ));
561                None
562            }
563        },
564    };
565    files.push((
566        "index.cjs".into(),
567        Content::Text(index_cjs(name, fallback.as_deref())),
568    ));
569
570    let mut optional = serde_json::Map::new();
571    for p in PLATFORMS {
572        let pkg = format!("{name}-{}", p.key);
573        optional.insert(pkg.clone(), json!(version));
574        let node = format!("{lib}.{}.node", p.key);
575        let mut platform = json!({
576            "name": pkg,
577            "version": version,
578            "description": format!("{} binary of {name}, generated by rust-anything", p.target),
579            "main": node,
580            "files": [node],
581            "os": [p.os],
582            "cpu": [p.cpu],
583        });
584        if let Some(libc) = p.libc {
585            platform["libc"] = json!([libc]);
586        }
587        files.push((
588            format!("npm/{}/package.json", p.key),
589            Content::Text(serde_json::to_string_pretty(&platform)? + "\n"),
590        ));
591    }
592    let main = json!({
593        "name": name,
594        "version": version,
595        "description": format!("Rust port of `{}`, generated by rust-anything", manifest.unit),
596        "main": "index.cjs",
597        "files": shipped,
598        "optionalDependencies": optional,
599    });
600    files.push((
601        "package.json".into(),
602        Content::Text(serde_json::to_string_pretty(&main)? + "\n"),
603    ));
604    files.push((
605        ".gitignore".into(),
606        Content::Text("target/\ntarballs/\nnpm-built/\n*.node\n*.tgz\n".into()),
607    ));
608
609    let built = crate_dir.join(format!("{lib}.node"));
610    match host_key() {
611        Some(key) if built.exists() => {
612            files.push((
613                format!("npm/{key}/{lib}.{key}.node"),
614                Content::Copy(built.clone()),
615            ));
616            if crate::harness::sources_newer_than(crate_dir, &built) {
617                notes.push(format!(
618                    "{} is older than the crate's sources; run `rust-anything build {}` and \
619                     package again",
620                    built.display(),
621                    crate_dir.display()
622                ));
623            }
624            notes.push(format!(
625                "This machine's binary is in npm/{key}/. To try it: npm pack {0}/npm/{key} and \
626                 npm pack {0}, then npm install both tarballs.",
627                out.display()
628            ));
629        }
630        Some(_) => notes.push(format!(
631            "No {lib}.node in the crate: run `rust-anything build {}` and package again to try \
632             the package on this machine.",
633            crate_dir.display()
634        )),
635        None => {}
636    }
637    Ok(())
638}
639
640/// The original unit as a file the package can ship and require: one JS file that imports
641/// nothing.
642fn original_fallback(manifest: &Manifest) -> Result<(String, PathBuf), String> {
643    let path = manifest.root.join(&manifest.unit);
644    if !path.is_file() {
645        return Err(format!(
646            "the original `{}` is not a single file in {}",
647            manifest.unit,
648            manifest.root.display()
649        ));
650    }
651    let file = path
652        .file_name()
653        .map(|f| f.to_string_lossy().to_string())
654        .unwrap_or_default();
655    if ["ts", "mts", "cts", "tsx"]
656        .iter()
657        .any(|e| file.ends_with(&format!(".{e}")))
658    {
659        return Err(format!(
660            "`{file}` is TypeScript, and Node does not strip types under node_modules"
661        ));
662    }
663    if !["js", "cjs", "mjs"]
664        .iter()
665        .any(|e| file.ends_with(&format!(".{e}")))
666    {
667        return Err(format!("`{file}` is not a JS file"));
668    }
669    let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
670    let imports = text.lines().any(|l| {
671        let l = l.trim_start();
672        l.starts_with("import ")
673            || l.starts_with("import{")
674            || (l.starts_with("export ") && l.contains(" from "))
675            || l.contains("require(")
676            || l.contains("import(")
677    });
678    if imports {
679        return Err(format!("`{file}` imports other modules"));
680    }
681    Ok((file, path))
682}
683
684fn index_cjs(name: &str, fallback: Option<&str>) -> String {
685    let otherwise = match fallback {
686        Some(spec) => format!("  module.exports = require({})\n", js_string(spec)),
687        None => format!(
688            "  throw new Error(\n    `{name} has no Rust build for ${{key}} (built for: ${{supported.join(', ')}})` +\n      (errors.length ? `:\\n${{errors.join('\\n')}}` : '')\n  )\n"
689        ),
690    };
691    format!(
692        "'use strict'\n// Generated by `rust-anything package`: the Rust port for this platform, or the original.\n\
693         const {{ load, supported }} = require('./native.cjs')\nconst {{ binding, key, errors }} = load()\n\
694         if (binding && process.env.RUST_ANYTHING_MODE !== 'old') {{\n  module.exports = require('./binding.cjs')\n}} else {{\n{otherwise}}}\n"
695    )
696}
697
698fn native_cjs(name: &str, lib: &str) -> String {
699    let keys: Vec<String> = PLATFORMS.iter().map(|p| format!("'{}'", p.key)).collect();
700    format!(
701        r#"'use strict'
702// Generated by `rust-anything package`: finds the binary for this platform.
703const {{ platform, arch }} = process
704
705function abi() {{
706  if (platform === 'win32') return '-msvc'
707  if (platform !== 'linux') return ''
708  try {{
709    return process.report.getReport().header.glibcVersionRuntime ? '-gnu' : '-musl'
710  }} catch {{
711    return '-gnu'
712  }}
713}}
714
715const key = `${{platform}}-${{arch}}${{abi()}}`
716const supported = [{keys}]
717let loaded = null
718
719function load() {{
720  if (loaded) return loaded
721  const errors = []
722  let binding = null
723  if (supported.includes(key)) {{
724    for (const id of [`./npm/${{key}}/{lib}.${{key}}.node`, `{name}-${{key}}`]) {{
725      try {{
726        binding = require(id)
727        break
728      }} catch (e) {{
729        errors.push(`${{id}}: ${{e.message.split('\n')[0]}}`)
730      }}
731    }}
732  }}
733  loaded = {{ binding, key, errors }}
734  return loaded
735}}
736
737module.exports = {{ load, key, supported }}
738"#,
739        keys = keys.join(", ")
740    )
741}
742
743fn js_string(s: &str) -> String {
744    serde_json::to_string(s).unwrap_or_else(|_| "''".into())
745}
746
747fn wasm_files(
748    crate_dir: &Path,
749    manifest: &Manifest,
750    name: &str,
751    version: &str,
752    files: &mut Vec<(String, Content)>,
753) -> Result<()> {
754    let pkg = crate_dir.join("pkg");
755    let lib = manifest.lib_name();
756    if !pkg.join(format!("{lib}.js")).exists() {
757        bail!(
758            "no wasm build in {}; run `rust-anything build {}` first",
759            pkg.display(),
760            crate_dir.display()
761        );
762    }
763    files.push((
764        "index.cjs".into(),
765        Content::Copy(crate_dir.join("index.cjs")),
766    ));
767    for file in tree(&pkg)? {
768        let file_name = file.file_name().unwrap_or_default().to_string_lossy();
769        if file_name == ".gitignore" || file_name == "package.json" {
770            continue;
771        }
772        files.push((
773            format!("pkg/{}", slash(&file)),
774            Content::Copy(pkg.join(&file)),
775        ));
776    }
777    let main = json!({
778        "name": name,
779        "version": version,
780        "description": format!("Rust port of `{}` (WebAssembly), generated by rust-anything", manifest.unit),
781        "main": "index.cjs",
782        "types": format!("pkg/{lib}.d.ts"),
783        "files": ["index.cjs", "pkg/"],
784    });
785    files.push((
786        "package.json".into(),
787        Content::Text(serde_json::to_string_pretty(&main)? + "\n"),
788    ));
789    Ok(())
790}
791
792/// The GitHub Actions workflow, written inside the output folder; GitHub runs workflows only
793/// from the repository's `.github/workflows`, so the note says where to move it.
794fn workflow_file(
795    manifest: &Manifest,
796    name: &str,
797    version: &str,
798    crate_dir: &Path,
799    out: &Path,
800) -> Result<((String, Content), String)> {
801    let repo = git_root(out);
802    let out_rel = repo
803        .as_deref()
804        .and_then(|r| relative(r, out))
805        .unwrap_or_else(|| ".".into());
806    let slug: String = name
807        .trim_start_matches('@')
808        .chars()
809        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
810        .collect();
811    let (file, text) = match manifest.kind {
812        Kind::Pyo3 => (
813            format!("{slug}-wheels.yml"),
814            wheels_yml(name, version, &python_module(manifest), &out_rel),
815        ),
816        _ => {
817            let crate_rel = relative(out, crate_dir).context("relating the crate to --out")?;
818            (
819                format!("{slug}-npm.yml"),
820                npm_yml(name, version, &manifest.lib_name(), &out_rel, &crate_rel),
821            )
822        }
823    };
824    let path = format!(".github/workflows/{file}");
825    let note = match &repo {
826        Some(repo) => format!(
827            "CI: move {path} to {}/.github/workflows/ (GitHub runs workflows only from there); it \
828             builds every platform and uploads the packages as artifacts.",
829            repo.display()
830        ),
831        None => format!(
832            "CI: {path} assumes {} is the repository root; move it to the repository's \
833             .github/workflows/ and set `working-directory` to this folder.",
834            out.display()
835        ),
836    };
837    Ok(((path, Content::Text(text)), note))
838}
839
840fn wheels_yml(name: &str, version: &str, module: &str, dir: &str) -> String {
841    format!(
842        r#"# Generated by `rust-anything package`: abi3 wheels of {name} {version} (one per platform,
843# every CPython from 3.9 on) and an sdist, uploaded as artifacts. Nothing is published.
844name: {name} wheels
845
846on:
847  workflow_dispatch:
848  push:
849    tags: ['v*']
850
851defaults:
852  run:
853    shell: bash
854    working-directory: {dir}
855
856jobs:
857  wheels:
858    name: ${{{{ matrix.target }}}}
859    runs-on: ${{{{ matrix.os }}}}
860    strategy:
861      fail-fast: false
862      matrix:
863        include:
864          - {{ os: macos-latest, target: aarch64-apple-darwin, check: true }}
865          - {{ os: macos-latest, target: x86_64-apple-darwin, check: false }}
866          - {{ os: ubuntu-latest, target: x86_64-unknown-linux-gnu, check: true }}
867          - {{ os: ubuntu-latest, target: aarch64-unknown-linux-gnu, check: false }}
868          - {{ os: windows-latest, target: x86_64-pc-windows-msvc, check: true }}
869    steps:
870      - uses: actions/checkout@v4
871      - uses: actions/setup-python@v5
872        with:
873          python-version: '3.12'
874      - uses: PyO3/maturin-action@v1
875        with:
876          target: ${{{{ matrix.target }}}}
877          manylinux: auto
878          args: --release --out dist
879          working-directory: {dir}
880      - name: Import check
881        if: matrix.check
882        run: |
883          python -m pip install {name} --no-index --find-links dist --force-reinstall
884          python -c "import {module}"
885      - uses: actions/upload-artifact@v4
886        with:
887          name: wheel-${{{{ matrix.target }}}}
888          path: {dir}/dist
889
890  sdist:
891    runs-on: ubuntu-latest
892    steps:
893      - uses: actions/checkout@v4
894      - uses: PyO3/maturin-action@v1
895        with:
896          command: sdist
897          args: --out dist
898          working-directory: {dir}
899      - uses: actions/upload-artifact@v4
900        with:
901          name: sdist
902          path: {dir}/dist
903"#
904    )
905}
906
907fn npm_yml(name: &str, version: &str, lib: &str, dir: &str, crate_rel: &str) -> String {
908    let matrix: String = PLATFORMS
909        .iter()
910        .map(|p| {
911            let file = match p.os {
912                "darwin" => format!("lib{lib}.dylib"),
913                "linux" => format!("lib{lib}.so"),
914                _ => format!("{lib}.dll"),
915            };
916            format!(
917                "          - {{ key: {}, target: {}, os: {}, lib: {file}, check: {} }}\n",
918                p.key, p.target, p.runner, p.native
919            )
920        })
921        .collect();
922    format!(
923        r#"# Generated by `rust-anything package`: the {name} {version} npm packages (one per
924# platform, plus the main one), packed and uploaded as artifacts. Nothing is published.
925name: {name} npm packages
926
927on:
928  workflow_dispatch:
929  push:
930    tags: ['v*']
931
932defaults:
933  run:
934    shell: bash
935    working-directory: {dir}
936
937jobs:
938  build:
939    name: ${{{{ matrix.key }}}}
940    runs-on: ${{{{ matrix.os }}}}
941    strategy:
942      fail-fast: false
943      matrix:
944        include:
945{matrix}    steps:
946      - uses: actions/checkout@v4
947      - uses: actions/setup-node@v4
948        with:
949          node-version: 22
950      - run: rustup target add ${{{{ matrix.target }}}}
951      - run: cargo build --release --target ${{{{ matrix.target }}}} --manifest-path {crate_rel}/Cargo.toml --target-dir target
952      - run: cp target/${{{{ matrix.target }}}}/release/${{{{ matrix.lib }}}} npm/${{{{ matrix.key }}}}/{lib}.${{{{ matrix.key }}}}.node
953      - name: Load check
954        if: matrix.check
955        run: node -e "const r = require('./native.cjs').load(); if (!r.binding) throw new Error(r.errors.join('\n'))"
956      - uses: actions/upload-artifact@v4
957        with:
958          name: npm-${{{{ matrix.key }}}}
959          path: {dir}/npm/${{{{ matrix.key }}}}/*.node
960
961  pack:
962    needs: build
963    runs-on: ubuntu-latest
964    steps:
965      - uses: actions/checkout@v4
966      - uses: actions/setup-node@v4
967        with:
968          node-version: 22
969      - uses: actions/download-artifact@v4
970        with:
971          pattern: npm-*
972          path: {dir}/npm-built
973      - run: |
974          for built in npm-built/npm-*; do cp "$built"/*.node "npm/${{built##*/npm-}}/"; done
975          mkdir -p tarballs
976          for platform in npm/*/; do npm pack "./$platform" --pack-destination tarballs; done
977          npm pack --pack-destination tarballs
978      - uses: actions/upload-artifact@v4
979        with:
980          name: npm-tarballs
981          path: {dir}/tarballs
982"#
983    )
984}
985
986fn git_root(from: &Path) -> Option<PathBuf> {
987    let mut dir = from.to_path_buf();
988    loop {
989        if dir.join(".git").exists() {
990            return Some(dir);
991        }
992        if !dir.pop() {
993            return None;
994        }
995    }
996}
997
998/// `to` relative to `from`, with `/` separators; `.` when they are the same folder.
999fn relative(from: &Path, to: &Path) -> Option<String> {
1000    let from: Vec<Component> = from.components().collect();
1001    let to: Vec<Component> = to.components().collect();
1002    if from.first() != to.first() {
1003        return None;
1004    }
1005    let common = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
1006    let mut parts: Vec<String> = vec!["..".into(); from.len() - common];
1007    parts.extend(
1008        to[common..]
1009            .iter()
1010            .map(|c| c.as_os_str().to_string_lossy().to_string()),
1011    );
1012    Some(if parts.is_empty() {
1013        ".".into()
1014    } else {
1015        parts.join("/")
1016    })
1017}
1018
1019/// Every file under `dir`, relative to it, sorted.
1020fn tree(dir: &Path) -> Result<Vec<PathBuf>> {
1021    let mut out = Vec::new();
1022    let mut stack = vec![PathBuf::new()];
1023    while let Some(rel) = stack.pop() {
1024        let entries = std::fs::read_dir(dir.join(&rel))
1025            .with_context(|| format!("reading {}", dir.display()))?;
1026        for entry in entries {
1027            let entry = entry?;
1028            let path = rel.join(entry.file_name());
1029            if entry.file_type()?.is_dir() {
1030                stack.push(path);
1031            } else {
1032                out.push(path);
1033            }
1034        }
1035    }
1036    out.sort();
1037    Ok(out)
1038}
1039
1040fn slash(path: &Path) -> String {
1041    path.components()
1042        .map(|c| c.as_os_str().to_string_lossy())
1043        .collect::<Vec<_>>()
1044        .join("/")
1045}
1046
1047#[cfg(test)]
1048mod tests {
1049    use super::*;
1050
1051    #[test]
1052    fn relative_paths() {
1053        assert_eq!(
1054            relative(Path::new("/r/a/package"), Path::new("/r/a")).as_deref(),
1055            Some("..")
1056        );
1057        assert_eq!(
1058            relative(Path::new("/r"), Path::new("/r/rust/x/package")).as_deref(),
1059            Some("rust/x/package")
1060        );
1061        assert_eq!(
1062            relative(Path::new("/r"), Path::new("/r")).as_deref(),
1063            Some(".")
1064        );
1065    }
1066
1067    #[test]
1068    fn npm_names() {
1069        assert!(validate_npm_name("fuzzy-rs").is_ok());
1070        assert!(validate_npm_name("@x18n/fuzzy").is_ok());
1071        assert!(validate_npm_name("Fuzzy").is_err());
1072        assert!(validate_npm_name("@x18n/").is_err());
1073    }
1074
1075    #[test]
1076    fn every_platform_has_a_unique_key() {
1077        let mut keys: Vec<&str> = PLATFORMS.iter().map(|p| p.key).collect();
1078        keys.sort_unstable();
1079        keys.dedup();
1080        assert_eq!(keys.len(), PLATFORMS.len());
1081    }
1082
1083    #[test]
1084    fn stamp_paths_stay_inside() {
1085        assert!(safe_relative("npm/darwin-arm64/package.json"));
1086        assert!(!safe_relative("../x"));
1087        assert!(!safe_relative("/etc/passwd"));
1088    }
1089}