pite-project 0.2.0

Project manifest (pite.toml), res:// paths and templates.
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// SPDX-License-Identifier: MIT OR Apache-2.0
//! `pite-project`: `pite.toml` manifest, `res://` paths, templates.

#![forbid(unsafe_code)]

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

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

pub const MANIFEST_FILE: &str = "pite.toml";

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PiteManifest {
    #[serde(default)]
    pub project: ProjectMeta,
    #[serde(default)]
    pub export: ExportConfig,
    /// Pinned third-party packages (`pite vendor add`). The table is the
    /// lock: committed `vendor/` bytes must match it (`pite vendor verify`).
    /// No `form` field yet — absent means zipped wheels; unpacked trees
    /// arrive with explicit forms later, keeping this shape working.
    #[serde(default)]
    pub vendor: HashMap<String, VendorEntry>,
    #[serde(flatten, default)]
    pub extra: HashMap<String, toml::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectMeta {
    #[serde(default = "default_name")]
    pub name: String,
    #[serde(default = "default_version")]
    pub pite_version: String,
    #[serde(default = "default_main_scene")]
    pub main_scene: String,
    #[serde(default = "default_python")]
    pub python: String,
    #[serde(default)]
    pub author: String,
    #[serde(default)]
    pub icon: String,
    #[serde(default = "default_window_width")]
    pub window_width: u32,
    #[serde(default = "default_window_height")]
    pub window_height: u32,
    #[serde(flatten, default)]
    pub extra: HashMap<String, toml::Value>,
}

impl Default for ProjectMeta {
    fn default() -> Self {
        Self {
            name: default_name(),
            pite_version: default_version(),
            main_scene: default_main_scene(),
            python: default_python(),
            author: String::new(),
            icon: String::new(),
            window_width: default_window_width(),
            window_height: default_window_height(),
            extra: HashMap::new(),
        }
    }
}

fn default_name() -> String {
    "my-game".to_string()
}
fn default_version() -> String {
    "0.2.0".to_string()
}
fn default_main_scene() -> String {
    "res://scenes/main.pitescene".to_string()
}
fn default_python() -> String {
    "3.12".to_string()
}
fn default_window_width() -> u32 {
    1280
}
fn default_window_height() -> u32 {
    720
}

/// Export settings. Everything defaults. `platforms` was removed in 0.1.1
/// (export never read it); manifests that still carry it parse untouched
/// and warn via `validate_manifest`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportConfig {
    #[serde(default)]
    pub binary_name: Option<String>,
    #[serde(default)]
    pub include: Vec<String>,
    #[serde(flatten, default)]
    pub extra: HashMap<String, toml::Value>,
}

impl Default for ExportConfig {
    fn default() -> Self {
        Self {
            binary_name: None,
            include: Vec::new(),
            extra: HashMap::new(),
        }
    }
}

/// One pinned package in `[vendor]`. `sha256` covers the stored artifact:
/// the wheel file when zipped, a canonical tree hash when unpacked.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VendorEntry {
    pub version: String,
    pub sha256: String,
    /// False for transitive deps pulled in by `add`; true for asked-for ones.
    #[serde(default)]
    pub direct: bool,
}

pub fn load_manifest(dir: &Path) -> Result<PiteManifest> {
    let path = dir.join(MANIFEST_FILE);
    let text = std::fs::read_to_string(&path)
        .with_context(|| format!("cannot read {}", path.display()))?;
    toml::from_str(&text).with_context(|| format!("cannot parse {}", path.display()))
}

/// Write the manifest back to `dir/pite.toml`. Serializes through
/// `toml::Value` (sorted tables) so saves are byte-stable even with unknown
/// `extra` keys aboard; known fields land alphabetically on disk.
pub fn save_manifest(dir: &Path, manifest: &PiteManifest) -> Result<()> {
    let path = dir.join(MANIFEST_FILE);
    let value =
        toml::Value::try_from(manifest).with_context(|| "cannot encode manifest as TOML")?;
    let mut text =
        toml::to_string_pretty(&value).with_context(|| "cannot render manifest as TOML")?;
    text.push('\n');
    std::fs::write(&path, text).with_context(|| format!("cannot write {}", path.display()))
}

/// Replacement for a deprecated manifest key, if any. Empty today: the
/// registry exists so a future rename warns instead of silently changing meaning.
pub fn deprecated_replacement(field: &str) -> Option<&'static str> {
    let _ = field;
    None
}

/// Pure manifest validation: unknown/deprecated keys warn (sorted, stable),
/// impossible values error. Filesystem checks (icon exists) live in `pite check`.
pub fn validate_manifest(manifest: &PiteManifest) -> (Vec<String>, Vec<String>) {
    let mut errors = Vec::new();
    let mut warnings = Vec::new();
    let mut unknown: Vec<String> = manifest.extra.keys().cloned().collect();
    for key in manifest.project.extra.keys() {
        unknown.push(format!("project.{key}"));
    }
    for key in manifest.export.extra.keys() {
        unknown.push(format!("export.{key}"));
    }
    unknown.sort();
    for field in unknown {
        if field == "export.platforms" {
            warnings.push(
                "manifest: export.platforms is deprecated and ignored (removed in 0.1.1)"
                    .to_string(),
            );
            continue;
        }
        match deprecated_replacement(&field) {
            Some(use_instead) => warnings.push(format!(
                "manifest: {field:?} is deprecated, use {use_instead:?}"
            )),
            None => warnings.push(format!("manifest: unknown field {field:?}")),
        }
    }
    if manifest.project.python.is_empty() {
        errors.push("manifest: project.python must not be empty".to_string());
    }
    if manifest.project.window_width == 0 || manifest.project.window_height == 0 {
        errors.push(format!(
            "manifest: window is {}x{}, dimensions must be positive",
            manifest.project.window_width, manifest.project.window_height
        ));
    }
    if !manifest.project.icon.is_empty() && !manifest.project.icon.starts_with("res://") {
        errors.push(format!(
            "manifest: icon {:?} must be res:// or empty (absolute paths are forbidden)",
            manifest.project.icon
        ));
    }
    (errors, warnings)
}

pub fn find_project_root(start: &Path) -> Option<PathBuf> {
    let mut dir = if start.is_file() {
        start.parent()?.to_path_buf()
    } else {
        start.to_path_buf()
    };
    loop {
        if dir.join(MANIFEST_FILE).is_file() {
            return Some(dir);
        }
        if !dir.pop() {
            return None;
        }
    }
}

pub fn resolve_res(project_dir: &Path, res_path: &str) -> Option<PathBuf> {
    res_path
        .strip_prefix("res://")
        .map(|rel| project_dir.join(rel))
}

pub fn to_res_path(project_dir: &Path, path: &Path) -> Option<String> {
    path.strip_prefix(project_dir)
        .ok()
        .map(|rel| format!("res://{}", rel.to_string_lossy().replace('\\', "/")))
}

pub const TEMPLATE_PITE_TOML: &str = r#"[project]
name = "TEMPLATE_NAME"
pite_version = "0.2.0"
main_scene = "res://scenes/main.pitescene"
python = "3.12"
author = ""
icon = ""
window_width = 1280
window_height = 720
"#;

/// Fresh `main.pitescene` for `create_project`. The format version comes
/// from the `pite-scene` const so scaffolds track format bumps.
pub fn template_scene() -> String {
    format!(
        r#"format_version = {}
root = "root"

[[node]]
id = "root"
type = "Node2D"
name = "Main"

[[node]]
id = "player"
type = "Sprite2D"
name = "Player"
parent = "root"

[node.props]
texture = "res://assets/player.png"

[node.script]
path = "res://scripts/player.py"
class = "Player"

[[node]]
id = "cam"
type = "Camera2D"
name = "Camera"
parent = "root"

[node.props]
position = [100.0, 200.0]
"#,
        pite_scene::FORMAT_VERSION
    )
}

pub const TEMPLATE_SCRIPT: &str = r#"import pite


class Player(pite.Node2D):
    speed: float = 200.0

    def _ready(self):
        self.position = (100.0, 200.0)

    def _process(self, delta: float):
        x, y = self.position
        if pite.held("ArrowRight"):
            x += self.speed * delta
        if pite.held("ArrowLeft"):
            x -= self.speed * delta
        if pite.held("ArrowDown"):
            y += self.speed * delta
        if pite.held("ArrowUp"):
            y -= self.speed * delta
        if pite.pressed("Space"):
            x += 10.0
        self.position = (x, y)
"#;

/// Valid 1x1 RGBA PNG backing the `res://assets/player.png` reference in
/// [`template_scene()`], so fresh scaffolds pass `pite check`.
const TEMPLATE_PLAYER_PNG: &[u8] = &[
    137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0,
    0, 0, 31, 21, 196, 137, 0, 0, 0, 13, 73, 68, 65, 84, 120, 156, 99, 248, 255, 255, 255, 127, 0,
    9, 251, 3, 253, 42, 134, 227, 138, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
];

pub fn create_project(dest: &Path, name: &str, template: &str) -> Result<PathBuf> {
    if template != "minimal-2d" {
        anyhow::bail!("unknown template {template:?} (only \"minimal-2d\" exists)");
    }
    let dir = if dest.file_name().map(|n| n == name).unwrap_or(false) {
        dest.to_path_buf()
    } else {
        dest.join(name)
    };
    if dir.exists() {
        anyhow::bail!("{} already exists", dir.display());
    }
    std::fs::create_dir_all(dir.join("scenes")).with_context(|| "cannot create project dirs")?;
    std::fs::create_dir_all(dir.join("scripts"))?;
    std::fs::create_dir_all(dir.join("assets"))?;
    std::fs::write(
        dir.join(MANIFEST_FILE),
        TEMPLATE_PITE_TOML.replace("TEMPLATE_NAME", name),
    )?;
    std::fs::write(dir.join("scenes").join("main.pitescene"), template_scene())?;
    std::fs::write(dir.join("scripts").join("player.py"), TEMPLATE_SCRIPT)?;
    std::fs::write(dir.join("assets").join("player.png"), TEMPLATE_PLAYER_PNG)?;
    Ok(dir)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn tmpdir(tag: &str) -> PathBuf {
        let n = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("pite-manifest-{tag}-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn load_text(text: &str) -> PiteManifest {
        let dir = tmpdir("parse");
        std::fs::write(dir.join(MANIFEST_FILE), text).unwrap();
        let manifest = load_manifest(&dir).unwrap();
        std::fs::remove_dir_all(&dir).ok();
        manifest
    }

    #[test]
    fn old_manifest_parses_untouched() {
        let manifest = load_text("[project]\nname = \"old\"\n");
        assert_eq!(manifest.project.name, "old");
        assert_eq!(manifest.project.pite_version, "0.2.0");
        assert_eq!(manifest.project.main_scene, "res://scenes/main.pitescene");
        assert_eq!(manifest.project.python, "3.12");
        assert_eq!(manifest.project.author, "");
        assert_eq!(manifest.project.icon, "");
        assert_eq!(manifest.project.window_width, 1280);
        assert_eq!(manifest.project.window_height, 720);
        assert!(manifest.project.extra.is_empty());
        assert!(manifest.vendor.is_empty());
        let (errors, warnings) = validate_manifest(&manifest);
        assert!(errors.is_empty(), "got {errors:?}");
        assert!(warnings.is_empty(), "got {warnings:?}");
    }

    #[test]
    fn vendor_table_round_trips() {
        let dir = tmpdir("vendor");
        let mut manifest = load_text("[project]\nname = \"t\"\n");
        manifest.vendor.insert(
            "requests".to_string(),
            VendorEntry {
                version: "2.32.3".to_string(),
                sha256: "abc".to_string(),
                direct: true,
            },
        );
        manifest.vendor.insert(
            "urllib3".to_string(),
            VendorEntry {
                version: "2.2.2".to_string(),
                sha256: "def".to_string(),
                direct: false,
            },
        );
        save_manifest(&dir, &manifest).unwrap();
        let back = load_manifest(&dir).unwrap();
        assert_eq!(back.vendor.len(), 2);
        assert_eq!(back.vendor["requests"].version, "2.32.3");
        assert!(back.vendor["requests"].direct);
        assert!(!back.vendor["urllib3"].direct);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn bad_type_fails_loudly() {
        let dir = tmpdir("bad-type");
        std::fs::write(dir.join(MANIFEST_FILE), "[project]\nname = 5\n").unwrap();
        let err = load_manifest(&dir).unwrap_err();
        assert!(err.to_string().contains("cannot parse"), "got {err:#}");
        std::fs::write(
            dir.join(MANIFEST_FILE),
            "[project]\nname = \"x\"\nwindow_width = \"wide\"\n",
        )
        .unwrap();
        let err = load_manifest(&dir).unwrap_err();
        assert!(err.to_string().contains("cannot parse"), "got {err:#}");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn unknown_keys_survive_round_trip() {
        let manifest = load_text(
            "custom = 1\n\n[project]\nname = \"x\"\nnickname = \"y\"\n\n[export]\nbundle = true\n",
        );
        assert_eq!(
            manifest.project.extra.get("nickname"),
            Some(&toml::Value::String("y".to_string()))
        );
        let again: PiteManifest = toml::from_str(&toml::to_string(&manifest).unwrap()).unwrap();
        assert_eq!(manifest.extra, again.extra);
        assert_eq!(manifest.project.extra, again.project.extra);
        assert_eq!(manifest.export.extra, again.export.extra);
        let (_, warnings) = validate_manifest(&again);
        for field in ["custom", "project.nickname", "export.bundle"] {
            assert!(
                warnings.iter().any(|w| w.contains(field)),
                "missing warning for {field}, got: {warnings:?}"
            );
        }
    }

    #[test]
    fn impossible_values_are_errors() {
        let manifest = load_text(
            "[project]\nname = \"x\"\npython = \"\"\nwindow_width = 0\nicon = \"/abs/icon.png\"\n",
        );
        let (errors, _) = validate_manifest(&manifest);
        assert!(
            errors.iter().any(|e| e.contains("python")),
            "got {errors:?}"
        );
        assert!(errors.iter().any(|e| e.contains("0x")), "got {errors:?}");
        assert!(errors.iter().any(|e| e.contains("icon")), "got {errors:?}");
    }

    #[test]
    fn save_keeps_unknown_keys_and_edits() {
        let dir = tmpdir("save");
        std::fs::write(
            dir.join(MANIFEST_FILE),
            "custom = 1\n\n[project]\nname = \"x\"\nnickname = \"y\"\n",
        )
        .unwrap();
        let mut manifest = load_manifest(&dir).unwrap();
        manifest.project.name = "renamed".to_string();
        save_manifest(&dir, &manifest).unwrap();
        let again = load_manifest(&dir).unwrap();
        assert_eq!(again.project.name, "renamed");
        assert_eq!(
            again.project.extra.get("nickname"),
            Some(&toml::Value::String("y".to_string()))
        );
        assert_eq!(again.extra.get("custom"), Some(&toml::Value::Integer(1)));
        let (errors, _) = validate_manifest(&again);
        assert!(errors.is_empty(), "got {errors:?}");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn save_is_byte_stable() {
        let dir = tmpdir("save-stable");
        std::fs::write(
            dir.join(MANIFEST_FILE),
            "zeta = 1\nalpha = 2\n\n[project]\nname = \"x\"\n",
        )
        .unwrap();
        let manifest = load_manifest(&dir).unwrap();
        save_manifest(&dir, &manifest).unwrap();
        let first = std::fs::read_to_string(dir.join(MANIFEST_FILE)).unwrap();
        let reloaded = load_manifest(&dir).unwrap();
        save_manifest(&dir, &reloaded).unwrap();
        let second = std::fs::read_to_string(dir.join(MANIFEST_FILE)).unwrap();
        assert_eq!(first, second, "save churned:\n{first}\n---\n{second}");
        std::fs::remove_dir_all(&dir).ok();
    }
}