clingwrap 0.8.0

types and functions to implement command line programs
Documentation
//! Format a string for nicer output.
//!
//! Indent and prefix each line in a string so it stands out better in output.
//!
//! # Example
//!
//! ```rust
//! use clingwrap::indent::Indenter;
//! let mut i = Indenter::default().indent(4);
//! let out = i.format("hello\nworld");
//! assert_eq!(out, "    hello\n    world\n");
//! ```

/// Indent and prefix each line in a string.
///
/// Each line will end in a newline, even if the input ends in a line that
/// doesn't.
#[derive(Default)]
pub struct Indenter {
    indent: String,
    prefix: String,
}

impl Indenter {
    /// Indent each line by `n` spaces.
    pub fn indent(mut self, n: usize) -> Self {
        let mut indent = String::new();
        for _ in 0..n {
            indent.push(' ');
        }

        self.indent = indent;
        self
    }

    /// Add a prefix string to each line, after any indent.
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = prefix.into();
        self
    }

    /// Format input into output.
    pub fn format(&self, text: impl AsRef<str>) -> String {
        let mut output = String::new();

        let text = text.as_ref();
        for line in text.lines() {
            output.push_str(&self.indent);
            output.push_str(&self.prefix);
            output.push_str(line);
            output.push('\n');
        }

        output
    }
}

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

    #[test]
    fn no_indent_no_prefix() {
        let i = Indenter::default();
        assert_eq!(i.format("hello"), "hello\n");
    }

    #[test]
    fn indent_no_prefix() {
        let i = Indenter::default().indent(4);
        assert_eq!(i.format("hello"), "    hello\n");
    }

    #[test]
    fn prefix_no_indent() {
        let i = Indenter::default().prefix("> ");
        assert_eq!(i.format("hello"), "> hello\n");
    }

    #[test]
    fn prefix_and_indent() {
        let i = Indenter::default().indent(4).prefix("> ");
        assert_eq!(i.format("hello"), "    > hello\n");
    }
}