Launcher: data packs into a world

datapacks.rs lists a world's datapacks/ (zips and folders with
pack.mcmeta, as the game discovers them; off when datapacks.json lists them
disabled), adds a data pack zip under a free name (refusing resource packs:
no data/ folder) and removes one to the trash, forgetting it in
datapacks.json. The game turns a new pack on when the world opens.

Home: each world gets "Data packs", which opens its packs under the row
with Add data pack… and Remove; a zip dropped on a world goes into it.
CLI: `worlds datapack-list|datapack-add|datapack-remove <world>`;
datapack-remove needs confirm over MCP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-27 02:49:42 +01:00
parent cac63dedca
commit aa6fdac501
11 changed files with 640 additions and 4 deletions
+156
View File
@@ -0,0 +1,156 @@
//! A world's data packs: `<world>/datapacks/`, each a `.zip` or a folder with a `pack.mcmeta`, as
//! the game discovers them (`datapack::discover`). The game turns on every pack it finds there
//! that `<world>/datapacks.json` doesn't list as disabled, when the world opens or on `/reload`,
//! so adding one is copying it in.
use crate::packs::{entry, plain};
use std::fs;
use std::path::{Path, PathBuf};
const SETTINGS: &str = "datapacks.json";
#[derive(Clone, Debug, PartialEq)]
pub struct DataPack {
/// Its file or folder name in `datapacks/`; the game's id is `file/<name>`.
pub file: String,
pub path: PathBuf,
/// `pack.mcmeta`'s description as plain text.
pub description: String,
/// Off when `datapacks.json` lists it as disabled (the game's `/datapack disable`).
pub enabled: bool,
}
fn settings(world: &Path) -> serde_json::Value {
fs::read(world.join(SETTINGS))
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_else(|| serde_json::json!({}))
}
fn disabled(settings: &serde_json::Value) -> Vec<String> {
settings["disabled"]
.as_array()
.into_iter()
.flatten()
.filter_map(|v| v.as_str().map(str::to_string))
.collect()
}
/// The data packs of the world folder `world`, by name.
pub fn list(world: &Path) -> Vec<DataPack> {
let off = disabled(&settings(world));
let mut packs: Vec<DataPack> = fs::read_dir(world.join("datapacks"))
.into_iter()
.flatten()
.flatten()
.filter_map(|e| {
let path = e.path();
let file = e.file_name().to_str()?.to_string();
let zip = path.is_file() && file.to_ascii_lowercase().ends_with(".zip");
if !(zip || path.is_dir()) {
return None;
}
let meta: serde_json::Value =
serde_json::from_slice(&entry(&path, "pack.mcmeta")?).ok()?;
Some(DataPack {
enabled: !off.contains(&format!("file/{file}")),
description: plain(&meta["pack"]["description"]),
file,
path,
})
})
.collect();
packs.sort_by_key(|p| p.file.to_lowercase());
packs
}
/// Whether a zip is a data pack: a `pack.mcmeta` and a `data/` folder.
fn check(file: &Path) -> Result<(), String> {
let name = file
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let zip = fs::File::open(file)
.ok()
.and_then(|f| zip::ZipArchive::new(f).ok())
.ok_or_else(|| format!("{name} is not a zip file that can be read."))?;
if zip.index_for_name("pack.mcmeta").is_none() {
return Err(format!("{name} is not a pack: it has no pack.mcmeta."));
}
if !zip.file_names().any(|n| n.starts_with("data/")) {
return Err(format!(
"{name} has no data folder: it is a resource pack, not a data pack."
));
}
Ok(())
}
/// Copies a data pack zip into the world's `datapacks/` under a free name. The game turns it on
/// the next time the world opens (or on `/reload`).
pub fn add(world: &Path, file: &Path) -> Result<DataPack, String> {
check(file)?;
let dir = world.join("datapacks");
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let name = file.file_name().ok_or("A pack file has a name")?;
let stem = Path::new(name)
.file_stem()
.unwrap_or(name)
.to_string_lossy();
let target = (1..)
.map(|n| match n {
1 => dir.join(name),
n => dir.join(format!("{stem} ({n}).zip")),
})
.find(|p| !p.exists())
.unwrap();
fs::copy(file, &target).map_err(|e| format!("Could not copy {}: {e}", file.display()))?;
let file_name = target.file_name().unwrap().to_string_lossy().into_owned();
// A pack of the same name removed while it was disabled would stay off.
forget(world, &file_name)?;
list(world)
.into_iter()
.find(|p| p.file == file_name)
.ok_or_else(|| format!("{} is not a data pack the game reads", target.display()))
}
/// Drops `file/<name>` from both lists of `datapacks.json`, when it is there.
fn forget(world: &Path, file: &str) -> Result<(), String> {
let mut s = settings(world);
let id = format!("file/{file}");
let mut changed = false;
for key in ["enabled", "disabled"] {
if let Some(list) = s[key].as_array_mut() {
let before = list.len();
list.retain(|v| v.as_str() != Some(id.as_str()));
changed |= list.len() != before;
}
}
if !changed {
return Ok(());
}
let text = serde_json::to_string_pretty(&s).unwrap();
fs::write(world.join(SETTINGS), text).map_err(|e| format!("{SETTINGS}: {e}"))
}
/// The data pack a command names: its file name, with or without `.zip`.
pub fn find(world: &Path, query: &str) -> Result<DataPack, String> {
list(world)
.into_iter()
.find(|p| p.file == query || p.file.strip_suffix(".zip") == Some(query))
.ok_or_else(|| {
format!(
"No data pack {query} in {}",
world.join("datapacks").display()
)
})
}
/// Moves the data pack to the system's trash and forgets it in `datapacks.json`.
pub fn remove(world: &Path, pack: &DataPack) -> Result<(), String> {
crate::desktop_seams::to_trash(&pack.path)
.map_err(|e| format!("Could not move {} to the trash: {e}", pack.file))?;
forget(world, &pack.file)
}
#[cfg(test)]
#[path = "datapacks/tests.rs"]
mod tests;