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
use legion::systems::CommandBuffer;

use crate::{codegen::File, BuildContext};

/// Generate a `.cargo/config.toml` file.
#[legion::system]
pub(crate) fn run(cmd: &mut CommandBuffer, #[resource] ctx: &BuildContext) {
    let config = generate_config(ctx.optimized);
    cmd.push((config,));
}

fn generate_config(optimized: bool) -> File {
    let target = if optimized {
        Some(Targets {
            wasm32_unknown_unknown: Target {
                rustflags: &["-C", "link-arg=-s"],
            },
        })
    } else {
        None
    };

    let config = Config {
        target,
        net: Net {
            git_fetch_with_cli: true,
        },
        build: Build {
            target: "wasm32-unknown-unknown",
        },
    };

    let config = toml::to_vec(&config)
        .expect("We can always serialize a Config to TOML");

    File::new(".cargo/config.toml", config)
}

#[derive(Debug, serde::Serialize)]
struct Config {
    target: Option<Targets>,
    net: Net,
    build: Build,
}

/// The [`[build]`](https://doc.rust-lang.org/cargo/reference/config.html#build)
/// table.
#[derive(Debug, serde::Serialize)]
struct Build {
    /// The default target triple.
    target: &'static str,
}

/// The `[target]` table.
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
struct Targets {
    wasm32_unknown_unknown: Target,
}

#[derive(Debug, serde::Serialize)]
struct Target {
    rustflags: &'static [&'static str],
}

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
struct Net {
    git_fetch_with_cli: bool,
}

#[cfg(test)]
mod tests {
    use toml::Value;

    use super::*;

    #[test]
    fn request_small_binaries_when_optimised() {
        let should_be = toml::toml! {
            [target.wasm32-unknown-unknown]
            rustflags = ["-C", "link-arg=-s"]

            [net]
            git-fetch-with-cli = true

            [build]
            target = "wasm32-unknown-unknown"
        };

        let got = generate_config(true);

        assert_eq!(toml::from_slice::<Value>(&got.data).unwrap(), should_be);
    }

    #[test]
    fn only_git_fetch_with_cli_for_debug_builds() {
        let should_be = toml::toml! {
            [net]
            git-fetch-with-cli = true

            [build]
            target = "wasm32-unknown-unknown"
        };

        let got = generate_config(false);

        assert_eq!(toml::from_slice::<Value>(&got.data).unwrap(), should_be);
    }
}