yog-cli 0.42.3

Yog build tool — `yog build` compiles a mod and packages it as .yog.
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
//! `yog.toml` — a mod project's manifest, the only build file mod authors
//! write.

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

/// The manifest's file name, in the project root.
pub const MANIFEST: &str = "yog.toml";
/// Where `yog build` generates the cargo project, under the project root.
pub const BUILD_DIR: &str = ".yog-build";
/// Plain crates.io dependencies.
pub const DEPS_SECTION: &str = "[dependencies]";
/// Other Yog mods' exports crates.
pub const EXPORT_DEPS_SECTION: &str = "[dependencies.exports]";
/// Rust edition when `[mod] edition` is absent.
pub const DEFAULT_EDITION: &str = "2024";
/// License of a mod, and of its exports crate, when none is given.
pub const DEFAULT_LICENSE: &str = "MIT OR Apache-2.0";
/// `yog-api` version when crates.io can't be asked (offline, etc.).
const FALLBACK_API_VERSION: &str = "0.96";

/// The current directory, if it's a mod project (has a `yog.toml`).
pub fn project_root() -> Result<PathBuf, String> {
    let root = std::env::current_dir().map_err(|e| e.to_string())?;
    if root.join(MANIFEST).is_file() {
        Ok(root)
    } else {
        Err(format!("no {MANIFEST} found in the current directory"))
    }
}

/// Parsed content of a `yog.toml` project file.
#[derive(Debug)]
pub struct YogToml {
    pub id: String,
    pub name: String,
    pub version: String,
    pub description: String,
    /// Translation keys of `name`/`description` when yog.toml gives them
    /// as `@<Set>.<name>` resources (see `resolve_metadata`).
    pub name_key: Option<String>,
    pub description_key: Option<String>,
    /// The mod's icon, an image source (`icon = "@Icons.logo"` resolved).
    pub icon: Option<String>,
    pub authors: Vec<String>,
    pub license: String,
    /// License for the generated `yog publish exports` bindings crate.
    /// Defaults to "MIT OR Apache-2.0" regardless of the mod's own license
    /// (AGPL propagating onto every consumer's dependency tree would kill
    /// adoption of the exports crate) — set `[mod] exports_license = "..."`
    /// to opt into matching the mod's own license instead.
    pub exports_license: Option<String>,
    /// The Minecraft version whose vanilla content it names (`[mod] datapack`).
    pub datapack: Option<String>,
    pub edition: Option<String>,
    /// Optional: path to yog-api for local/monorepo development.
    /// Set via [dev] yog_api_path = "..."  or YOG_API_PATH env var.
    pub yog_api_path: Option<String>,
    /// Optional: pin yog-api version as "yog_api = \"X.Y\"" in [dependencies].
    pub yog_api_version: Option<String>,
    /// User-declared dependencies from [dependencies] section — plain
    /// crates.io crates, used exactly as written.
    pub dependencies: Vec<(String, String)>,
    /// Other Yog mods this mod depends on, from `[dependencies.exports]`.
    /// Each entry `name = spec` maps to that mod's generated exports crate:
    /// `{name} = { package = "{name}-exports", ...spec }` — so mod code
    /// imports it under its own name (`use {name}::...`), same as a direct
    /// dependency, and two mod dependencies never collide under a shared
    /// alias (unlike the old name-contains-hyphen heuristic this replaced).
    pub mod_dependencies: Vec<(String, String)>,
    /// `[dev-dependencies]` — crates only `yog bench` benchmarks use.
    pub dev_dependencies: Vec<(String, String)>,
    /// Named dev-instance launch configs from `[run.<name>]` sections.
    pub run_configs: Vec<RunConfig>,
    /// Content of other mods (original Java mods, or Yog mods) this mod
    /// names, declared up front: `[external.<namespace>]` with `items`,
    /// `blocks`, `entities`, `recipes` (paths: `["cutting_board"]`).
    pub externals: Vec<External>,
}

/// One `[external.<namespace>]` section.
#[derive(Debug, Default, Clone)]
pub struct External {
    pub namespace: String,
    /// `kind` (`items`, `blocks`, `entities`, `recipes`) → paths.
    pub ids: Vec<(String, Vec<String>)>,
}

/// A `[run.<name>]` section: where to drop the built artifact and what to
/// launch afterwards, for a full `yog run <name>` dev-instance workflow.
#[derive(Debug, Default, Clone)]
pub struct RunConfig {
    pub name: String,
    /// Optional human-readable label (`name = "..."` inside `[run.X]`), for
    /// editors to show/edit instead of the raw dotted section-key id. Falls
    /// back to `name` (the id) when absent.
    pub display_name: Option<String>,
    /// Directory the built `.yog` gets copied into (e.g. an instance's `yog-mods/`).
    /// Relative paths resolve against the mod project root.
    pub export_dir: Option<String>,
    /// Executable to launch after export (e.g. `java`, a wrapper script, `./gradlew`).
    pub command: Option<String>,
    /// Arguments passed to `command`, in order.
    pub args: Vec<String>,
    /// Working directory for `command`. Relative paths resolve against the project root.
    pub cwd: Option<String>,
    /// Extra environment variables as `KEY=VALUE` pairs.
    pub env: Vec<(String, String)>,
}

impl YogToml {
    pub fn read(path: &Path) -> Result<Self, String> {
        let text = std::fs::read_to_string(path)
            .map_err(|e| format!("reading {}: {e}", path.display()))?;
        parse_yog_toml(&text)
    }

    /// Resolve where yog-api lives.  Priority:
    ///   1. YOG_API_PATH env var
    ///   2. [dev] yog_api_path in yog.toml
    ///   3. yog_api_version in [dependencies] (e.g. "0.5")
    ///   4. YOG_API_VERSION env var
    ///   5. latest from crates.io
    pub fn api_dep(&self) -> String {
        if let Ok(p) = std::env::var("YOG_API_PATH") {
            // Resolve to absolute so it works from any subdirectory
            let abs = PathBuf::from(&p)
                .canonicalize()
                .unwrap_or_else(|_| PathBuf::from(&p));
            return format!("yog-api = {{ path = {:?} }}", abs.to_string_lossy());
        }
        if let Some(p) = &self.yog_api_path {
            return format!("yog-api = {{ path = {p:?} }}");
        }
        let version = {
            let env_version = std::env::var("YOG_API_VERSION").ok();
            self.yog_api_version
                .as_deref()
                .or(env_version.as_deref())
                .map(|v| v.to_owned())
                .unwrap_or_else(latest_yog_api_version)
        };
        format!("yog-api = {:?}", version)
    }
}

// ── Reading ─────────────────────────────────────────────────────────────────

use yog_data::{Text, Value};
use yog_formats::manifest::ManifestFile;

/// `v` as TOML's inline syntax — how a dependency is written into Cargo.toml.
fn toml_inline(v: &Value) -> String {
    let quote = |s: &str| format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""));
    match v {
        Value::Map(m) => {
            let fields: Vec<String> = m
                .iter()
                .map(|(k, v)| {
                    let key = if k.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') { k.to_string() } else { quote(k) };
                    format!("{key} = {}", toml_inline(v))
                })
                .collect();
            format!("{{ {} }}", fields.join(", "))
        }
        Value::List(items) => format!("[{}]", items.iter().map(toml_inline).collect::<Vec<_>>().join(", ")),
        Value::Bool(b) => b.to_string(),
        Value::Int(n) => n.to_string(),
        Value::Float(f) => f.to_string(),
        other => quote(other.as_str().unwrap_or_default()),
    }
}

/// A text of `yog.toml` as `resolve_metadata` reads it: `@Set.key` or the words (`@@` for a leading `@`).
fn text_form(t: Text) -> Result<String, String> {
    match t {
        Text::Literal(s) => Ok(yog_data::typed::escape_at(&s)),
        Text::Res(r) => Ok(format!("@{}.{}", r.set, r.key)),
        Text::NameOf(_) | Text::Lang(_) => Err("a mod's name and description are text or a `.yres` text (`@Strings.mod_name`)".into()),
    }
}

/// Reads `yog.toml` (TOML, through Yog Data's schema: every problem with its line).
pub fn parse_yog_toml(text: &str) -> Result<YogToml, String> {
    // A dotted run header is nested tables to TOML: say how to write it.
    for (i, line) in text.lines().enumerate() {
        let l = line.trim();
        if let Some(name) = l.strip_prefix("[run.").and_then(|r| r.strip_suffix(']'))
            && name.contains('.')
            && !name.starts_with('"')
        {
            return Err(format!("yog.toml:{}: write the run target's name in quotes: [run.\"{name}\"]", i + 1));
        }
    }
    let read = yog_data::schema::from_toml::<ManifestFile>(text).map_err(|e| {
        e.0.iter()
            .map(|l| match l.at {
                Some(at) => format!("yog.toml:{}: {}{}", at.line, if l.path.is_root() { String::new() } else { format!("{}: ", l.path) }, l.message),
                None => format!("yog.toml: {}", l.message),
            })
            .collect::<Vec<_>>()
            .join("\n")
    })?;
    let f = read.value;
    let m = f.module;
    let mut dependencies = Vec::new();
    let mut mod_dependencies = Vec::new();
    let mut yog_api_version = None;
    for (name, spec) in f.dependencies.0 {
        match (name.as_str(), &spec) {
            ("exports", Value::Map(exports)) => mod_dependencies.extend(exports.iter().map(|(k, v)| (k.to_string(), toml_inline(v)))),
            ("yog-api" | "yog_api" | "yog_api_version", _) => yog_api_version = Some(spec.as_str().map(str::to_string).unwrap_or_else(|| toml_inline(&spec))),
            _ => dependencies.push((name, toml_inline(&spec))),
        }
    }
    let run_configs = f
        .run
        .0
        .into_iter()
        .map(|(name, r)| RunConfig {
            name,
            display_name: r.name,
            export_dir: r.export_dir,
            command: r.command,
            args: r.args,
            cwd: r.cwd,
            env: r.env.into_iter().filter_map(|kv| kv.split_once('=').map(|(k, v)| (k.to_string(), v.to_string()))).collect(),
        })
        .collect();
    let externals = f
        .external
        .0
        .into_iter()
        .map(|(namespace, e)| External {
            namespace,
            ids: [("items", e.items), ("blocks", e.blocks), ("entities", e.entities), ("recipes", e.recipes)]
                .into_iter()
                .filter(|(_, v)| !v.is_empty())
                .map(|(k, v)| (k.to_string(), v))
                .collect(),
        })
        .collect();
    let name = m.name.map(text_form).transpose()?;
    let description = m.description.map(text_form).transpose()?;
    let icon = m.icon.map(|i| match i {
        yog_data::Image::Source(s) => s,
        yog_data::Image::Res(r) => format!("@{}.{}", r.set, r.key),
    });
    Ok(YogToml {
        name: name.unwrap_or_else(|| m.id.clone()),
        version: m.version.unwrap_or_else(|| "0.1.0".into()),
        description: description.unwrap_or_default(),
        name_key: None,
        description_key: None,
        icon,
        authors: m.authors,
        license: m.license.unwrap_or_else(|| DEFAULT_LICENSE.into()),
        exports_license: m.exports_license,
        datapack: m.datapack,
        edition: m.edition,
        yog_api_path: f.dev.and_then(|d| d.yog_api_path),
        yog_api_version,
        dependencies,
        mod_dependencies,
        dev_dependencies: f.dev_dependencies.0.into_iter().map(|(k, v)| (k, toml_inline(&v))).collect(),
        run_configs,
        externals,
        id: m.id,
    })
}

/// Cargo derives a lib crate name from the package `name` by turning `-` into
/// `_`, but keeps case — so a mod `id` like "My-Mod" becomes the invalid
/// `My_Mod` and rustc warns on every build. `id` is a free-form project
/// identifier (not required to be a valid Rust ident), so the generated
/// wrapper pins `[lib] name` to a proper snake_case form instead.
pub fn to_snake_name(id: &str) -> String {
    let mut out = String::with_capacity(id.len());
    for c in id.chars() {
        if c == '-' || c == '_' {
            if !out.ends_with('_') {
                out.push('_');
            }
        } else if c.is_uppercase() {
            if !out.is_empty() && !out.ends_with('_') {
                out.push('_');
            }
            out.extend(c.to_lowercase());
        } else {
            out.push(c);
        }
    }
    out
}

/// rkyv version embedded at compile time via `build.rs`.
pub fn workspace_rkyv_version() -> String {
    env!("RKYV_VERSION").to_string()
}

/// Fetch the latest non-yanked version of `yog-api` from crates.io.
pub fn latest_yog_api_version() -> String {
    match std::process::Command::new("cargo")
        .args(["search", "yog-api", "--limit", "1"])
        .output()
    {
        Ok(out) if out.status.success() => {
            String::from_utf8_lossy(&out.stdout)
                .lines()
                .next()
                .and_then(|l| {
                    let mut parts = l.split_whitespace();
                    parts.next(); // skip crate name (e.g. "yog-api")
                    if parts.next() == Some("=") {
                        // skip the "=" separator
                        parts.next().map(|v| v.trim_matches('"').to_owned())
                    } else {
                        None
                    }
                })
                .unwrap_or_else(|| FALLBACK_API_VERSION.into())
        }
        _ => FALLBACK_API_VERSION.into(),
    }
}

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

    /// Yog-VLSI's manifest, as written — what the TOML reader that replaces
    /// this one must read the same.
    const VLSI: &str = r#"
[mod]
id          = "yog-vlsi"
name        = "@Strings.mod_name"
version     = "0.3.0"
description = "@Strings.mod_description"
authors     = ["F000NK", "Yog Team"]
license     = "AGPL-3.0-only"
edition     = "2024"

[dependencies]
serde      = { version = "1", features = ["derive"] }
serde_json = "1"
yog-api    = "0.93"
yog-kit    = "0.4"

[dependencies.exports]
yog-pipes = "0.5"

## a comment
[run."forge-1.21.1"]
name       = "Forge 1.21.1"
export_dir = "../Yog-Mod-Loader/forge/run/yog-mods"
command    = "./gradlew"
args       = ["runClient", "-Pminecraft_version=1.21.1"]
cwd        = "../Yog-Mod-Loader/forge"
env        = ["JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64"]

[external.farmersdelight]
items  = ["cutting_board", "tomato"]
blocks = ["stove"]
"#;

    #[test]
    fn reads_a_real_manifest() {
        let t = parse_yog_toml(VLSI).unwrap();
        assert_eq!((t.id.as_str(), t.name.as_str(), t.version.as_str()), ("yog-vlsi", "@Strings.mod_name", "0.3.0"));
        assert_eq!(t.authors, ["F000NK", "Yog Team"]);
        assert_eq!(t.license, "AGPL-3.0-only");
        assert_eq!(t.yog_api_version.as_deref(), Some("0.93"), "yog-api is taken out of the dependencies");
        let deps: Vec<&str> = t.dependencies.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(deps, ["serde", "serde_json", "yog-kit"]);
        assert_eq!(t.mod_dependencies, [("yog-pipes".to_string(), "\"0.5\"".to_string())]);
        let run = &t.run_configs[0];
        assert_eq!((run.name.as_str(), run.display_name.as_deref()), ("forge-1.21.1", Some("Forge 1.21.1")));
        assert_eq!(run.args, ["runClient", "-Pminecraft_version=1.21.1"]);
        assert_eq!(run.env, [("JAVA_HOME".to_string(), "/usr/lib/jvm/java-21-openjdk-amd64".to_string())]);
        let ext = &t.externals[0];
        assert_eq!(ext.namespace, "farmersdelight");
        assert_eq!(ext.ids[0], ("items".to_string(), vec!["cutting_board".to_string(), "tomato".to_string()]));
    }

    #[test]
    fn problems_say_where() {
        let e = parse_yog_toml("[mod]\nid = \"m\"\n\n[run.forge-1.21.1]\nname = \"F\"\n").unwrap_err();
        assert_eq!(e, "yog.toml:4: write the run target's name in quotes: [run.\"forge-1.21.1\"]");
        let e = parse_yog_toml("[mod]\nid = \"m\"\nautors = [\"me\"]\n\n[external.create]\nitem = [\"wrench\"]\n").unwrap_err();
        assert_eq!(e.lines().collect::<Vec<_>>(), [
            "yog.toml:3: mod.autors: unknown field `autors` — did you mean `authors`?",
            "yog.toml:6: external.create.item: unknown field `item` — did you mean `items`?",
        ]);
        let t = parse_yog_toml("[mod]\nid = \"m\"\nname = \"@@me\"\n").unwrap();
        assert_eq!(t.name, "@@me", "a literal @ stays escaped for resolve_metadata");
    }

    #[test]
    fn needs_an_id() {
        assert!(parse_yog_toml("[mod]\nname = \"x\"").is_err());
        let t = parse_yog_toml("[mod]\nid = \"m\"").unwrap();
        assert_eq!((t.name.as_str(), t.version.as_str()), ("m", "0.1.0"), "defaults");
    }
}