gdenv-lib 1.1.0

The best command-line tool to install and switch between multiple versions of Godot.
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
use crate::cargo::CargoInfoProvider;
use crate::gdextension_config::GdExtensionConfig;
use crate::godot_version::GodotVersion;
use anyhow::{Context, Result};
use documented::{Documented, DocumentedFieldsOpt};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum ProjectSpecError {
    #[error(
        "No gdenv.toml or .godot-version file found in current directory or in parent directories."
    )]
    NotFound,
    #[error("Failed to parse Godot project configuration file {0}: {1}")]
    ParseError(PathBuf, String),
    #[error(transparent)]
    IoError(#[from] std::io::Error),
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

/// Godot configuration project specification
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct ProjectSpecification {
    /// Path to the project root directory.
    /// This could be the same as `spec_file_path` or the current directory,
    /// depending on the existence of a `gdenv.toml` file.
    pub project_root_dir: PathBuf,
    /// Path to the project specification file.
    /// If None, no `gdenv.toml` file was found, so gdenv will use the current directory.
    pub spec_file_path: Option<PathBuf>,
    /// Godot version to use when running the project.
    pub godot_version: GodotVersion,
    /// Path to the Godot project directory.
    pub godot_project_dir: PathBuf,
    /// Additional arguments to pass to the Godot executable.
    pub run_args: Vec<String>,
    /// Additional arguments to pass to Godot when launching in editor mode.
    pub editor_args: Vec<String>,
    /// Run the editor in headless import mode if the .godot folder doesn't exist.
    pub pre_import: bool,
    /// .gdextension file generation configuration.
    pub gdextension: HashMap<String, GdExtensionConfig>,
    /// Godot addon specifications. The name given in this field will
    /// be used as the addon's name in the project's `addons` directory.
    pub addons: HashMap<String, AddonSpec>,
}

/// # The Godot project management file: `gdenv.toml`
/// # The following sections are available:
#[derive(Serialize, Deserialize, Documented, Debug, Default)]
#[serde(deny_unknown_fields)]
pub struct ProjectSpecificationToml {
    /// Specifications for the Godot project.
    pub godot: SpecGodot,
    /// .gdextension file generation configuration.
    pub gdextension: Option<HashMap<String, SpecGdExtensionGenerator>>,
    /// Godot addon specifications. The name given in this field will
    /// be used as the addon's name in the project's `addons` directory.
    pub addon: Option<HashMap<String, AddonSpec>>,
}

/// # --------------------------------------------------------------------------------
/// # Describes the Godot project.
/// # Required.
/// [godot]
#[derive(Serialize, Deserialize, Documented, DocumentedFieldsOpt, Debug, Default)]
#[serde(deny_unknown_fields)]
pub struct SpecGodot {
    /// # Godot version to use when running the project.
    /// # Required.
    /// version = "4.6.0-stable"
    pub version: String,

    /// # Whether to use the .NET version of Godot. Optional.
    /// #dotnet = false
    pub dotnet: Option<bool>,

    /// # Path to the Godot project directory. Optional. Example: "./godot"
    /// #project_dir = "."
    pub project_dir: Option<PathBuf>,

    /// # Additional arguments to pass to the Godot executable. Optional.
    /// # Example: ["--debug", "--no-window", "--headless"]
    /// #run_args = []
    pub run_args: Option<Vec<String>>,

    /// # Additional arguments to pass to Godot when launching in editor mode. Optional.
    /// # Example: ["--debug", "--no-window", "--headless"]
    /// #editor_args = []
    pub editor_args: Option<Vec<String>>,

    /// # Before opening the project, run the editor in headless import mode
    /// # to import the project when the `.godot` folder doesn't yet exist.
    /// # Useful when opening newly Git cloned projects. Optional.
    /// #pre_import = true
    pub pre_import: Option<bool>,
}

/// # --------------------------------------------------------------------------------
/// # Describes how one-or-more gdextension files should be generated.
/// # The <name> field is only for your convenience.
/// # The gdextension file can be generated for various project <type>s, covered below.
/// # More project types can be added in the future. Optional.
/// [gdextension.<name>.<type>]
#[derive(Serialize, Deserialize, Documented, Debug, Eq, PartialEq, Clone)]
#[serde(deny_unknown_fields)]
pub enum SpecGdExtensionGenerator {
    /// Generate a gdextension file for a rust project.
    Rust(SpecRustGdExtension),
}

/// # Generate a gdextension file for a rust project.
/// [gdextension.<name>.Rust]
#[derive(
    Serialize, Deserialize, Documented, DocumentedFieldsOpt, Debug, Eq, PartialEq, Clone, Default,
)]
#[serde(deny_unknown_fields)]
pub struct SpecRustGdExtension {
    /// # Path to the folder containing Cargo.toml. Used to find Cargo's build target directory. Required.
    /// # Example: "./rust"
    /// cargo_crate_path = "."
    pub cargo_crate_path: PathBuf,

    /// # File name for the gdextension config: `<config_name>.gdextension`. Optional.
    /// #config_name = "rust"
    pub config_name: Option<String>,

    /// # GdExtension API version compatability. Optional.
    /// #compatability_version = 4.1
    pub compatability_version: Option<String>,

    /// # GdExtension entry symbol for the shared library. Optional.
    /// #entry_symbol = "gdext_rust_init"
    pub entry_symbol: Option<String>,

    /// # Is the shared library hot reloadable? Optional.
    /// #reloadable = false
    pub reloadable: Option<bool>,
}

/// # --------------------------------------------------------------------------------
/// # Describes how one-or-more Godot addons should be synchronized.
/// # The <name> field determines the addon's default directory name,
/// # e.g. `addons/<name>/...files...`. Optional.
/// [addon.<name>]
#[derive(Serialize, Deserialize, Documented, DocumentedFieldsOpt, Debug, Eq, PartialEq, Clone)]
pub struct AddonSpec {
    /// # Paths to include from the addon's source directory. Optional.
    /// #include = []
    pub include: Option<Vec<PathBuf>>,

    /// # Paths to exclude from the addon's source directory. Optional.
    /// #exclude = []
    pub exclude: Option<Vec<PathBuf>>,

    /// # Path relative to project_dir to place addon files.
    /// # Defaults to <godot_project_dir>/addons/<addon_name>.
    /// #destination = "./custom/location"
    pub destination: Option<PathBuf>,

    #[serde(flatten)]
    pub source: AddonSource,
}

/// # Addons can be sourced from one of the following options:
/// #  - Git repository.
/// #  - Local directory.
#[derive(Serialize, Deserialize, Documented, Debug, Eq, PartialEq, Clone)]
#[serde(untagged, rename = "addon source type")]
pub enum AddonSource {
    /// Addon sourced from a Git repository.
    Git(GitAddonSource),
    /// Addon sourced from a local directory.
    Local(LocalAddonSource),
}

/// # -- Git repository specific addon fields:
#[derive(Serialize, Deserialize, Documented, DocumentedFieldsOpt, Debug, Eq, PartialEq, Clone)]
#[serde(deny_unknown_fields)]
pub struct GitAddonSource {
    /// # Git repository URL. Required.
    /// #git = "https://github.com/bytemeadow/gdenv.git"
    pub git: String,

    /// # Git reference to 'checkout' (branch, tag, commit hash, etc). Optional.
    /// #rev = "main"
    pub rev: Option<String>,

    /// # Sub-directory, relative to the repository root, to source the addon files from. Optional.
    /// #subdir = ""
    pub subdir: Option<PathBuf>,
}

/// # -- Local directory specific addon fields:
#[derive(Serialize, Deserialize, Documented, DocumentedFieldsOpt, Debug, Eq, PartialEq, Clone)]
#[serde(deny_unknown_fields)]
pub struct LocalAddonSource {
    /// # Path to the directory whose contents will be copied to the destination directory. Required.
    /// #path = "/path/to/local/addon"
    pub path: PathBuf,
}

pub fn spec_documentation() -> Result<String> {
    let out = [
        struct_doc::<ProjectSpecificationToml>(),
        struct_doc_f::<SpecGodot>(),
        struct_doc::<SpecGdExtensionGenerator>(),
        struct_doc_f::<SpecRustGdExtension>(),
        struct_doc_f::<AddonSpec>(),
        struct_doc_f::<GitAddonSource>(),
        struct_doc_f::<LocalAddonSource>(),
    ];
    Ok(out.join("\n"))
}

fn struct_doc_f<T: Documented + DocumentedFieldsOpt>() -> String {
    let fields = T::FIELD_DOCS
        .iter()
        .filter_map(|x| *x)
        .map(|doc| format!("{}\n", doc));
    [
        T::DOCS.to_string(),
        fields.collect::<Vec<String>>().join("\n"),
    ]
    .join("\n\n")
}

fn struct_doc<T: Documented>() -> String {
    [T::DOCS, ""].join("\n")
}

/// Loads the Godot project specification from a given starting path.
///
/// This function attempts to locate and parse a Godot project configuration file within the
/// directory tree starting from the given `start_path`. It supports two types of configuration
/// files:
///
/// - `gdenv.toml`: A TOML-based configuration file that defines various project settings.
/// - `.godot-version`: A simple file that specifies the Godot version information.
///
/// # Arguments
///
/// * `start_path` - A reference to the starting directory path where the search for the
///   project configuration file begins.
pub fn load_godot_project_spec<P: CargoInfoProvider>(
    start_path: &Path,
    cargo_target_path_provider: P,
) -> Result<ProjectSpecification, ProjectSpecError> {
    let spec_file = find_godot_project_spec(start_path)?;
    match spec_file {
        SpecFileType::Toml {
            dir_path,
            file_path,
        } => {
            let str_spec = fs::read_to_string(&file_path)?;
            let spec = toml::from_str::<ProjectSpecificationToml>(&str_spec).context(format!(
                "Failed to parse Godot project configuration file gdenv.toml: {}",
                file_path.display()
            ))?;
            let project_dir = spec.godot.project_dir.unwrap_or(PathBuf::from("."));
            Ok(ProjectSpecification {
                project_root_dir: dir_path,
                spec_file_path: Some(file_path.clone()),
                godot_version: GodotVersion::new(
                    &spec.godot.version,
                    spec.godot.dotnet.unwrap_or(false),
                )?,
                godot_project_dir: project_dir.clone(),
                run_args: spec.godot.run_args.unwrap_or_default(),
                editor_args: spec.godot.editor_args.unwrap_or_default(),
                pre_import: spec.godot.pre_import.unwrap_or(true),
                gdextension: gdextension_generator_to_config(
                    file_path.parent().unwrap_or(start_path),
                    spec.gdextension.unwrap_or_default(),
                    &project_dir,
                    cargo_target_path_provider,
                )?,
                addons: spec.addon.unwrap_or_default(),
            })
        }
        SpecFileType::Version {
            dir_path,
            file_path,
        } => {
            let file_content = fs::read_to_string(&file_path)?;
            let mut version_str = file_content.trim().split(' ');
            let version = version_str
                .next()
                .context("No version specified in .godot-version file.")?;
            let dotnet = version_str.next().unwrap_or("");
            Ok(ProjectSpecification {
                project_root_dir: dir_path,
                spec_file_path: Some(file_path),
                godot_version: GodotVersion::new(version, dotnet == "dotnet" || dotnet == "mono")?,
                godot_project_dir: PathBuf::from("."),
                run_args: vec![],
                editor_args: vec![],
                pre_import: true,
                gdextension: HashMap::default(),
                addons: HashMap::default(),
            })
        }
    }
}

fn gdextension_generator_to_config<P: CargoInfoProvider>(
    working_dir: &Path,
    generators: HashMap<String, SpecGdExtensionGenerator>,
    godot_project_path: &Path,
    cargo_info_provider: P,
) -> Result<HashMap<String, GdExtensionConfig>> {
    generators
        .into_iter()
        .map(|(name, generator)| -> Result<(String, GdExtensionConfig)> {
            match generator {
                SpecGdExtensionGenerator::Rust(generator) => {
                    let cargo_info = &cargo_info_provider(
                        &working_dir
                            .join(&generator.cargo_crate_path)
                            .join("Cargo.toml"),
                    )?;
                    let mut config = GdExtensionConfig::start(
                        &cargo_info.crate_name,
                        &working_dir.join(godot_project_path),
                        &cargo_info.target_dir,
                    );
                    if let Some(config_name) = &generator.config_name {
                        config = config.config_file_name(&format!("{}.gdextension", config_name));
                    }
                    if let Some(compatability_version) = &generator.compatability_version {
                        config = config.compatability_version(compatability_version);
                    }
                    if let Some(entry_symbol) = &generator.entry_symbol {
                        config = config.entry_symbol(entry_symbol);
                    }
                    if let Some(reloadable) = generator.reloadable {
                        config = config.reloadable(reloadable);
                    }
                    Ok((name, config))
                }
            }
        })
        .collect()
}

enum SpecFileType {
    Toml {
        dir_path: PathBuf,
        file_path: PathBuf,
    },
    Version {
        dir_path: PathBuf,
        file_path: PathBuf,
    },
}

/// Searches for 'gdproject.toml' or '.godot-version' starting from `start_path`
/// and moving upwards towards the root. 'gdproject.toml' takes precedence.
fn find_godot_project_spec(start_path: &Path) -> Result<SpecFileType, ProjectSpecError> {
    let mut current_dir = start_path.to_path_buf();

    loop {
        // 1. Check for the TOML file first (precedence)
        let toml_path = current_dir.join("gdenv.toml");
        if toml_path.exists() {
            return Ok(SpecFileType::Toml {
                dir_path: current_dir,
                file_path: toml_path,
            });
        }

        // 2. Check for the .godot-version file
        let version_path = current_dir.join(".godot-version");
        if version_path.exists() {
            return Ok(SpecFileType::Version {
                dir_path: current_dir,
                file_path: version_path,
            });
        }

        // Move to the parent directory
        if !current_dir.pop() {
            // Reached the filesystem root
            break;
        }
    }

    Err(ProjectSpecError::NotFound)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cargo::CargoInfo;
    use crate::godot_version::GodotVersion;
    use anyhow::bail;

    #[test]
    fn test_gdenv_toml_project_spec_full() -> Result<()> {
        let tmp_dir = tempfile::Builder::new().prefix("gdenv-test").tempdir()?;
        let version_file = tmp_dir.path().join("gdenv.toml");
        let str_spec = r#"
[godot]
version = "4.6.0-stable"
dotnet = true
project_dir = "./godot"
run_args = ["arg1", "arg2"]
editor_args = ["arg3", "arg4"]
pre_import = false

[gdextension.config_a.Rust]
cargo_crate_path = "rust"
config_name = "not_rust"
compatability_version = "4.2"
entry_symbol = "my_entry_symbol"
reloadable = true

[gdextension.config_b.Rust]
cargo_crate_path = "rust"

[addon.dialogic]
git = "https://github.com/dialogic-godot/dialogic"
rev = "main"

[addon.curtains]
git = "https://github.com/DragonAxe/gd-bvy-curtains"
rev = "other_ref"

[addon.gdunit4]
git = "https://github.com/godot-gdunit-labs/gdUnit4"
include = ["addons/gdUnit4"]

[addon.local-project]
path = "../local-project"
        "#;
        fs::write(&version_file, str_spec)?;
        let cargo_info = CargoInfo {
            crate_name: "my_gdextension".to_string(),
            target_dir: PathBuf::from("/home/user/.cache/cargo/target"),
        };
        let spec = load_godot_project_spec(tmp_dir.path(), |_| Ok(cargo_info.clone()))?;
        let expected_spec = ProjectSpecification {
            project_root_dir: tmp_dir.path().to_path_buf(),
            spec_file_path: Some(version_file),
            godot_version: GodotVersion::new("4.6.0", true)?,
            godot_project_dir: PathBuf::from("./godot"),
            run_args: vec!["arg1".to_string(), "arg2".to_string()],
            editor_args: vec!["arg3".to_string(), "arg4".to_string()],
            pre_import: false,
            gdextension: HashMap::from([
                (
                    "config_a".to_string(),
                    GdExtensionConfig::start(
                        &cargo_info.crate_name,
                        &tmp_dir.path().join("./godot"),
                        &cargo_info.target_dir,
                    )
                    .config_file_name("not_rust.gdextension")
                    .compatability_version("4.2")
                    .entry_symbol("my_entry_symbol")
                    .reloadable(true),
                ),
                (
                    "config_b".to_string(),
                    GdExtensionConfig::start(
                        &cargo_info.crate_name,
                        &tmp_dir.path().join("./godot"),
                        &cargo_info.target_dir,
                    ),
                ),
            ]),
            addons: HashMap::from([
                (
                    "dialogic".to_string(),
                    AddonSpec {
                        include: None,
                        exclude: None,
                        destination: None,
                        source: AddonSource::Git(GitAddonSource {
                            git: "https://github.com/dialogic-godot/dialogic".to_string(),
                            rev: Some("main".to_string()),
                            subdir: None,
                        }),
                    },
                ),
                (
                    "curtains".to_string(),
                    AddonSpec {
                        include: None,
                        exclude: None,
                        destination: None,
                        source: AddonSource::Git(GitAddonSource {
                            git: "https://github.com/DragonAxe/gd-bvy-curtains".to_string(),
                            rev: Some("other_ref".to_string()),
                            subdir: None,
                        }),
                    },
                ),
                (
                    "gdunit4".to_string(),
                    AddonSpec {
                        include: Some(vec![PathBuf::from("addons/gdUnit4")]),
                        exclude: None,
                        destination: None,
                        source: AddonSource::Git(GitAddonSource {
                            git: "https://github.com/godot-gdunit-labs/gdUnit4".to_string(),
                            rev: None,
                            subdir: None,
                        }),
                    },
                ),
                (
                    "local-project".to_string(),
                    AddonSpec {
                        include: None,
                        exclude: None,
                        destination: None,
                        source: AddonSource::Local(LocalAddonSource {
                            path: PathBuf::from("../local-project"),
                        }),
                    },
                ),
            ]),
        };
        assert_eq!(spec, expected_spec);
        Ok(())
    }

    #[test]
    fn test_gdenv_toml_project_spec_minimal() -> Result<()> {
        let tmp_dir = tempfile::Builder::new().prefix("gdenv-test").tempdir()?;
        let version_file = tmp_dir.path().join("gdenv.toml");
        let str_spec = r#"
[godot]
version = "4.6.0"
        "#;
        fs::write(version_file, str_spec)?;
        let spec =
            load_godot_project_spec(tmp_dir.path(), |_| bail!("Test lambda not implemented."))?;
        assert_eq!(spec.godot_version, GodotVersion::new("4.6.0", false)?);
        Ok(())
    }

    #[test]
    fn test_gdenv_toml_project_spec_empty() -> Result<()> {
        let tmp_dir = tempfile::Builder::new().prefix("gdenv-test").tempdir()?;
        let version_file = tmp_dir.path().join("gdenv.toml");
        let str_spec = r#""#;
        fs::write(version_file, str_spec)?;
        let spec =
            load_godot_project_spec(tmp_dir.path(), |_| bail!("Test lambda not implemented."));
        assert!(spec.is_err());
        Ok(())
    }

    #[test]
    fn test_godot_version_file_full() -> Result<()> {
        let tmp_dir = tempfile::Builder::new().prefix("gdenv-test").tempdir()?;
        let version_file = tmp_dir.path().join(".godot-version");
        let str_spec = "4.6 dotnet";
        fs::write(version_file, str_spec)?;

        let spec =
            load_godot_project_spec(tmp_dir.path(), |_| bail!("Test lambda not implemented."))?;

        assert_eq!(spec.godot_version, GodotVersion::new("4.6.0-stable", true)?);

        Ok(())
    }

    #[test]
    fn test_godot_version_file_version_only() -> Result<()> {
        let tmp_dir = tempfile::Builder::new().prefix("gdenv-test").tempdir()?;
        let version_file = tmp_dir.path().join(".godot-version");
        let str_spec = "4.6";
        fs::write(version_file, str_spec)?;

        let spec =
            load_godot_project_spec(tmp_dir.path(), |_| bail!("Test lambda not implemented."))?;

        assert_eq!(
            spec.godot_version,
            GodotVersion::new("4.6.0-stable", false)?
        );

        Ok(())
    }

    #[test]
    fn test_godot_version_file_empty() -> Result<()> {
        let tmp_dir = tempfile::Builder::new().prefix("gdenv-test").tempdir()?;
        let version_file = tmp_dir.path().join(".godot-version");
        let str_spec = "";
        fs::write(version_file, str_spec)?;
        let spec =
            load_godot_project_spec(tmp_dir.path(), |_| bail!("Test lambda not implemented."));
        assert!(spec.is_err());
        Ok(())
    }
}