scrut 0.4.3

A simple and powerful test framework for CLI applications
Documentation
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

use std::fmt::Display;

use anyhow::Result;
use clap::ValueEnum;

use crate::config::DocumentConfig;
use crate::testcase::TestCase;

/// A Parser extracts one or more [`crate::testcase::TestCase`]s from a provided text
pub trait Parser {
    /// Returns all testcases found in the provided text
    fn parse(&self, tests: &str) -> Result<(DocumentConfig, Vec<TestCase>)>;
}

#[derive(Debug, Clone, Copy, PartialEq, ValueEnum)]
pub enum ParserType {
    Markdown,
    Cram,
}

impl ParserType {
    pub fn file_extension(&self) -> &'static str {
        match self {
            Self::Cram => "t",
            Self::Markdown => "md",
        }
    }
}

impl Display for ParserType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Cram => "cram",
                Self::Markdown => "markdown",
            }
        )
    }
}

impl TryFrom<String> for ParserType {
    type Error = String;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        match &value as &str {
            "markdown" | "md" => Ok(Self::Markdown),
            "cram" => Ok(Self::Cram),
            _ => Err(format!("Unsupported parser format `{value}`")),
        }
    }
}