#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineKind {
Blank,
Comment,
Pattern,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Line {
raw: String,
}
impl Line {
#[must_use]
pub fn raw(&self) -> &str {
&self.raw
}
fn content(&self) -> &str {
self.raw.strip_suffix('\r').unwrap_or(&self.raw)
}
#[must_use]
pub fn kind(&self) -> LineKind {
let content = self.content();
if content.trim().is_empty() {
LineKind::Blank
} else if content.starts_with('#') {
LineKind::Comment
} else {
LineKind::Pattern
}
}
#[must_use]
pub fn comment(&self) -> Option<(usize, &str)> {
if self.kind() != LineKind::Comment {
return None;
}
let content = self.content();
let level = content.chars().take_while(|c| *c == '#').count();
let text = &content[level..];
Some((level, text.strip_prefix(' ').unwrap_or(text)))
}
#[must_use]
pub fn pattern(&self) -> Option<(bool, &str)> {
if self.kind() != LineKind::Pattern {
return None;
}
let content = self.content();
Some(
content
.strip_prefix('!')
.map_or((false, content), |rest| (true, rest)),
)
}
}
fn raw_of(mut content: String) -> String {
if content.ends_with('\r') {
content.push('\r');
}
content
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitIgnore {
lines: Vec<Line>,
trailing_newline: bool,
}
impl GitIgnore {
#[must_use]
pub fn parse(source: &str) -> Self {
let (body, trailing_newline) = source
.strip_suffix('\n')
.map_or((source, false), |body| (body, true));
let lines = if body.is_empty() && !trailing_newline {
Vec::new()
} else {
body.split('\n')
.map(|raw| Line {
raw: raw.to_owned(),
})
.collect()
};
Self {
lines,
trailing_newline,
}
}
#[must_use]
pub fn render(&self) -> String {
let mut out = self
.lines
.iter()
.map(Line::raw)
.collect::<Vec<_>>()
.join("\n");
if self.trailing_newline {
out.push('\n');
}
out
}
#[must_use]
pub fn lines(&self) -> &[Line] {
&self.lines
}
pub(crate) fn from_lines(lines: Vec<String>) -> Self {
Self {
trailing_newline: !lines.is_empty(),
lines: lines
.into_iter()
.map(|content| Line {
raw: raw_of(content),
})
.collect(),
}
}
}
#[cfg(test)]
mod tests {
use super::{GitIgnore, LineKind};
fn kinds(source: &str) -> Vec<LineKind> {
GitIgnore::parse(source)
.lines()
.iter()
.map(super::Line::kind)
.collect()
}
#[test]
fn classifies_blank_comment_and_pattern() {
assert_eq!(
kinds("# Cargo\n\n/target\n"),
vec![LineKind::Comment, LineKind::Blank, LineKind::Pattern]
);
}
#[test]
fn whitespace_only_line_is_blank() {
assert_eq!(kinds(" \n\t\n"), vec![LineKind::Blank, LineKind::Blank]);
}
#[test]
fn hash_after_leading_space_is_a_pattern() {
assert_eq!(kinds(" # not a comment\n"), vec![LineKind::Pattern]);
}
#[test]
fn escaped_hash_is_a_pattern() {
assert_eq!(kinds("\\#literal\n"), vec![LineKind::Pattern]);
}
#[test]
fn classification_looks_past_a_trailing_cr() {
assert_eq!(
kinds("# c\r\n\r\n/t\r\n"),
vec![LineKind::Comment, LineKind::Blank, LineKind::Pattern]
);
}
#[test]
fn comment_reports_level_and_text() {
let g = GitIgnore::parse("# Cargo\n## Mise\n###\n#NoSpace\n");
let parts: Vec<_> = g.lines().iter().filter_map(super::Line::comment).collect();
assert_eq!(
parts,
vec![(1, "Cargo"), (2, "Mise"), (3, ""), (1, "NoSpace")]
);
}
#[test]
fn comment_strips_a_trailing_cr_from_its_text() {
let g = GitIgnore::parse("# Cargo\r\n");
assert_eq!(g.lines()[0].comment(), Some((1, "Cargo")));
}
#[test]
fn comment_is_none_for_other_kinds() {
let g = GitIgnore::parse("/target\n\n");
assert!(g.lines().iter().all(|l| l.comment().is_none()));
}
#[test]
fn pattern_reports_negation() {
let g = GitIgnore::parse("/target\n!keep.log\n");
let parts: Vec<_> = g.lines().iter().filter_map(super::Line::pattern).collect();
assert_eq!(parts, vec![(false, "/target"), (true, "keep.log")]);
}
#[test]
fn pattern_strips_a_trailing_cr() {
let g = GitIgnore::parse("/target\r\n");
assert_eq!(g.lines()[0].pattern(), Some((false, "/target")));
}
#[test]
fn pattern_is_none_for_other_kinds() {
let g = GitIgnore::parse("# c\n\n");
assert!(g.lines().iter().all(|l| l.pattern().is_none()));
}
}