hexicon 0.1.0

Hexicon, for writing interactive fiction: builds a game, plays it in a terminal, tests it, documents it, and serves editors
//! `hexicon new`: a game to start from, in a new folder: a manifest
//! (`hexicon.toml`) and a first source (`start.hxn`) on Hexad, which
//! build and play as they are.

use std::path::Path;
use std::process::ExitCode;

/// The game's title, from its folder's name: `my-game` is "My Game".
fn title_of(name: &str) -> String {
    let words: Vec<String> = name
        .split(['-', '_', ' '])
        .filter(|word| !word.is_empty())
        .map(|word| {
            let mut chars = word.chars();
            chars.next().map_or_else(String::new, |first| {
                first.to_uppercase().chain(chars).collect()
            })
        })
        .collect();
    if words.is_empty() {
        "My Game".to_owned()
    } else {
        words.join(" ")
    }
}

/// A new IFID: a random UUID, as the IFID standard has them.
fn new_ifid() -> String {
    use std::hash::{BuildHasher, Hasher};
    let mut bytes = [0u8; 16];
    for chunk in bytes.chunks_mut(8) {
        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
        hasher.write_u64(0);
        chunk.copy_from_slice(&hasher.finish().to_le_bytes());
    }
    // Version 4 (random), variant 1.
    bytes[6] = (bytes[6] & 0x0F) | 0x40;
    bytes[8] = (bytes[8] & 0x3F) | 0x80;
    let hex: String = bytes.iter().map(|b| format!("{b:02X}")).collect();
    format!(
        "{}-{}-{}-{}-{}",
        &hex[..8],
        &hex[8..12],
        &hex[12..16],
        &hex[16..20],
        &hex[20..]
    )
}

/// A string as TOML writes one, in double quotes.
fn toml_string(text: &str) -> String {
    format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
}

/// A string as Hexicon writes one, in single quotes.
fn source_string(text: &str) -> String {
    format!("'{}'", text.replace('\\', "\\\\").replace('\'', "\\'"))
}

/// What a new game is built on: Hexad, and for a choice game, the
/// extensions its choices need.
fn libraries(choices: bool) -> &'static str {
    if choices {
        "[\"system\", { name = \"hexad\", include = [\"extensions/hypothetical\", \"extensions/choices\"] }]"
    } else {
        "[\"system\", \"hexad\"]"
    }
}

fn manifest(title: &str, image: &str, choices: bool) -> String {
    format!(
        "# {title}, a game for Hexicon.\n\
         \n\
         [game]\n\
         name = {}\n\
         libraries = {}\n\
         sources = [\"start\"]\n\
         image = {}\n\
         \n\
         [defines]\n\
         LANGUAGE = \"english\"\n",
        toml_string(title),
        libraries(choices),
        toml_string(image)
    )
}

fn start(title: &str, ifid: &str, choices: bool) -> String {
    if choices {
        return start_choices(title, ifid);
    }
    format!(
        "// Where {title} begins.\n\
         \n\
         import hexad;\n\
         \n\
         // The story: what it is called, who wrote it, and who the player\n\
         // is as it begins.\n\
         story: Story\n\
         \x20   IFID = '{ifid}'\n\
         \x20   name = {}\n\
         \x20   byline = 'by the author'\n\
         \x20   version = '1'\n\
         \n\
         \x20   protagonist = me\n\
         ;\n\
         \n\
         // The first room, and what is in it.\n\
         startRoom: Room 'Start Room'\n\
         \x20   \"This is where the game begins. \"\n\
         ;\n\
         \n\
         + note: Thing 'note'\n\
         \x20   \"It says: <q>Welcome to <<story.name>>.</q> \"\n\
         ;\n\
         \n\
         // The player, who starts in the room.\n\
         + me: Player 'you'\n\
         ;\n",
        source_string(title)
    )
}

/// A choice game to start from: played by choosing, with the room's
/// choices and its exits listed, and reading the note one of them.
fn start_choices(title: &str, ifid: &str) -> String {
    format!(
        "// Where {title} begins.\n\
         \n\
         import hexad;\n\
         \n\
         // The story: what it is called, who wrote it, and who the player\n\
         // is as it begins. It is played by choosing.\n\
         story: Story\n\
         \x20   IFID = '{ifid}'\n\
         \x20   name = {}\n\
         \x20   byline = 'by the author'\n\
         \x20   version = '1'\n\
         \n\
         \x20   protagonist = me\n\
         \x20   choiceGame = true\n\
         ;\n\
         \n\
         // The first room, and what is in it.\n\
         startRoom: Room 'Start Room'\n\
         \x20   \"This is where the game begins. \"\n\
         ;\n\
         \n\
         + note: Thing 'note'\n\
         \x20   \"A folded note. \"\n\
         \x20   readDesc = \"It says: <q>Welcome to <<story.name>>.</q> \"\n\
         ;\n\
         \n\
         // The player, who starts in the room.\n\
         + me: Player 'you'\n\
         ;\n\
         \n\
         // What can be done in the room: its own choices, and then its\n\
         // exits, which it lists by itself.\n\
         startMoment: RoomMoment @startRoom;\n\
         \n\
         + ActionChoice 'Read the note' action = Read dobj = note;\n",
        source_string(title)
    )
}

/// Make the game in `folder`, a choice game if `choices` says: what is
/// written, or what is wrong.
pub(crate) fn create(folder: &Path, choices: bool) -> Result<(String, String), String> {
    let shown = folder.display();
    if folder.exists()
        && std::fs::read_dir(folder)
            .map(|mut entries| entries.next().is_some())
            .unwrap_or(true)
    {
        return Err(format!(
            "{shown}: already exists and is not empty; start a game in a new folder"
        ));
    }
    let name = folder
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    let title = title_of(&name);
    let image = format!("{}.hxg", if name.is_empty() { "game" } else { &name });
    std::fs::create_dir_all(folder).map_err(|e| format!("{shown}: {e}"))?;
    for (file, text) in [
        ("hexicon.toml", manifest(&title, &image, choices)),
        ("start.hxn", start(&title, &new_ifid(), choices)),
    ] {
        let path = folder.join(file);
        std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
    }
    Ok((title, image))
}

pub(crate) fn run(args: &[&str], usage: &str) -> ExitCode {
    let (folder, choices) = match args {
        [folder] => (folder, false),
        ["--choices", folder] => (folder, true),
        _ => {
            eprint!("{usage}");
            return ExitCode::from(2);
        }
    };
    match create(Path::new(folder), choices) {
        Ok((title, image)) => {
            println!(
                "Started {title} in {folder}: hexicon.toml and start.hxn.\n\
                 To build it and play it:\n\
                 \n\
                 \x20   cd {folder}\n\
                 \x20   hexicon build\n\
                 \x20   hexicon run {image}"
            );
            ExitCode::SUCCESS
        }
        Err(message) => {
            eprintln!("hexicon: {message}");
            ExitCode::FAILURE
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_title_comes_from_the_folders_name() {
        assert_eq!(title_of("my-game"), "My Game");
        assert_eq!(title_of("the_lost_key"), "The Lost Key");
        assert_eq!(title_of("Cave"), "Cave");
        assert_eq!(title_of(""), "My Game");
    }

    #[test]
    fn an_ifid_is_a_random_uuid() {
        let ifid = new_ifid();
        assert_eq!(ifid.len(), 36);
        assert_eq!(&ifid[14..15], "4");
        assert!(matches!(&ifid[19..20], "8" | "9" | "A" | "B"));
        assert_ne!(ifid, new_ifid());
    }

    #[test]
    fn a_new_game_builds_as_it_is() {
        let folder = std::env::temp_dir().join(format!("hexicon-new-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&folder);
        let game = folder.join("my-game");
        let (title, image) = create(&game, false).unwrap();
        assert_eq!((title.as_str(), image.as_str()), ("My Game", "my-game.hxg"));
        // Not over a folder with something in it.
        assert!(create(&game, false).is_err());

        let game_dir = game.to_string_lossy().into_owned();
        let out = game.join(&image).to_string_lossy().into_owned();
        let _ = crate::build::run(&["-f", &game_dir, "-o", &out], "");
        let built = std::fs::metadata(&out).map(|meta| meta.len()).unwrap_or(0);
        let _ = std::fs::remove_dir_all(&folder);
        assert!(built > 0, "no image was built");
    }

    #[test]
    fn a_new_choice_game_builds_as_it_is() {
        let folder =
            std::env::temp_dir().join(format!("hexicon-new-choices-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&folder);
        let game = folder.join("the-choice");
        let (_, image) = create(&game, true).unwrap();
        let manifest = std::fs::read_to_string(game.join("hexicon.toml")).unwrap();
        assert!(manifest.contains("extensions/choices"));
        let source = std::fs::read_to_string(game.join("start.hxn")).unwrap();
        assert!(source.contains("choiceGame = true"));

        let game_dir = game.to_string_lossy().into_owned();
        let out = game.join(&image).to_string_lossy().into_owned();
        let _ = crate::build::run(&["-f", &game_dir, "-o", &out], "");
        let built = std::fs::metadata(&out).map(|meta| meta.len()).unwrap_or(0);
        let _ = std::fs::remove_dir_all(&folder);
        assert!(built > 0, "no image was built");
    }
}