rayengine-cli 0.0.3

Project tools for rayengine games
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
//! First-party dependency edits preserve authored TOML and plugin configuration.
use super::*;
use toml_edit::{DocumentMut, Item, Table, value};

pub(crate) const NAMES: &[&str] = &["particles", "voxel", "beacons", "tilemap"];

pub(crate) fn edit(
    path: &Path,
    name: &str,
    add: bool,
    local: Option<&Path>,
    features: &[String],
) -> Result<Value> {
    let name = name.strip_prefix("rayengine-").unwrap_or(name);
    if !NAMES.contains(&name) {
        return Err(Failure::new(
            "unknown_plugin",
            format!("unknown plugin `{name}`; available: {}", NAMES.join(", ")),
        ));
    }
    let manifest = manifest(path)?;
    let root = manifest.parent().expect("manifest parent");
    let (project, _) = project_manifest(path, None)?;
    let project_path = project
        .as_ref()
        .map(|p| p.path.clone())
        .unwrap_or_else(|| root.join("rayengine.toml"));
    let mut cargo = document(&manifest)?;
    let mut config = if project_path.exists() {
        document(&project_path)?
    } else {
        let mut doc = DocumentMut::new();
        doc["schema_version"] = value(1);
        doc
    };
    let dependency = format!("rayengine-{name}");
    let meta = lifecycle::metadata(&manifest, false)?;
    let package = lifecycle::project_package(&meta, &manifest)?;
    // Renamed dependencies must be edited under their authored key.
    let existing = package["dependencies"]
        .as_array()
        .into_iter()
        .flatten()
        .find(|d| d["name"] == dependency && d["kind"].is_null() && d["target"].is_null());
    let key = existing
        .and_then(|d| d["rename"].as_str())
        .unwrap_or(&dependency)
        .to_string();
    let mut selected_path = None;
    if add {
        if existing.is_some()
            || cargo
                .get("dependencies")
                .and_then(|d| d.get(&key))
                .is_some()
        {
            return Err(Failure::new(
                "plugin_already_added",
                format!("{dependency} is already a dependency"),
            ));
        }
        if features.iter().any(|f| {
            f.is_empty()
                || !f
                    .bytes()
                    .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
        }) {
            return Err(Failure::new(
                "invalid_plugin",
                "plugin features must be nonempty feature names",
            ));
        }
        let sdk = package["dependencies"]
            .as_array()
            .into_iter()
            .flatten()
            .find(|d| d["name"] == "rayengine" && d["kind"].is_null() && d["target"].is_null())
            .ok_or_else(|| {
                Failure::new("missing_sdk", "the package needs a rayengine dependency")
            })?;
        let inferred = sdk["path"]
            .as_str()
            .map(|s| Path::new(s).join("../../plugins").join(name));
        let local = local.map(Path::to_path_buf).or(inferred);
        let mut entry = Table::new();
        if let Some(local) = local {
            let local = local.canonicalize().map_err(|e| {
                Failure::new(
                    "invalid_plugin",
                    format!(
                        "{}: {e}; supply --plugin-path for this SDK",
                        local.display()
                    ),
                )
            })?;
            let plugin_manifest = local.join("Cargo.toml").canonicalize().map_err(io_error)?;
            let plugin_meta = lifecycle::metadata(&plugin_manifest, false)?;
            let plugin = lifecycle::project_package(&plugin_meta, &plugin_manifest)?;
            if plugin["name"] != dependency {
                return Err(Failure::new(
                    "invalid_plugin",
                    format!("--plugin-path must point to {dependency}"),
                ));
            }
            if features.iter().any(|f| plugin["features"].get(f).is_none()) {
                return Err(Failure::new(
                    "invalid_plugin",
                    "requested feature does not exist in the local plugin",
                ));
            }
            // Read the SDK's authored core dependency rather than assuming its layout.
            let sdk_core = if let Some(path) = sdk["path"].as_str() {
                let sdk_manifest = Path::new(path)
                    .join("Cargo.toml")
                    .canonicalize()
                    .map_err(io_error)?;
                let sdk_meta = lifecycle::metadata(&sdk_manifest, false)?;
                lifecycle::project_package(&sdk_meta, &sdk_manifest)?["dependencies"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .find(|d| d["name"] == "rayengine-core" && d["kind"].is_null())
                    .cloned()
            } else {
                None
            };
            // Local source trees must agree so games do not acquire two incompatible SDKs.
            for dep in plugin["dependencies"]
                .as_array()
                .into_iter()
                .flatten()
                .filter(|d| d["name"] == "rayengine" || d["name"] == "rayengine-core")
            {
                let expected = if dep["name"] == "rayengine-core" && sdk["path"].is_string() {
                    sdk_core.as_ref().ok_or_else(|| {
                        Failure::new(
                            "plugin_sdk_mismatch",
                            "the local SDK must declare the plugin's rayengine-core dependency",
                        )
                    })?
                } else {
                    sdk
                };
                let expected_path = expected["path"].as_str().map(PathBuf::from);
                let compatible = match (expected_path, dep["path"].as_str()) {
                    (Some(expected), Some(actual)) => {
                        match (expected.canonicalize(), Path::new(actual).canonicalize()) {
                            (Ok(expected), Ok(actual)) => expected == actual,
                            _ => false,
                        }
                    }
                    (None, None) => {
                        expected["req"] == dep["req"] && expected["source"] == dep["source"]
                    }
                    _ => false,
                };
                if !compatible {
                    return Err(Failure::new(
                        "plugin_sdk_mismatch",
                        "plugin and game must use the same SDK source/version",
                    ));
                }
            }
            entry["path"] = value(
                local
                    .to_str()
                    .ok_or_else(|| Failure::new("invalid_plugin", "plugin path must be UTF-8"))?,
            );
            selected_path = Some(local);
        } else {
            if sdk["source"].as_str()
                != Some("registry+https://github.com/rust-lang/crates.io-index")
            {
                return Err(Failure::new(
                    "invalid_sdk",
                    "SDK sources outside crates.io require a compatible --plugin-path; version numbers alone do not identify the SDK source",
                ));
            }
            let req = sdk["req"]
                .as_str()
                .unwrap_or("")
                .trim_start_matches(['^', '~', '=']);
            if req.split('.').count() != 3 || !req.bytes().all(|c| c.is_ascii_digit() || c == b'.')
            {
                return Err(Failure::new(
                    "invalid_sdk",
                    "use a concrete SDK version or --plugin-path",
                ));
            }
            entry["version"] = value(format!("={req}"));
        }
        if cargo
            .get("dependencies")
            .is_some_and(|d| d.as_table_like().is_none())
        {
            return Err(Failure::new(
                "invalid_cargo_manifest",
                "dependencies must be a TOML table",
            ));
        }
        // Do not replace a user-configured dependency on a repeated add.
        if cargo
            .get("dependencies")
            .and_then(|d| d.get(&key))
            .is_some()
        {
            return Err(Failure::new(
                "plugin_already_added",
                format!("{dependency} is already a dependency"),
            ));
        }
        if !features.is_empty() {
            entry["features"] = value(features.iter().cloned().collect::<toml_edit::Array>());
        }
        if cargo.get("dependencies").is_none() {
            cargo["dependencies"] = Item::Table(Table::new());
        }
        cargo["dependencies"]
            .as_table_like_mut()
            .expect("validated dependencies")
            .insert(&dependency, Item::Table(entry));
        if config.get("plugins").is_none() {
            config["plugins"] = Item::Table(Table::new());
        }
        let namespaces = config["plugins"]
            .as_table_like_mut()
            .ok_or_else(|| Failure::new("invalid_project_manifest", "plugins must be a table"))?;
        if !namespaces.contains_key(name) {
            namespaces.insert(name, Item::Table(Table::new()));
        }
    } else {
        if existing.is_none() {
            return Err(Failure::new(
                "plugin_not_added",
                format!("{dependency} is not a direct dependency"),
            ));
        }
        let removed = cargo
            .get_mut("dependencies")
            .and_then(Item::as_table_like_mut)
            .and_then(|t| t.remove(&key));
        if removed.is_none() {
            return Err(Failure::new(
                "plugin_not_added",
                format!("{dependency} is not a direct dependency"),
            ));
        }
        remove_feature_references(&mut cargo, &key);
        remove_namespace(&mut config, name);
    }
    // Stage both files completely before replacing either authored manifest.
    let write_config = add || project.is_some();
    let mut cargo_file = Replacement::stage(&manifest, cargo.to_string().as_bytes())?;
    let mut project_file = if write_config {
        Some(Replacement::stage(
            &project_path,
            config.to_string().as_bytes(),
        )?)
    } else {
        None
    };
    cargo_file.install()?;
    // Cargo checks feature references and inherited workspace declarations.
    if let Err(error) = lifecycle::metadata(&manifest, false) {
        cargo_file.rollback()?;
        return Err(error);
    }
    if let Some(project_file) = &mut project_file {
        if let Err(error) = project_file.install() {
            cargo_file.rollback()?;
            return Err(error);
        }
        project_file.finished = true;
    }
    cargo_file.finished = true;
    Ok(
        json!({"manifest": manifest, "project_manifest": write_config.then_some(project_path), "plugin": name, "dependency": dependency, "plugin_path": selected_path, "features": features}),
    )
}

fn remove_namespace(doc: &mut DocumentMut, name: &str) {
    if let Some(plugins) = doc.get_mut("plugins").and_then(Item::as_table_like_mut) {
        plugins.remove(name);
    }
    if let Some(profiles) = doc.get_mut("profiles").and_then(Item::as_table_like_mut) {
        for (_, profile) in profiles.iter_mut() {
            if let Some(plugins) = profile.get_mut("plugins").and_then(Item::as_table_like_mut) {
                plugins.remove(name);
            }
        }
    }
}

pub(crate) fn document(path: &Path) -> Result<DocumentMut> {
    fs::read_to_string(path)
        .map_err(io_error)?
        .parse()
        .map_err(|e| Failure::new("invalid_cargo_manifest", format!("{}: {e}", path.display())))
}

fn remove_feature_references(doc: &mut DocumentMut, dependency: &str) {
    let Some(features) = doc.get_mut("features").and_then(Item::as_table_like_mut) else {
        return;
    };
    // An explicitly declared feature with the dependency's name remains valid;
    // implicit optional-dependency features disappear with their dependency.
    let explicit_feature = features.contains_key(dependency);
    for (_, feature) in features.iter_mut() {
        if let Some(values) = feature.as_array_mut() {
            values.retain(|value| {
                value.as_str().is_none_or(|name| {
                    name != format!("dep:{dependency}")
                        && !name.starts_with(&format!("{dependency}/"))
                        && !name.starts_with(&format!("{dependency}?/"))
                        && (name != dependency || explicit_feature)
                })
            });
        }
    }
}

/// An adjacent staged replacement and an inode backup for rollback without writes.
struct Replacement {
    path: PathBuf,
    temporary: PathBuf,
    backup: Option<PathBuf>,
    installed: bool,
    finished: bool,
}
impl Replacement {
    fn stage(path: &Path, contents: &[u8]) -> Result<Self> {
        use std::{
            io::Write,
            sync::atomic::{AtomicU64, Ordering},
        };
        static SEQUENCE: AtomicU64 = AtomicU64::new(0);
        let id = SEQUENCE.fetch_add(1, Ordering::Relaxed);
        let parent = path.parent().expect("manifest parent");
        let temporary = parent.join(format!(".rayengine-edit-{}-{id}.tmp", std::process::id()));
        // Exclusive creation never removes another writer's temporary file.
        let mut file = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temporary)
            .map_err(io_error)?;
        let mut replacement = Self {
            path: path.to_path_buf(),
            temporary,
            backup: None,
            installed: false,
            finished: false,
        };
        if path.exists() {
            let backup = parent.join(format!(".rayengine-edit-{}-{id}.bak", std::process::id()));
            fs::hard_link(path, &backup).map_err(io_error)?;
            replacement.backup = Some(backup);
            file.set_permissions(fs::metadata(path).map_err(io_error)?.permissions())
                .map_err(io_error)?;
        }
        file.write_all(contents).map_err(io_error)?;
        file.sync_all().map_err(io_error)?;
        Ok(replacement)
    }
    fn install(&mut self) -> Result<()> {
        fs::rename(&self.temporary, &self.path).map_err(io_error)?;
        self.installed = true;
        Ok(())
    }
    fn rollback(&mut self) -> Result<()> {
        if !self.installed {
            return Ok(());
        }
        let result = if let Some(backup) = &self.backup {
            fs::rename(backup, &self.path)
        } else {
            fs::remove_file(&self.path)
        };
        result.map_err(|error| {
            Failure::new(
                "io_failed",
                format!(
                    "could not restore {}: {error}; original remains at {}",
                    self.path.display(),
                    self.backup.as_deref().unwrap_or(&self.path).display()
                ),
            )
        })?;
        self.installed = false;
        Ok(())
    }
}
impl Drop for Replacement {
    fn drop(&mut self) {
        // Keep the backup if rollback itself failed, so original bytes survive.
        if self.installed && !self.finished && self.rollback().is_err() {
            return;
        }
        let _ = fs::remove_file(&self.temporary);
        if let Some(backup) = &self.backup {
            let _ = fs::remove_file(backup);
        }
    }
}