Open ChessBase databases (.cbh, .cbv) and zip/7z archives
New crate chess-import converts non-PGN sources to PGN in memory and returns a PgnDatabase, so the library, notation and analysis work unchanged: - .cbv archives (container rewritten after uncbv), .cbh with companion files (layout after the public Morphy format description): games, variations, comments with per-database code page detection, NAGs, squares/arrows, set-up positions, time spent, book chapters (guiding texts) as move-less records; - ChessBase figurines become piece letters, diagram/object markers handled, Western names in Cyrillic databases read correctly; - .zip/.7z with PGN (own encoding each), .cbh and .cbv; duplicates skipped; - .cbz/encrypted archives and 2CBH rejected with clear messages. Library: '+ Add database', format shown, import notes; comments keep paragraph breaks. Tests on the user's sample books (skipped when absent). Also: AUR PKGBUILD for 0.2.0 with the bundled Stockfish. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
26bf901124
commit
bb7d3b3fa6
31 changed files with 3618 additions and 64 deletions
160
crates/chess-import/tests/formats.rs
Normal file
160
crates/chess-import/tests/formats.rs
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
//! Every way into the importer: plain PGN, zip archives (with PGN in a legacy code
|
||||
//! page and in folders), an unpacked ChessBase database on disk.
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use chess_import::{Format, ImportError, Opened};
|
||||
|
||||
/// A fresh directory under the system temp dir, removed on drop.
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> TempDir {
|
||||
let p = std::env::temp_dir().join(format!(
|
||||
"chess-import-{tag}-{}-{:?}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
));
|
||||
std::fs::create_dir_all(&p).expect("temp dir");
|
||||
TempDir(p)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn open(path: &Path) -> Result<Opened, ImportError> {
|
||||
let never = AtomicBool::new(false);
|
||||
chess_import::open(path, &mut |_| {}, &never)
|
||||
}
|
||||
|
||||
const GAME: &str = "[Event \"Test\"]\n[White \"A\"]\n[Black \"B\"]\n[Result \"1-0\"]\n\n1. e4 e5 2. Qh5 Nc6 3. Bc4 Nf6 4. Qxf7# 1-0\n";
|
||||
|
||||
#[test]
|
||||
fn plain_pgn_is_unchanged() {
|
||||
let dir = TempDir::new("pgn");
|
||||
let p = dir.0.join("game.pgn");
|
||||
std::fs::write(&p, GAME).expect("write");
|
||||
let o = open(&p).expect("opens");
|
||||
assert_eq!(o.format, Format::Pgn);
|
||||
assert_eq!(o.db.len(), 1);
|
||||
assert!(o.notes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip_with_legacy_pgn_and_folders() {
|
||||
let dir = TempDir::new("zip");
|
||||
let p = dir.0.join("games.zip");
|
||||
let file = std::fs::File::create(&p).expect("create");
|
||||
let mut zip = zip::ZipWriter::new(file);
|
||||
let stored =
|
||||
zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
zip.start_file("one.pgn", stored).expect("entry");
|
||||
zip.write_all(GAME.as_bytes()).expect("data");
|
||||
// A Russian comment in Windows-1251, inside a folder.
|
||||
let (cp1251, _, _) = encoding_rs::WINDOWS_1251.encode(
|
||||
"[Event \"Тест\"]\n[White \"Алехин\"]\n[Black \"Капабланка\"]\n[Result \"*\"]\n\n1. d4 {Хороший ход} d5 *\n",
|
||||
);
|
||||
zip.add_directory("sub/", stored).expect("dir");
|
||||
zip.start_file("sub/two.PGN", stored).expect("entry");
|
||||
zip.write_all(&cp1251).expect("data");
|
||||
zip.start_file("readme.txt", stored).expect("entry");
|
||||
zip.write_all(b"not a database").expect("data");
|
||||
zip.finish().expect("finish");
|
||||
|
||||
let o = open(&p).expect("opens");
|
||||
assert_eq!(o.format, Format::Zip);
|
||||
assert_eq!(o.db.len(), 2);
|
||||
let second = o.db.raw_text(1).expect("text");
|
||||
assert!(
|
||||
second.contains("Алехин") && second.contains("Хороший ход"),
|
||||
"{second}"
|
||||
);
|
||||
|
||||
// The same archive under another extension is still recognized by its content.
|
||||
let renamed = dir.0.join("games.bin");
|
||||
std::fs::copy(&p, &renamed).expect("copy");
|
||||
assert_eq!(open(&renamed).expect("opens").format, Format::Zip);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zip_without_databases_and_unsupported_files() {
|
||||
let dir = TempDir::new("empty");
|
||||
let p = dir.0.join("empty.zip");
|
||||
let mut zip = zip::ZipWriter::new(std::fs::File::create(&p).expect("create"));
|
||||
zip.start_file("notes.txt", zip::write::SimpleFileOptions::default())
|
||||
.expect("entry");
|
||||
zip.write_all(b"hello").expect("data");
|
||||
zip.finish().expect("finish");
|
||||
assert!(matches!(open(&p), Err(ImportError::Empty)));
|
||||
|
||||
let cbz = dir.0.join("locked.cbz");
|
||||
std::fs::write(&cbz, b"whatever").expect("write");
|
||||
assert!(matches!(
|
||||
open(&cbz),
|
||||
Err(ImportError::Unsupported(
|
||||
chess_import::Unsupported::Encrypted
|
||||
))
|
||||
));
|
||||
let broken = dir.0.join("broken.cbv");
|
||||
std::fs::write(&broken, [8u8, 0, 1, 0, 0x95, 0, 0, 0, 1, 2, 3]).expect("write");
|
||||
assert!(matches!(open(&broken), Err(ImportError::Corrupt(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unpacked_chessbase_database_matches_its_archive() {
|
||||
// Unpack a book archive from the samples to disk and open its .cbh directly.
|
||||
let samples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../pgnFilesforExample");
|
||||
let Some(archive) = std::fs::read_dir(&samples).ok().and_then(|d| {
|
||||
d.flatten()
|
||||
.map(|e| e.path())
|
||||
.find(|p| p.extension().is_some_and(|e| e == "7z"))
|
||||
}) else {
|
||||
eprintln!("skipped: no .7z sample");
|
||||
return;
|
||||
};
|
||||
let dir = TempDir::new("cbh");
|
||||
let mut cbh = None;
|
||||
let mut reader = sevenz_rust2::ArchiveReader::new(
|
||||
std::fs::File::open(&archive).expect("open"),
|
||||
sevenz_rust2::Password::empty(),
|
||||
)
|
||||
.expect("7z");
|
||||
reader
|
||||
.for_each_entries(|entry, r| {
|
||||
let mut data = Vec::new();
|
||||
r.read_to_end(&mut data)?;
|
||||
let name = entry
|
||||
.name()
|
||||
.rsplit(['/', '\\'])
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
if !entry.is_directory() && !name.is_empty() && !name.ends_with(".cbv") {
|
||||
let p = dir.0.join(&name);
|
||||
std::fs::write(&p, data)?;
|
||||
if name.ends_with(".cbh") {
|
||||
cbh = Some(p);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
})
|
||||
.expect("unpack");
|
||||
let cbh = cbh.expect("archive holds a .cbh");
|
||||
let from_disk = open(&cbh).expect("opens");
|
||||
assert_eq!(from_disk.format, Format::ChessBase);
|
||||
let from_archive = open(&archive).expect("opens");
|
||||
assert_eq!(from_disk.db.len(), from_archive.db.len());
|
||||
for i in 0..from_disk.db.len() {
|
||||
assert_eq!(
|
||||
from_disk.db.raw_text(i),
|
||||
from_archive.db.raw_text(i),
|
||||
"record {i}"
|
||||
);
|
||||
}
|
||||
}
|
||||
123
crates/chess-import/tests/samples.rs
Normal file
123
crates/chess-import/tests/samples.rs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
//! Conversion of the real databases in `pgnFilesforExample/` (not in the repository:
|
||||
//! the tests skip what is missing).
|
||||
//!
|
||||
//! Every converted game must parse back without warnings, a ChessBase database must
|
||||
//! convert the same from its `.cbv` archive as unpacked, and texts must keep their
|
||||
//! letters.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use chess_core::Severity;
|
||||
use chess_import::{Format, Opened};
|
||||
|
||||
fn samples() -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../pgnFilesforExample")
|
||||
}
|
||||
|
||||
fn open(name: &str) -> Option<Opened> {
|
||||
let path = samples().join(name);
|
||||
if !path.exists() {
|
||||
eprintln!("skipped: {} not found", path.display());
|
||||
return None;
|
||||
}
|
||||
let never = AtomicBool::new(false);
|
||||
Some(chess_import::open(&path, &mut |_| {}, &never).expect("opens"))
|
||||
}
|
||||
|
||||
/// Parses every game; returns (games with moves, all PGN text joined).
|
||||
fn check_all(o: &Opened) -> (usize, String) {
|
||||
let mut with_moves = 0;
|
||||
let mut text = String::new();
|
||||
for i in 0..o.db.len() {
|
||||
let g = o.db.load_game(i).expect("game");
|
||||
assert!(
|
||||
g.max_severity().is_none_or(|s| s < Severity::Warning),
|
||||
"game {i}: {:?}\n{}",
|
||||
g.diagnostics,
|
||||
o.db.raw_text(i).unwrap_or_default()
|
||||
);
|
||||
if !g.game.mainline().is_empty() {
|
||||
with_moves += 1;
|
||||
}
|
||||
let raw = o.db.raw_text(i).unwrap_or_default();
|
||||
assert!(
|
||||
!raw.chars()
|
||||
.any(|c| c.is_control() && c != '\n' && c != '\t'),
|
||||
"game {i}: control characters in {raw:?}"
|
||||
);
|
||||
text.push_str(&raw);
|
||||
}
|
||||
(with_moves, text)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chessbase_archives_convert_cleanly() {
|
||||
for (name, games, texts) in [
|
||||
("Rubinstein russian.cbv", 129, 9),
|
||||
("Anand 01-14.cbv", 399, 0),
|
||||
("Endgame Manual.cbv", 847, 134),
|
||||
] {
|
||||
let Some(o) = open(name) else { continue };
|
||||
assert_eq!(o.format, Format::ChessBaseArchive);
|
||||
assert!(o.notes.is_empty(), "{name}: {:?}", o.notes);
|
||||
assert_eq!(o.db.len(), games + texts, "{name}: records");
|
||||
let (with_moves, _) = check_all(&o);
|
||||
// A few games of a book may be only a position with a comment.
|
||||
assert!(
|
||||
with_moves + texts + 5 >= games + texts,
|
||||
"{name}: {with_moves} games with moves"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texts_keep_their_letters() {
|
||||
if let Some(o) = open("Rubinstein russian.cbv") {
|
||||
let (_, text) = check_all(&o);
|
||||
assert!(text.contains("Размены необходимы, чтобы уравнять игру."));
|
||||
assert!(!text.contains('\u{fffd}'));
|
||||
}
|
||||
if let Some(o) = open("Endgame Manual.cbv") {
|
||||
let (_, text) = check_all(&o);
|
||||
assert!(
|
||||
text.contains("Nürnberg"),
|
||||
"Western tournament names in a Russian database"
|
||||
);
|
||||
assert!(!text.contains("Nьrnberg"));
|
||||
}
|
||||
if let Some(o) = open("Anand 01-14.cbv") {
|
||||
let (_, text) = check_all(&o);
|
||||
assert!(text.contains("3...Bg4"), "figurines become letters");
|
||||
// Only figurines before a square or a capture are converted; of the ~2600 in
|
||||
// the book two are typos ("19 ¥5", "5...¥Ne7") and stay as they are.
|
||||
assert!(text.matches('\u{a5}').count() <= 2);
|
||||
assert!(!text.contains('\u{e027}'));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn archives_with_both_forms_of_a_database() {
|
||||
// Each book archive holds the database unpacked and as .cbv: the two conversions
|
||||
// must be identical, so the archive yields one copy.
|
||||
let dir = samples();
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
eprintln!("skipped: no samples");
|
||||
return;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
if !name.ends_with(".7z") {
|
||||
continue;
|
||||
}
|
||||
let o = open(&name).expect("present");
|
||||
assert_eq!(o.format, Format::SevenZip);
|
||||
assert!(
|
||||
o.notes.len() == 1 && o.notes[0].contains("skipped"),
|
||||
"{name}: {:?}",
|
||||
o.notes
|
||||
);
|
||||
let (with_moves, _) = check_all(&o);
|
||||
assert!(with_moves > 10, "{name}");
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue