use std::{
env, fs,
path::{Path, PathBuf},
};
use anyhow::{Context, Result, anyhow};
use crate::{
bundled,
config::{
CompatibilityVerdict, GdsuiteConfig, InstalledContractsState, InstalledState,
InstalledToolState, Manifest, ReleaseManifest, ToolAcquireSpec,
},
process,
};
pub const GD_DIR: &str = ".gdsuite";
const GDTEST_HARNESS_PATH: &str = "addons/gdtest/gdtest_worker.gd";
const GDTEST_EDITOR_PLUGIN_DIR: &str = "addons/gdtest_editor";
pub const GDHEALTH_ARTIFACT_DIR: &str = "reports/code-health";
#[derive(Debug, Clone)]
pub struct ProjectContext {
pub root: PathBuf,
pub gdsuite_dir: PathBuf,
pub state_dir: PathBuf,
pub config_path: PathBuf,
pub manifest_path: PathBuf,
pub installation_path: PathBuf,
pub versions_path: PathBuf,
}
#[derive(Debug, Clone)]
pub struct Toolchain {
pub godot_exe: PathBuf,
pub gdtidy: PathBuf,
pub gdtest: PathBuf,
pub gdhealth: PathBuf,
pub gdtypecheck: PathBuf,
}
#[derive(Debug, Clone)]
pub struct InstallPlan {
pub gdtest: ToolAcquireSpec,
pub gdhealth: ToolAcquireSpec,
pub gdtypecheck: ToolAcquireSpec,
pub gdtidy: ToolAcquireSpec,
}
#[derive(Debug, Clone)]
pub struct InstallOutcome {
pub manifest: Manifest,
pub requested: InstallPlan,
}
#[derive(Debug, Clone)]
pub struct CompatibilityReport {
pub gdtest: ToolCompatibility,
pub gdhealth: ToolCompatibility,
pub gdtypecheck: ToolCompatibility,
pub gdtidy: ToolCompatibility,
}
#[derive(Debug, Clone)]
pub struct ToolCompatibility {
pub requested: String,
pub resolved_version: Option<String>,
pub verdict: CompatibilityVerdict,
pub reason: String,
pub extra: Vec<(String, String)>,
}
#[derive(Debug, Clone)]
struct ProbedToolchain {
gdtest_version: Option<String>,
gdtest_harness_version: Option<String>,
gdhealth_version: Option<String>,
gdhealth_schema_version: Option<u32>,
gdtypecheck_version: Option<String>,
gdtidy_version: Option<String>,
}
#[derive(Debug, Default, Clone)]
pub struct AddonInstallReport {
pub installed_files: usize,
pub skipped_modified: Vec<PathBuf>,
pub upgrade: Option<AddonUpgrade>,
}
#[derive(Debug, Clone)]
pub struct AddonUpgrade {
pub from_version: String,
pub to_version: String,
pub backup_dir: PathBuf,
pub replaced: Vec<PathBuf>,
}
impl ProjectContext {
pub fn new(root: PathBuf) -> Self {
let gdsuite_dir = root.join(GD_DIR);
let state_dir = gdsuite_dir.join("state");
Self {
config_path: root.join("gdsuite.toml"),
manifest_path: state_dir.join("manifest.json"),
installation_path: state_dir.join("installation.json"),
versions_path: state_dir.join("versions.json"),
root,
gdsuite_dir,
state_dir,
}
}
pub fn ensure_dirs(&self) -> Result<()> {
fs::create_dir_all(self.gdsuite_dir.join("bin"))?;
fs::create_dir_all(self.gdsuite_dir.join("tools"))?;
fs::create_dir_all(&self.state_dir)?;
Ok(())
}
}
const GITIGNORED: [&str; 4] = [
".godot/",
".gdsuite/",
"reports/gdsuite/",
"reports/code-health/",
];
pub fn ensure_gitignored(context: &ProjectContext) -> Result<()> {
let path = context.root.join(".gitignore");
let existing = fs::read_to_string(&path).unwrap_or_default();
let is_ignored = |entry: &str| {
existing
.lines()
.map(|line| line.trim().trim_start_matches('/'))
.any(|line| line == entry || line == entry.trim_end_matches('/'))
};
let missing: Vec<&str> = GITIGNORED
.into_iter()
.filter(|entry| !is_ignored(entry))
.collect();
if missing.is_empty() {
return Ok(());
}
let mut updated = existing.clone();
if !updated.is_empty() && !updated.ends_with('\n') {
updated.push('\n');
}
if !updated.is_empty() {
updated.push('\n');
}
updated.push_str("# Generated by gdsuite and its tools\n");
for entry in missing {
updated.push_str(entry);
updated.push('\n');
}
fs::write(&path, updated).with_context(|| format!("failed to write {}", path.display()))
}
pub fn load_dotenv_if_present(context: &ProjectContext) -> Result<()> {
let path = context.root.join(".env");
if !path.exists() {
return Ok(());
}
let body =
fs::read_to_string(&path).with_context(|| format!("failed to read {}", path.display()))?;
for (index, raw_line) in body.lines().enumerate() {
let line = raw_line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let line = line.strip_prefix("export ").unwrap_or(line).trim();
let Some((key, raw_value)) = line.split_once('=') else {
return Err(anyhow!(
"invalid .env entry at {}:{}",
path.display(),
index + 1
));
};
let key = key.trim();
if key.is_empty() {
return Err(anyhow!(
"invalid .env entry at {}:{}",
path.display(),
index + 1
));
}
if env::var_os(key).is_some() {
continue;
}
let value = parse_dotenv_value(raw_value.trim())
.ok_or_else(|| anyhow!("invalid .env value at {}:{}", path.display(), index + 1))?;
unsafe {
env::set_var(key, value);
}
}
Ok(())
}
fn parse_dotenv_value(raw: &str) -> Option<String> {
if raw.len() >= 2 && raw.starts_with('"') && raw.ends_with('"') {
let inner = &raw[1..raw.len() - 1];
return Some(
inner
.replace("\\n", "\n")
.replace("\\r", "\r")
.replace("\\t", "\t")
.replace("\\\"", "\"")
.replace("\\\\", "\\"),
);
}
if raw.len() >= 2 && raw.starts_with('\'') && raw.ends_with('\'') {
return Some(raw[1..raw.len() - 1].to_string());
}
let value = raw
.split_once('#')
.map(|(head, _)| head)
.unwrap_or(raw)
.trim()
.to_string();
Some(value)
}
pub fn load_config(context: &ProjectContext) -> Result<GdsuiteConfig> {
GdsuiteConfig::load(&context.config_path)
}
pub fn load_manifest(context: &ProjectContext) -> Result<Manifest> {
Manifest::load(&context.manifest_path)
}
pub fn save_manifest(context: &ProjectContext, manifest: &Manifest) -> Result<()> {
manifest.write(&context.manifest_path)
}
pub fn save_installation_state(context: &ProjectContext, state: &InstalledState) -> Result<()> {
state.write(&context.installation_path)
}
pub fn release_manifest() -> &'static ReleaseManifest {
ReleaseManifest::bundled()
}
pub fn install_plan(config: &GdsuiteConfig) -> InstallPlan {
let release = release_manifest();
InstallPlan {
gdtest: if config.tools.gdtest_source == default_gdtest_requested() {
release.tools.gdtest.acquire.clone()
} else {
parse_tool_source_spec(&config.tools.gdtest_source, "gdtest")
},
gdhealth: if config.tools.gdhealth_source == default_gdhealth_requested() {
release.tools.gdhealth.acquire.clone()
} else {
parse_tool_source_spec(&config.tools.gdhealth_source, "gdhealth")
},
gdtypecheck: if config.tools.gdtypecheck_source == default_gdtypecheck_requested() {
release.tools.gdtypecheck.acquire.clone()
} else {
parse_tool_source_spec(&config.tools.gdtypecheck_source, "gdtypecheck")
},
gdtidy: if config.tools.gdtidy_source == default_gdtidy_requested() {
release.tools.gdtidy.acquire.clone()
} else {
parse_tool_source_spec(&config.tools.gdtidy_source, "gdtidy")
},
}
}
fn default_gdtidy_requested() -> String {
release_manifest().tools.gdtidy.acquire.render_requested()
}
fn default_gdtest_requested() -> String {
release_manifest().tools.gdtest.acquire.render_requested()
}
fn default_gdhealth_requested() -> String {
release_manifest().tools.gdhealth.acquire.render_requested()
}
fn default_gdtypecheck_requested() -> String {
release_manifest()
.tools
.gdtypecheck
.acquire
.render_requested()
}
pub fn resolve_godot(
context: &ProjectContext,
cli_override: Option<&Path>,
config: Option<&GdsuiteConfig>,
) -> Result<PathBuf> {
let mut candidates = Vec::new();
if let Some(path) = cli_override {
candidates.push(path.to_path_buf());
}
if let Some(path) = env::var_os("GODOT_EXE") {
candidates.push(PathBuf::from(path));
}
if let Some(config) = config
&& let Some(path) = &config.project.godot_exe
{
candidates.push(path.clone());
}
if let Ok(manifest) = load_manifest(context)
&& let Some(path) = manifest.godot_exe
{
candidates.push(path);
}
if let Ok(path) = which::which("godot") {
candidates.push(path);
}
if let Ok(path) = which::which("godot4") {
candidates.push(path);
}
candidates.push(PathBuf::from(r"C:\Program Files\Godot\Godot.exe"));
candidates.push(PathBuf::from(r"C:\Program Files\Godot_v4\Godot.exe"));
for candidate in candidates {
if let Some(path) = resolve_command_candidate(&candidate) {
return Ok(path);
}
for path in process::candidate_paths(candidate) {
if path.exists() {
return Ok(path);
}
}
}
Err(anyhow!(
"could not resolve Godot executable for {}",
context.root.display()
))
}
fn resolve_command_candidate(candidate: &Path) -> Option<PathBuf> {
if candidate.is_absolute() || candidate.parent().is_some() {
return None;
}
let command = candidate.to_str()?;
which::which(command).ok()
}
pub fn resolve_toolchain(
context: &ProjectContext,
manifest: Option<&Manifest>,
) -> Result<Toolchain> {
let manifest = manifest.cloned().unwrap_or_default();
Ok(Toolchain {
godot_exe: manifest
.godot_exe
.ok_or_else(|| anyhow!("missing Godot path in manifest"))?,
gdtidy: manifest
.gdtidy
.or_else(|| find_binary(context, &["gdtidy"]))
.ok_or_else(|| anyhow!("missing gdtidy in manifest"))?,
gdtest: manifest
.gdtest
.or_else(|| find_binary(context, &["gdtest"]))
.ok_or_else(|| anyhow!("missing gdtest in manifest"))?,
gdhealth: manifest
.gdhealth
.or_else(|| find_binary(context, &["gdhealth"]))
.ok_or_else(|| anyhow!("missing gdhealth in manifest"))?,
gdtypecheck: manifest
.gdtypecheck
.or_else(|| find_binary(context, &["gdtypecheck"]))
.ok_or_else(|| anyhow!("missing gdtypecheck in manifest"))?,
})
}
pub fn install_toolchain(
context: &ProjectContext,
config: &GdsuiteConfig,
godot_exe: &Path,
) -> Result<InstallOutcome> {
let requested = install_plan(config);
let gdtest = install_tool(context, &requested.gdtest, "gdtest")?;
let gdhealth = install_tool(context, &requested.gdhealth, "gdhealth")?;
let gdtypecheck = install_tool(context, &requested.gdtypecheck, "gdtypecheck")?;
let gdtidy = install_tool(context, &requested.gdtidy, "gdtidy")?;
Ok(InstallOutcome {
manifest: Manifest {
godot_exe: Some(godot_exe.to_path_buf()),
gdtidy: Some(gdtidy),
gdtest: Some(gdtest),
gdhealth: Some(gdhealth),
gdtypecheck: Some(gdtypecheck),
},
requested,
})
}
pub fn verify_toolchain(context: &ProjectContext, toolchain: &Toolchain) -> Result<()> {
process::run_checked(
&toolchain.godot_exe,
&["--version".to_string()],
&context.root,
)?;
process::run_checked(&toolchain.gdtidy, &["--version".to_string()], &context.root)?;
process::run_checked(&toolchain.gdtest, &["--version".to_string()], &context.root)?;
process::run_checked(&toolchain.gdhealth, &["--help".to_string()], &context.root)?;
process::run_checked(
&toolchain.gdtypecheck,
&["--version".to_string()],
&context.root,
)?;
Ok(())
}
pub fn ensure_gdtest_class_cache(
context: &ProjectContext,
_config: &GdsuiteConfig,
godot_exe: &Path,
addon_report: &AddonInstallReport,
) -> Result<()> {
let runtime_dir = harness_parent_dir(GDTEST_HARNESS_PATH);
let runtime_res_dir = res_dir_from_rel_path(&runtime_dir);
let gdt_res_path = join_res_path(&runtime_res_dir, "gdt.gd");
let cache_path = context
.root
.join(".godot")
.join("global_script_class_cache.cfg");
let cache_has_gdt = fs::read_to_string(&cache_path)
.map(|body| body.contains(&format!("\"path\": \"{gdt_res_path}\"")))
.unwrap_or(false);
if addon_report.installed_files == 0 && cache_has_gdt {
return Ok(());
}
let args = vec![
"--headless".to_string(),
"--path".to_string(),
context.root.display().to_string(),
"--import".to_string(),
];
process::run_checked(godot_exe, &args, &context.root).with_context(|| {
format!(
"failed to build Godot class cache for gdtest runtime at {}",
gdt_res_path
)
})?;
Ok(())
}
pub fn all_bundled(config: &GdsuiteConfig) -> bool {
let plan = install_plan(config);
crate::config::TOOL_NAMES
.into_iter()
.all(|tool| *plan.get(tool) == ToolAcquireSpec::Bundled)
}
pub fn bundled_toolchain(
context: &ProjectContext,
cli_godot: Option<&Path>,
config: &GdsuiteConfig,
) -> Toolchain {
Toolchain {
godot_exe: resolve_godot(context, cli_godot, Some(config)).unwrap_or_default(),
gdtidy: process::bundled_tool_path("gdtidy"),
gdtest: process::bundled_tool_path("gdtest"),
gdhealth: process::bundled_tool_path("gdhealth"),
gdtypecheck: process::bundled_tool_path("gdtypecheck"),
}
}
pub fn ensure_test_addons(
context: &ProjectContext,
config: &GdsuiteConfig,
godot_exe: &Path,
) -> Result<Option<AddonInstallReport>> {
if install_plan(config).gdtest != ToolAcquireSpec::Bundled {
return Ok(None);
}
let required = release_manifest()
.contracts
.gdtest
.required_harness
.trim_start_matches("==")
.to_string();
let installed = harness_version_of(&context.root.join(GDTEST_HARNESS_PATH));
if installed.as_deref() == Some(required.as_str()) {
return Ok(None);
}
if godot_exe.as_os_str().is_empty() {
return Err(anyhow!(
"Godot not found, and tests need it; install Godot and add it to PATH, set GODOT_EXE, or pass --godot-exe"
));
}
context.ensure_dirs()?;
ensure_gitignored(context)?;
bundled::write_gdtest_addons(&tool_source_cache_dir(context, "gdtest"))?;
let report = install_gdtest_addons(context, config)?;
refresh_editor_links(context)?;
ensure_gdtest_class_cache(context, config, godot_exe, &report)?;
Ok(Some(report))
}
pub fn find_binary(context: &ProjectContext, names: &[&str]) -> Option<PathBuf> {
let roots = [
context.gdsuite_dir.join("tools").join("gdtidy").join("bin"),
context.gdsuite_dir.join("tools").join("gdtest").join("bin"),
context
.gdsuite_dir
.join("tools")
.join("gdhealth")
.join("bin"),
context
.gdsuite_dir
.join("tools")
.join("gdtypecheck")
.join("bin"),
context.gdsuite_dir.join("bin"),
];
for root in roots {
for name in names {
for candidate in process::candidate_paths(root.join(name)) {
if candidate.exists() {
return Some(candidate);
}
}
}
}
None
}
fn install_tool(
context: &ProjectContext,
requested: &ToolAcquireSpec,
name: &str,
) -> Result<PathBuf> {
let cargo = || {
which::which("cargo")
.with_context(|| format!("cargo is required to build {name} from this source"))
};
let root = context.gdsuite_dir.join("tools").join(name);
fs::create_dir_all(&root)
.with_context(|| format!("failed to create tool root {}", root.display()))?;
match requested {
ToolAcquireSpec::Bundled => {
fs::remove_dir_all(&root)
.with_context(|| format!("failed to clear {}", root.display()))?;
if name == "gdtest" {
bundled::write_gdtest_addons(&tool_source_cache_dir(context, name))?;
refresh_editor_links(context)?;
}
return Ok(process::bundled_tool_path(name));
}
ToolAcquireSpec::Path { path } => {
let package_root = resolve_package_root(&context.root.join(path), name)?;
let args = vec![
"install".to_string(),
"--path".to_string(),
package_root.display().to_string(),
"--root".to_string(),
root.display().to_string(),
"--force".to_string(),
];
process::run_checked(&cargo()?, &args, &context.root)?;
}
ToolAcquireSpec::Crate { .. }
| ToolAcquireSpec::GithubRelease { .. }
| ToolAcquireSpec::GithubReleaseRepo { .. } => {
return Err(unsupported_source(name, requested));
}
ToolAcquireSpec::Git { url, rev, subdir } => {
let source_root = tool_source_cache_dir(context, name);
if source_root.exists() {
fs::remove_dir_all(&source_root)
.with_context(|| format!("failed to remove {}", source_root.display()))?;
}
clone_git_source(url, rev, &source_root)?;
let package_root = subdir
.as_ref()
.map(|value| source_root.join(value))
.unwrap_or_else(|| source_root.clone());
if !package_root.exists() {
return Err(anyhow!(
"git source subdir does not exist for {}: {}",
name,
package_root.display()
));
}
let package_root = resolve_package_root(&package_root, name)?;
let args = vec![
"install".to_string(),
"--path".to_string(),
package_root.display().to_string(),
"--root".to_string(),
root.display().to_string(),
"--force".to_string(),
];
process::run_checked(&cargo()?, &args, &context.root)?;
}
}
for candidate in process::candidate_paths(root.join("bin").join(name)) {
if candidate.exists() {
return Ok(candidate);
}
}
Err(anyhow!("installing {} did not produce its binary", name))
}
fn unsupported_source(name: &str, source: &ToolAcquireSpec) -> anyhow::Error {
anyhow!(
"{name}: `{}` is no longer supported: the tools are built into gdsuite. Remove {name}_source from [tools] in gdsuite.toml (`gdsuite update` does it for gdsuite's own tools), or build {name} from a folder (path:) or a Git repository (git:)",
source.render_requested()
)
}
fn resolve_package_root(source_root: &Path, name: &str) -> Result<PathBuf> {
let manifest_path = source_root.join("Cargo.toml");
if !manifest_path.exists() {
return Ok(source_root.to_path_buf());
}
let text = fs::read_to_string(&manifest_path)
.with_context(|| format!("failed to read {}", manifest_path.display()))?;
let manifest: toml::Value = toml::from_str(&text)
.with_context(|| format!("failed to parse {}", manifest_path.display()))?;
if manifest.get("package").is_some() {
return Ok(source_root.to_path_buf());
}
let members = manifest
.get("workspace")
.and_then(|w| w.get("members"))
.and_then(|m| m.as_array())
.ok_or_else(|| anyhow!("workspace at {} has no members", source_root.display()))?;
for member in members {
let member_path = member
.as_str()
.ok_or_else(|| anyhow!("invalid workspace member"))?;
let candidate = source_root.join(member_path);
let member_manifest = candidate.join("Cargo.toml");
if !member_manifest.exists() {
continue;
}
let member_text = fs::read_to_string(&member_manifest)?;
let member_toml: toml::Value = toml::from_str(&member_text)?;
let package_name = member_toml
.get("package")
.and_then(|p| p.get("name"))
.and_then(|n| n.as_str());
if package_name == Some(name) {
return Ok(candidate);
}
}
Err(anyhow!(
"could not find package '{}' in workspace at {}",
name,
source_root.display()
))
}
fn parse_tool_source_spec(source: &str, default_name: &str) -> ToolAcquireSpec {
if source == "bundled" {
return ToolAcquireSpec::Bundled;
}
if let Some(rest) = source.strip_prefix("crate:")
&& let Some((name, version)) = rest.split_once('@')
&& !name.is_empty()
&& !version.is_empty()
{
return ToolAcquireSpec::Crate {
crate_name: name.to_string(),
version: version.to_string(),
};
}
if let Some(url) = source.strip_prefix("github:")
&& !url.is_empty()
{
if !url.starts_with("http://")
&& !url.starts_with("https://")
&& let Some((repo_path, tag)) = url.rsplit_once('@')
&& let Some((owner, repo)) = repo_path.split_once('/')
&& !owner.is_empty()
&& !repo.is_empty()
&& !tag.is_empty()
{
return ToolAcquireSpec::GithubReleaseRepo {
owner: owner.to_string(),
repo: repo.to_string(),
tag: tag.to_string(),
};
}
return ToolAcquireSpec::GithubRelease {
url: url.to_string(),
};
}
if let Some(rest) = source.strip_prefix("git:") {
let (url, query) = rest.split_once('?').unwrap_or((rest, ""));
let mut rev = None;
let mut subdir = None;
for pair in query.split('&').filter(|segment| !segment.is_empty()) {
if let Some((key, value)) = pair.split_once('=') {
match key {
"rev" => rev = Some(value.to_string()),
"subdir" => subdir = Some(value.to_string()),
_ => {}
}
}
}
if !url.is_empty()
&& let Some(rev) = rev
{
return ToolAcquireSpec::Git {
url: url.to_string(),
rev,
subdir,
};
}
}
if let Some(path) = source.strip_prefix("path:")
&& !path.is_empty()
{
return ToolAcquireSpec::Path {
path: path.to_string(),
};
}
if source.contains("://") {
return ToolAcquireSpec::Git {
url: source.to_string(),
rev: "HEAD".to_string(),
subdir: Some(default_name.to_string()),
};
}
ToolAcquireSpec::Path {
path: source.to_string(),
}
}
fn resolved_source_root(context: &ProjectContext, source: &str, name: &str) -> Result<PathBuf> {
match parse_tool_source_spec(source, name) {
ToolAcquireSpec::Path { path } => Ok(context.root.join(path)),
ToolAcquireSpec::Bundled => {
let source_root = tool_source_cache_dir(context, name);
if !source_root.exists() {
return Err(anyhow!(
"{name}'s files are missing from .gdsuite; run `gdsuite setup`"
));
}
Ok(source_root)
}
ToolAcquireSpec::Crate { .. }
| ToolAcquireSpec::GithubRelease { .. }
| ToolAcquireSpec::GithubReleaseRepo { .. } => Err(unsupported_source(
name,
&parse_tool_source_spec(source, name),
)),
ToolAcquireSpec::Git { .. } => {
let source_root = tool_source_cache_dir(context, name);
if !source_root.exists() {
return Err(anyhow!(
"tool source cache missing for {}; run `gdsuite setup` to install the toolchain",
name
));
}
normalize_extracted_root(&source_root)
}
}
}
pub fn gdsuite_link_path(context: &ProjectContext) -> PathBuf {
context
.gdsuite_dir
.join("bin")
.join(format!("gdsuite{}", std::env::consts::EXE_SUFFIX))
}
pub fn refresh_editor_links(context: &ProjectContext) -> Result<()> {
bundled::refresh_link(&gdtest_launcher_path(context))?;
bundled::refresh_link(&gdsuite_link_path(context))
}
pub fn gdtest_launcher_path(context: &ProjectContext) -> PathBuf {
context
.gdsuite_dir
.join("tools")
.join("gdtest")
.join("bin")
.join(format!("gdtest{}", std::env::consts::EXE_SUFFIX))
}
fn tool_source_cache_dir(context: &ProjectContext, name: &str) -> PathBuf {
context.gdsuite_dir.join("tools").join(name).join("source")
}
fn clone_git_source(url: &str, rev: &str, destination: &Path) -> Result<()> {
let git = which::which("git").context("git is required for git-based setup sources")?;
if let Some(parent) = destination.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create {}", parent.display()))?;
}
let clone_args = vec![
"clone".to_string(),
url.to_string(),
command_path(destination),
];
process::run_checked(&git, &clone_args, Path::new("."))?;
let fetch_args = vec![
"-C".to_string(),
command_path(destination),
"fetch".to_string(),
"--depth".to_string(),
"1".to_string(),
"origin".to_string(),
rev.to_string(),
];
process::run_checked(&git, &fetch_args, Path::new("."))?;
let checkout_args = vec![
"-C".to_string(),
command_path(destination),
"checkout".to_string(),
"FETCH_HEAD".to_string(),
];
process::run_checked(&git, &checkout_args, Path::new("."))?;
Ok(())
}
fn normalize_extracted_root(source_root: &Path) -> Result<PathBuf> {
let children = fs::read_dir(source_root)
.with_context(|| format!("failed to read {}", source_root.display()))?
.filter_map(|entry| entry.ok())
.collect::<Vec<_>>();
if children.len() == 1 {
let child = children[0].path();
if child.is_dir() {
return Ok(child);
}
}
Ok(source_root.to_path_buf())
}
fn command_path(path: &Path) -> String {
#[cfg(windows)]
{
let text = path.display().to_string();
text.strip_prefix(r"\\?\").unwrap_or(&text).to_string()
}
#[cfg(not(windows))]
{
path.display().to_string()
}
}
pub fn probe_installation_state(
context: &ProjectContext,
config: &GdsuiteConfig,
manifest: &Manifest,
requested: &InstallPlan,
) -> Result<InstalledState> {
let toolchain = resolve_toolchain(context, Some(manifest))?;
let probed = probe_toolchain(context, config, &toolchain)?;
Ok(InstalledState {
suite_version: release_manifest().suite.version.clone(),
manifest_version: release_manifest().suite.manifest_version,
tools: crate::config::InstalledToolsState {
gdtest: InstalledToolState {
requested: requested.gdtest.clone(),
resolved_version: probed.gdtest_version.clone(),
},
gdhealth: InstalledToolState {
requested: requested.gdhealth.clone(),
resolved_version: probed.gdhealth_version.clone(),
},
gdtypecheck: InstalledToolState {
requested: requested.gdtypecheck.clone(),
resolved_version: probed.gdtypecheck_version.clone(),
},
gdtidy: InstalledToolState {
requested: requested.gdtidy.clone(),
resolved_version: probed.gdtidy_version.clone(),
},
},
contracts: InstalledContractsState {
gdtest_harness_version: probed.gdtest_harness_version,
gdhealth_schema_version: probed.gdhealth_schema_version,
},
})
}
pub fn compatibility_report(state: &InstalledState) -> CompatibilityReport {
let release = release_manifest();
let gdtest = match (
&state.tools.gdtest.resolved_version,
&state.contracts.gdtest_harness_version,
) {
(Some(version), Some(harness))
if normalize_version(version) == normalize_version(harness) =>
{
let mut report = evaluate_versioned_tool(
"gdtest",
&state.tools.gdtest.requested,
version,
&release.tools.gdtest.acquire,
&release.tools.gdtest.tested,
vec![("gdtest_harness".to_string(), harness.clone())],
);
if normalize_version(harness)
!= normalize_spec(&release.contracts.gdtest.required_harness)
{
report.verdict = CompatibilityVerdict::Warning;
report.reason = format!(
"gdtest harness {} is outside the suite-tested harness {}",
harness,
normalize_spec(&release.contracts.gdtest.required_harness)
);
}
report
}
(Some(version), Some(harness)) => ToolCompatibility {
requested: state.tools.gdtest.requested.render_requested(),
resolved_version: Some(version.clone()),
verdict: CompatibilityVerdict::Error,
reason: format!("gdtest CLI {version} is incompatible with harness {harness}"),
extra: vec![("gdtest_harness".to_string(), harness.clone())],
},
(Some(version), None) => ToolCompatibility {
requested: state.tools.gdtest.requested.render_requested(),
resolved_version: Some(version.clone()),
verdict: CompatibilityVerdict::Error,
reason: "gdtest harness version could not be determined".to_string(),
extra: Vec::new(),
},
(None, _) => ToolCompatibility {
requested: state.tools.gdtest.requested.render_requested(),
resolved_version: None,
verdict: CompatibilityVerdict::Error,
reason: "gdtest version probe failed".to_string(),
extra: Vec::new(),
},
};
let gdhealth = match (
&state.tools.gdhealth.resolved_version,
state.contracts.gdhealth_schema_version,
) {
(Some(version), Some(schema))
if schema == release.contracts.gdhealth.required_schema_version =>
{
evaluate_versioned_tool(
"gdhealth",
&state.tools.gdhealth.requested,
version,
&release.tools.gdhealth.acquire,
&release.tools.gdhealth.tested,
vec![("gdhealth_schema".to_string(), schema.to_string())],
)
}
(Some(version), Some(schema)) => ToolCompatibility {
requested: state.tools.gdhealth.requested.render_requested(),
resolved_version: Some(version.clone()),
verdict: CompatibilityVerdict::Error,
reason: format!(
"gdhealth schema {} is incompatible with required schema {}",
schema, release.contracts.gdhealth.required_schema_version
),
extra: vec![("gdhealth_schema".to_string(), schema.to_string())],
},
(Some(version), None) => ToolCompatibility {
requested: state.tools.gdhealth.requested.render_requested(),
resolved_version: Some(version.clone()),
verdict: CompatibilityVerdict::Error,
reason: "gdhealth schema version could not be determined".to_string(),
extra: Vec::new(),
},
(None, _) => ToolCompatibility {
requested: state.tools.gdhealth.requested.render_requested(),
resolved_version: None,
verdict: CompatibilityVerdict::Error,
reason: "gdhealth version probe failed".to_string(),
extra: Vec::new(),
},
};
let gdtypecheck = match &state.tools.gdtypecheck.resolved_version {
Some(version) => evaluate_versioned_tool(
"gdtypecheck",
&state.tools.gdtypecheck.requested,
version,
&release.tools.gdtypecheck.acquire,
&release.tools.gdtypecheck.tested,
Vec::new(),
),
None => ToolCompatibility {
requested: state.tools.gdtypecheck.requested.render_requested(),
resolved_version: None,
verdict: CompatibilityVerdict::Error,
reason: "gdtypecheck version probe failed".to_string(),
extra: Vec::new(),
},
};
let gdtidy = match &state.tools.gdtidy.resolved_version {
Some(version) => evaluate_versioned_tool(
"gdtidy",
&state.tools.gdtidy.requested,
version,
&release.tools.gdtidy.acquire,
&release.tools.gdtidy.tested,
Vec::new(),
),
None => ToolCompatibility {
requested: state.tools.gdtidy.requested.render_requested(),
resolved_version: None,
verdict: CompatibilityVerdict::Error,
reason: "gdtidy version probe failed".to_string(),
extra: Vec::new(),
},
};
CompatibilityReport {
gdtest,
gdhealth,
gdtypecheck,
gdtidy,
}
}
pub fn report_status(report: &CompatibilityReport) -> CompatibilityVerdict {
let verdicts = [
&report.gdtest.verdict,
&report.gdhealth.verdict,
&report.gdtypecheck.verdict,
&report.gdtidy.verdict,
];
if verdicts
.iter()
.any(|verdict| **verdict == CompatibilityVerdict::Error)
{
CompatibilityVerdict::Error
} else if verdicts
.iter()
.any(|verdict| **verdict == CompatibilityVerdict::Warning)
{
CompatibilityVerdict::Warning
} else {
CompatibilityVerdict::Ok
}
}
fn evaluate_versioned_tool(
tool_name: &'static str,
requested: &ToolAcquireSpec,
version: &str,
release_requested: &ToolAcquireSpec,
tested_spec: &str,
extra: Vec<(String, String)>,
) -> ToolCompatibility {
let requested_rendered = requested.render_requested();
let tested_version = normalize_spec(tested_spec);
let is_override = requested_rendered != release_requested.render_requested();
let version_matches = normalize_version(version) == tested_version;
let (verdict, reason) = if is_override {
(
CompatibilityVerdict::Warning,
format!(
"{tool_name} was installed from `{}` and is outside the suite-tested set",
requested_rendered
),
)
} else if !version_matches {
(
CompatibilityVerdict::Warning,
format!(
"{tool_name} {} is outside the suite-tested version {}",
version, tested_version
),
)
} else {
(
CompatibilityVerdict::Ok,
format!("{tool_name} matches the suite-tested contract"),
)
};
ToolCompatibility {
requested: requested_rendered,
resolved_version: Some(version.to_string()),
verdict,
reason,
extra,
}
}
fn probe_toolchain(
context: &ProjectContext,
config: &GdsuiteConfig,
toolchain: &Toolchain,
) -> Result<ProbedToolchain> {
Ok(ProbedToolchain {
gdtest_version: probe_command_version(&toolchain.gdtest, &["--version"], context),
gdtest_harness_version: probe_gdtest_harness_version(context, config),
gdhealth_version: probe_command_version(&toolchain.gdhealth, &["--version"], context),
gdhealth_schema_version: probe_gdhealth_schema_version(&toolchain.gdhealth, context),
gdtypecheck_version: probe_command_version(&toolchain.gdtypecheck, &["--version"], context),
gdtidy_version: probe_command_version(&toolchain.gdtidy, &["--version"], context),
})
}
fn probe_command_version(path: &Path, args: &[&str], context: &ProjectContext) -> Option<String> {
let args = args
.iter()
.map(|value| value.to_string())
.collect::<Vec<_>>();
let output = process::run(path, &args, &context.root).ok()?;
if !output.status.success() {
return None;
}
output
.stdout
.lines()
.find_map(|line| extract_version_token(line.trim()))
}
fn extract_version_token(line: &str) -> Option<String> {
line.split_whitespace()
.find(|token| token.chars().next().is_some_and(|c| c.is_ascii_digit()))
.map(|value| value.trim_start_matches('v').to_string())
.or_else(|| {
line.split_whitespace()
.last()
.map(|value| value.trim_start_matches('v').to_string())
})
}
fn probe_gdtest_harness_version(
context: &ProjectContext,
_config: &GdsuiteConfig,
) -> Option<String> {
let harness_path = context.root.join(GDTEST_HARNESS_PATH);
let body = fs::read_to_string(harness_path).ok()?;
extract_quoted_assignment(&body, "HARNESS_VERSION")
}
fn probe_gdhealth_schema_version(path: &Path, context: &ProjectContext) -> Option<u32> {
for args in [["--schema-version"], ["schema-version"]] {
let args = args
.iter()
.map(|value| value.to_string())
.collect::<Vec<_>>();
let output = process::run(path, &args, &context.root).ok()?;
if !output.status.success() {
continue;
}
if let Some(value) = output
.stdout
.lines()
.find_map(|line| line.trim().parse::<u32>().ok())
{
return Some(value);
}
}
None
}
fn extract_quoted_assignment(body: &str, name: &str) -> Option<String> {
for line in body.lines() {
let line = line.trim();
if !line.contains(name) {
continue;
}
let start = line.find('"')?;
let end = line[start + 1..].find('"')?;
return Some(line[start + 1..start + 1 + end].to_string());
}
None
}
fn normalize_spec(spec: &str) -> String {
spec.trim_start_matches('=').trim().to_string()
}
fn normalize_version(version: &str) -> String {
version.trim().trim_start_matches('v').to_string()
}
pub fn unconverted_configs(context: &ProjectContext) -> Vec<PathBuf> {
let read = |name: &str| -> Option<toml::Table> {
fs::read_to_string(context.root.join(name))
.ok()
.and_then(|text| text.parse().ok())
};
let files = [read("gdtidy.toml"), read("gdsuite.toml")];
let has = |section: &str| {
files
.iter()
.flatten()
.any(|table| table.contains_key(section))
};
let mut found = Vec::new();
for (names, section) in [
(["gdlintrc", ".gdlintrc"], "lint"),
(["gdformatrc", ".gdformatrc"], "fmt"),
] {
if has(section) {
continue;
}
if let Some(path) = names
.into_iter()
.map(|name| context.root.join(name))
.find(|path| path.is_file())
{
found.push(path);
}
}
found
}
pub struct ToolConfigConversion {
pub files: Vec<String>,
pub target: String,
pub notes: Vec<String>,
}
pub fn convert_tool_configs(
context: &ProjectContext,
gdtidy: &Path,
) -> Result<Option<ToolConfigConversion>> {
let files = unconverted_configs(context);
if files.is_empty() {
return Ok(None);
}
let names: Vec<String> = files
.iter()
.map(|path| {
path.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default()
})
.collect();
let mut args = vec!["migrate".to_string()];
args.extend(names.iter().cloned());
let output = process::run(gdtidy, &args, &context.root)?;
if !output.status.success() {
return Err(anyhow!(
"could not convert {}: {}",
names.join(" and "),
output.stderr.trim()
));
}
let mut notes: Vec<String> = Vec::new();
let mut target = "gdtidy.toml".to_string();
for note in output
.stderr
.lines()
.filter_map(|line| line.trim().strip_prefix("gdtidy: "))
{
if let Some(wrote) = note.strip_prefix("wrote ") {
if let Some((path, _)) = wrote.split_once(" from ") {
target = path.to_string();
}
continue;
}
if !notes.iter().any(|seen| seen == note) {
notes.push(note.to_string());
}
}
Ok(Some(ToolConfigConversion {
files: names,
target,
notes,
}))
}
pub fn install_gdtest_addons(
context: &ProjectContext,
config: &GdsuiteConfig,
) -> Result<AddonInstallReport> {
let source_root = resolved_source_root(context, &config.tools.gdtest_source, "gdtest")?;
let runtime_source = source_root.join("addons").join("gdtest");
if !runtime_source.exists() {
return Err(anyhow!(
"gdtest runtime addon source missing at {}",
runtime_source.display()
));
}
let mut report = AddonInstallReport::default();
let harness_name = Path::new(GDTEST_HARNESS_PATH).file_name().unwrap();
let source_version = harness_version_of(&runtime_source.join(harness_name));
let project_version = harness_version_of(&context.root.join(GDTEST_HARNESS_PATH));
let backup_dir = match (&project_version, &source_version) {
(Some(from), Some(to)) if from != to => {
let backup_dir = context
.gdsuite_dir
.join("backups")
.join(format!("gdtest-addons-{from}"));
report.upgrade = Some(AddonUpgrade {
from_version: from.clone(),
to_version: to.clone(),
backup_dir: backup_dir.clone(),
replaced: Vec::new(),
});
Some(backup_dir)
}
_ => None,
};
let runtime_target_dir = harness_parent_dir(GDTEST_HARNESS_PATH);
let runtime_res_dir = res_dir_from_rel_path(&runtime_target_dir);
install_addon_dir(
&runtime_source,
&context.root.join(&runtime_target_dir),
AddonTarget {
project_root: &context.root,
backup_dir: backup_dir.as_deref(),
},
&mut report,
|relative, contents| rewrite_runtime_asset(relative, contents, &runtime_res_dir),
)?;
Ok(report)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OldEditorAddon {
Absent,
Removed { backup: PathBuf },
KeptModified,
}
pub fn retire_gdtest_editor_addon(context: &ProjectContext) -> Result<OldEditorAddon> {
let dir = context.root.join(GDTEST_EDITOR_PLUGIN_DIR);
if !dir.is_dir() {
return Ok(OldEditorAddon::Absent);
}
let shipped: Vec<(String, &str)> = gdtest::addon_files()
.filter_map(|(path, contents)| {
path.strip_prefix(GDTEST_EDITOR_PLUGIN_DIR)
.map(|relative| (relative.trim_start_matches('/').to_string(), contents))
})
.collect();
if !is_unchanged_copy(&dir, &dir, &shipped)? {
return Ok(OldEditorAddon::KeptModified);
}
let backup = context.gdsuite_dir.join("backups").join("gdtest_editor");
if backup.exists() {
fs::remove_dir_all(&backup)
.with_context(|| format!("failed to clear {}", backup.display()))?;
}
copy_dir(&dir, &backup)?;
fs::remove_dir_all(&dir).with_context(|| format!("failed to remove {}", dir.display()))?;
disable_editor_plugin(
&context.root.join("project.godot"),
&format!("res://{GDTEST_EDITOR_PLUGIN_DIR}/plugin.cfg"),
)?;
Ok(OldEditorAddon::Removed { backup })
}
fn is_unchanged_copy(root: &Path, dir: &Path, shipped: &[(String, &str)]) -> Result<bool> {
for entry in fs::read_dir(dir).with_context(|| format!("failed to read {}", dir.display()))? {
let path = entry?.path();
if path.is_dir() {
if !is_unchanged_copy(root, &path, shipped)? {
return Ok(false);
}
continue;
}
let relative = path
.strip_prefix(root)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
let Some((_, contents)) = shipped.iter().find(|(name, _)| *name == relative) else {
if relative.ends_with(".uid") {
continue;
}
return Ok(false);
};
let current = fs::read_to_string(&path).unwrap_or_default();
if comparable(¤t) != comparable(contents) {
return Ok(false);
}
}
Ok(true)
}
fn comparable(text: &str) -> String {
text.lines()
.filter(|line| !line.starts_with("version="))
.collect::<Vec<_>>()
.join("\n")
}
fn copy_dir(from: &Path, to: &Path) -> Result<()> {
fs::create_dir_all(to).with_context(|| format!("failed to create {}", to.display()))?;
for entry in fs::read_dir(from).with_context(|| format!("failed to read {}", from.display()))? {
let path = entry?.path();
let target = to.join(path.file_name().unwrap());
if path.is_dir() {
copy_dir(&path, &target)?;
} else {
fs::copy(&path, &target)
.with_context(|| format!("failed to copy {}", path.display()))?;
}
}
Ok(())
}
fn disable_editor_plugin(project_file: &Path, plugin: &str) -> Result<()> {
let Ok(text) = fs::read_to_string(project_file) else {
return Ok(());
};
let quoted = format!("\"{plugin}\"");
let edited: Vec<String> = text
.lines()
.map(|line| {
if !line.starts_with("enabled=PackedStringArray(") || !line.contains("ed) {
return line.to_string();
}
let inside = line
.trim_start_matches("enabled=PackedStringArray(")
.trim_end_matches(')');
let kept: Vec<&str> = inside
.split(',')
.map(str::trim)
.filter(|item| !item.is_empty() && *item != quoted)
.collect();
format!("enabled=PackedStringArray({})", kept.join(", "))
})
.collect();
let mut result = edited.join("\n");
if text.ends_with('\n') {
result.push('\n');
}
if result != text {
fs::write(project_file, result)
.with_context(|| format!("failed to write {}", project_file.display()))?;
}
Ok(())
}
fn harness_version_of(harness: &Path) -> Option<String> {
let body = fs::read_to_string(harness).ok()?;
extract_quoted_assignment(&body, "HARNESS_VERSION")
}
#[derive(Clone, Copy)]
struct AddonTarget<'a> {
project_root: &'a Path,
backup_dir: Option<&'a Path>,
}
fn install_addon_dir(
source_dir: &Path,
target_dir: &Path,
target: AddonTarget<'_>,
report: &mut AddonInstallReport,
rewrite: impl Fn(&Path, &str) -> String + Copy,
) -> Result<()> {
for entry in fs::read_dir(source_dir)
.with_context(|| format!("failed to read addon source {}", source_dir.display()))?
{
let entry = entry?;
let source_path = entry.path();
let relative = source_path.strip_prefix(source_dir).unwrap();
let target_path = target_dir.join(relative);
if entry.file_type()?.is_dir() {
fs::create_dir_all(&target_path)
.with_context(|| format!("failed to create {}", target_path.display()))?;
install_addon_dir(&source_path, &target_path, target, report, rewrite)?;
continue;
}
let contents = fs::read_to_string(&source_path)
.with_context(|| format!("failed to read {}", source_path.display()))?;
let rewritten = rewrite(relative, &contents);
if let Some(parent) = target_path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create {}", parent.display()))?;
}
if target_path.exists() {
let current = fs::read_to_string(&target_path)
.with_context(|| format!("failed to read {}", target_path.display()))?;
if current == rewritten {
continue;
}
let Some(backup_dir) = target.backup_dir else {
report.skipped_modified.push(target_path);
continue;
};
let relative_to_project = target_path
.strip_prefix(target.project_root)
.unwrap_or(&target_path);
let backup_path = backup_dir.join(relative_to_project);
if let Some(parent) = backup_path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("failed to create {}", parent.display()))?;
}
fs::write(&backup_path, current)
.with_context(|| format!("failed to back up {}", target_path.display()))?;
if let Some(upgrade) = report.upgrade.as_mut() {
upgrade.replaced.push(target_path.clone());
}
}
fs::write(&target_path, rewritten)
.with_context(|| format!("failed to write {}", target_path.display()))?;
report.installed_files += 1;
}
Ok(())
}
fn rewrite_runtime_asset(relative: &Path, contents: &str, runtime_res_dir: &str) -> String {
let runtime_prefix = join_res_path(runtime_res_dir, "gdunit4_chain.gd");
let compat_prefix = join_res_path(runtime_res_dir, "gdunit4_compat.gd");
match relative.to_string_lossy().replace('\\', "/").as_str() {
"gdtest_worker.gd" => contents
.replace("res://addons/gdtest/gdunit4_chain.gd", &runtime_prefix)
.replace("res://addons/gdtest/gdunit4_compat.gd", &compat_prefix),
"gdunit4_compat.gd" => {
contents.replace("res://addons/gdtest/gdunit4_chain.gd", &runtime_prefix)
}
_ => contents.to_string(),
}
}
fn harness_parent_dir(harness: &str) -> PathBuf {
Path::new(harness)
.parent()
.map(Path::to_path_buf)
.filter(|path| !path.as_os_str().is_empty())
.unwrap_or_else(|| PathBuf::from("."))
}
fn res_dir_from_rel_path(path: &Path) -> String {
let normalized = path.display().to_string().replace('\\', "/");
if normalized == "." || normalized.is_empty() {
"res://".to_string()
} else {
format!("res://{}", normalized.trim_end_matches('/'))
}
}
fn join_res_path(base: &str, file: &str) -> String {
if base.ends_with('/') {
format!("{base}{file}")
} else {
format!("{base}/{file}")
}
}
impl InstallPlan {
pub fn get(&self, tool: &str) -> &ToolAcquireSpec {
match tool {
"gdtest" => &self.gdtest,
"gdhealth" => &self.gdhealth,
"gdtypecheck" => &self.gdtypecheck,
"gdtidy" => &self.gdtidy,
_ => panic!("unknown tool {tool}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolDrift {
pub tool: &'static str,
pub wanted: String,
pub installed: String,
}
impl ToolDrift {
pub fn message(&self) -> String {
let fix = if self.wanted.starts_with("github:") || self.wanted.starts_with("crate:") {
"gdsuite update"
} else {
"gdsuite setup"
};
format!(
"{}: {} is installed, but this project now uses {}; run `{fix}`",
self.tool, self.installed, self.wanted
)
}
}
pub fn installed_drift(context: &ProjectContext, config: &GdsuiteConfig) -> Vec<ToolDrift> {
let Ok(state) = InstalledState::load(&context.installation_path) else {
return Vec::new();
};
let plan = install_plan(config);
crate::config::TOOL_NAMES
.into_iter()
.filter_map(|tool| {
let installed = match tool {
"gdtest" => &state.tools.gdtest,
"gdhealth" => &state.tools.gdhealth,
"gdtypecheck" => &state.tools.gdtypecheck,
_ => &state.tools.gdtidy,
};
let wanted = plan.get(tool);
(installed.requested != *wanted).then(|| ToolDrift {
tool,
wanted: wanted.render_requested(),
installed: installed.requested.render_requested(),
})
})
.collect()
}
pub fn outdated_pins(config: &GdsuiteConfig) -> Vec<(&'static str, String, String)> {
let release = release_manifest();
config
.tools
.pinned()
.into_iter()
.filter_map(|(tool, source)| {
let tag = format!("v{}", release.tool(tool)?.version());
let pinned = source.strip_prefix(&own_release_prefix(tool))?;
(pinned != tag).then(|| (tool, pinned.to_string(), tag))
})
.collect()
}
pub fn settings_sources(context: &ProjectContext) -> Vec<(&'static str, String)> {
let sections: Vec<String> = fs::read_to_string(&context.config_path)
.ok()
.and_then(|text| text.parse::<toml::Table>().ok())
.map(|table| table.keys().cloned().collect())
.unwrap_or_default();
let source = |keys: &[&str], file: &str| {
let found: Vec<String> = keys
.iter()
.filter(|key| sections.iter().any(|section| section == *key))
.map(|key| format!("[{key}]"))
.collect();
if !found.is_empty() {
format!("gdsuite.toml {}", found.join(" "))
} else if context.root.join(file).exists() {
file.to_string()
} else {
"defaults".to_string()
}
};
vec![
("test", source(&["test"], "gdtest.toml")),
("health", source(&["health"], "gdhealth.toml")),
("fmt_lint", source(&["fmt", "lint"], "gdtidy.toml")),
]
}
pub fn own_release_prefix(tool: &str) -> String {
format!("github:q-rault/{tool}@")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::ToolAcquireSpec;
fn write_shipped_editor_addon(root: &Path) {
for (path, contents) in gdtest::addon_files() {
if path.starts_with(GDTEST_EDITOR_PLUGIN_DIR) {
let target = root.join(path);
fs::create_dir_all(target.parent().unwrap()).unwrap();
fs::write(target, contents).unwrap();
}
}
}
#[test]
fn test_retire_removes_unchanged_gdtest_editor_addon() {
let dir = tempfile::tempdir().unwrap();
let context = ProjectContext::new(dir.path().to_path_buf());
write_shipped_editor_addon(dir.path());
fs::write(
dir.path().join("addons/gdtest_editor/extra.gd.uid"),
"uid://x",
)
.unwrap();
let cfg = dir.path().join("addons/gdtest_editor/plugin.cfg");
let older: String = fs::read_to_string(&cfg)
.unwrap()
.lines()
.map(|line| {
if line.starts_with("version=") {
"version=\"0.2.1\""
} else {
line
}
})
.collect::<Vec<_>>()
.join("\r\n");
fs::write(&cfg, older).unwrap();
fs::write(
dir.path().join("project.godot"),
"[editor_plugins]\n\nenabled=PackedStringArray(\"res://addons/gdtest_editor/plugin.cfg\", \"res://addons/gdsuite/plugin.cfg\")\n",
)
.unwrap();
let outcome = retire_gdtest_editor_addon(&context).unwrap();
let backup = context.gdsuite_dir.join("backups/gdtest_editor");
assert_eq!(
outcome,
OldEditorAddon::Removed {
backup: backup.clone()
}
);
assert!(!dir.path().join("addons/gdtest_editor").exists());
assert!(backup.join("plugin.cfg").exists());
assert_eq!(
fs::read_to_string(dir.path().join("project.godot")).unwrap(),
"[editor_plugins]\n\nenabled=PackedStringArray(\"res://addons/gdsuite/plugin.cfg\")\n"
);
}
#[test]
fn test_retire_keeps_changed_gdtest_editor_addon() {
let dir = tempfile::tempdir().unwrap();
let context = ProjectContext::new(dir.path().to_path_buf());
write_shipped_editor_addon(dir.path());
fs::write(
dir.path().join("addons/gdtest_editor/plugin.gd"),
"# mine\n",
)
.unwrap();
let outcome = retire_gdtest_editor_addon(&context).unwrap();
assert_eq!(outcome, OldEditorAddon::KeptModified);
assert!(dir.path().join("addons/gdtest_editor/plugin.gd").exists());
assert_eq!(
retire_gdtest_editor_addon(&ProjectContext::new(dir.path().join("none"))).unwrap(),
OldEditorAddon::Absent
);
}
#[test]
fn test_parse_github_release_repo_spec() {
let spec = parse_tool_source_spec("github:q-rault/gdtest@v0.1.0", "gdtest");
assert!(
matches!(spec, ToolAcquireSpec::GithubReleaseRepo { ref owner, ref repo, ref tag }
if owner == "q-rault" && repo == "gdtest" && tag == "v0.1.0")
);
}
#[test]
fn test_parse_github_release_url_still_works() {
let spec = parse_tool_source_spec("github:https://example.com/asset.tar.gz", "gdtest");
assert!(matches!(spec, ToolAcquireSpec::GithubRelease { ref url }
if url == "https://example.com/asset.tar.gz"));
}
#[test]
fn release_and_crate_sources_say_what_to_do_instead() {
for source in ["github:q-rault/gdtest@v0.1.0", "crate:gdtest@0.2.0"] {
let message =
unsupported_source("gdtest", &parse_tool_source_spec(source, "gdtest")).to_string();
assert!(
message.contains(source) && message.contains("gdsuite update"),
"{message}"
);
}
}
}