alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
Documentation
//! Launch-buffer opening helpers.

use super::{error::BufferOpenError, file::BufferFile};
use crate::{
    fs_utils::{self, FilesystemConfig},
    text_stream::TextByteStream,
};
use std::{ffi::OsString, path::PathBuf};

/// Opens a launch buffer from a CLI file argument, creating the file when absent.
///
/// # Errors
///
/// Returns [`BufferOpenError`] when the file cannot be created/read or is not valid UTF-8.
pub fn open_launch_buffer(
    file_argument: Option<OsString>,
    fallback_text: &str,
    config: &FilesystemConfig,
) -> Result<(TextByteStream, BufferFile), BufferOpenError> {
    let Some(file_argument) = file_argument else {
        let stream = TextByteStream::new(fallback_text);
        return Ok((stream.clone(), BufferFile::scratch(stream.revision())));
    };

    let read_file = fs_utils::read_text_file(PathBuf::from(file_argument), config)
        .map_err(BufferOpenError::File)?;
    let stream =
        TextByteStream::from_bytes(read_file.bytes).map_err(|source| BufferOpenError::Text {
            path: read_file.path.clone(),
            source,
        })?;
    let buffer = BufferFile::backed_by(read_file.path, stream.revision());

    Ok((stream, buffer))
}

/// Selects the file argument from process arguments.
#[must_use]
pub fn launch_file_argument(arguments: impl IntoIterator<Item = OsString>) -> Option<OsString> {
    arguments.into_iter().next()
}