use crate::config::{Config, NAME_LEVEL, Rule, SECTION_LEVEL, Section, Target, VERSION};
use crate::error::Error;
use crate::gitignore::{GitIgnore, Line};
enum Entry<'a> {
Comment(&'a str),
Pattern { negate: bool, text: &'a str },
}
fn entry(line: &Line) -> Option<Entry<'_>> {
if let Some((_, text)) = line.comment() {
return Some(Entry::Comment(text));
}
line.pattern()
.map(|(negate, text)| Entry::Pattern { negate, text })
}
struct Group<'a> {
header: Vec<(usize, &'a str)>,
body: Vec<Entry<'a>>,
}
fn groups(lines: &[Line]) -> Vec<Group<'_>> {
lines
.split(|line| line.comment().is_none() && line.pattern().is_none())
.filter(|run| !run.is_empty())
.map(|run| {
let split = run
.iter()
.position(|line| line.comment().is_none())
.unwrap_or(run.len());
Group {
header: run[..split].iter().filter_map(Line::comment).collect(),
body: run[split..].iter().filter_map(entry).collect(),
}
})
.collect()
}
fn note_of(lines: &[&str]) -> Option<String> {
(!lines.is_empty()).then(|| lines.join("\n"))
}
impl Group<'_> {
fn as_config_name(&self) -> Option<&str> {
match self.header.as_slice() {
[(level, text)] if *level == NAME_LEVEL && self.body.is_empty() => Some(text),
_ => None,
}
}
fn as_section(&self) -> Option<Section> {
let ((level, first), rest) = self.header.split_first()?;
if *level < SECTION_LEVEL {
return None;
}
let rest: Vec<&str> = rest.iter().map(|(_, text)| *text).collect();
Some(Section {
name: Some((*first).to_owned()),
level: *level,
note: note_of(&rest),
rules: self.to_rules(Vec::new()),
})
}
fn is_preamble(&self) -> bool {
!self.header.is_empty()
&& self.body.is_empty()
&& self.header.iter().all(|(level, _)| *level == 1)
}
fn as_preamble(&self) -> Option<String> {
note_of(
&self
.header
.iter()
.map(|(_, text)| *text)
.collect::<Vec<&str>>(),
)
}
fn to_continuation_rules(&self) -> Vec<Rule> {
self.to_rules(self.header.iter().map(|(_, text)| *text).collect())
}
fn to_rules<'a>(&'a self, leading: Vec<&'a str>) -> Vec<Rule> {
let mut rules: Vec<Rule> = Vec::new();
let mut pending: Vec<&str> = leading;
let mut open: Option<usize> = None;
for entry in &self.body {
match entry {
Entry::Comment(text) => {
open = None;
pending.push(text);
}
Entry::Pattern { negate, text } => {
let index = match open {
Some(index) if *negate || rules[index].add.is_empty() => index,
_ => {
rules.push(Rule {
note: note_of(&std::mem::take(&mut pending)),
..Rule::default()
});
let index = rules.len() - 1;
open = Some(index);
index
}
};
let list = if *negate {
&mut rules[index].add
} else {
&mut rules[index].ignore
};
list.push((*text).to_owned());
}
}
}
if let Some(note) = note_of(&pending) {
rules.push(Rule {
note: Some(note),
..Rule::default()
});
}
rules
}
}
fn comment(level: usize, text: &str) -> String {
let hashes = "#".repeat(level);
if text.is_empty() {
hashes
} else {
format!("{hashes} {text}")
}
}
fn note_lines(note: Option<&String>) -> Vec<String> {
note.map(|note| note.split('\n').map(|line| comment(1, line)).collect())
.unwrap_or_default()
}
fn section_lines(section: &Section) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
if let Some(name) = §ion.name {
lines.push(comment(section.level, name));
}
lines.extend(note_lines(section.note.as_ref()));
for rule in §ion.rules {
if rule.note.is_some() && !lines.is_empty() {
lines.push(String::new());
}
lines.extend(note_lines(rule.note.as_ref()));
lines.extend(rule.ignore.iter().cloned());
lines.extend(rule.add.iter().map(|pattern| format!("!{pattern}")));
}
lines
}
fn target_lines(header: Option<&String>, name: Option<&String>, target: &Target) -> Vec<String> {
let mut lines: Vec<String> = note_lines(header);
if let Some(name) = name {
if !lines.is_empty() {
lines.push(String::new());
}
lines.push(comment(NAME_LEVEL, name));
}
for section in &target.sections {
if !lines.is_empty() {
lines.push(String::new());
}
lines.extend(section_lines(section));
}
lines
}
fn first_difference(expected: &str, actual: &str) -> Option<(usize, String, String)> {
let expected: Vec<&str> = expected.split('\n').collect();
let actual: Vec<&str> = actual.split('\n').collect();
(0..expected.len().max(actual.len())).find_map(|index| {
let want = expected.get(index).copied().unwrap_or_default();
let got = actual.get(index).copied().unwrap_or_default();
(want != got).then(|| (index + 1, want.to_owned(), got.to_owned()))
})
}
impl From<&Config> for GitIgnore {
fn from(config: &Config) -> Self {
Self::from_lines(target_lines(
config.header.as_ref(),
config.name.as_ref(),
&config.gitignore,
))
}
}
fn build(source: &GitIgnore) -> Result<Config, Error> {
let groups = groups(source.lines());
let (header, after_header) = groups
.split_first()
.filter(|(first, rest)| {
first.is_preamble()
&& rest
.first()
.is_some_and(|next| next.as_config_name().is_some())
})
.map_or((None, groups.as_slice()), |(first, rest)| {
(first.as_preamble(), rest)
});
let (name, rest) = after_header
.split_first()
.and_then(|(first, rest)| {
first
.as_config_name()
.map(|name| (Some(name.to_owned()), rest))
})
.unwrap_or((None, after_header));
let mut sections: Vec<Section> = Vec::new();
for group in rest {
if let Some(section) = group.as_section() {
sections.push(section);
continue;
}
let rules = group.to_continuation_rules();
match sections.last_mut() {
Some(section) => section.rules.extend(rules),
None => sections.push(Section {
rules,
..Section::default()
}),
}
}
let config = Config {
version: VERSION,
header,
name,
gitignore: Target { sections },
};
config.validate()?;
Ok(config)
}
impl GitIgnore {
pub fn canonical(&self) -> Result<Self, Error> {
build(self).map(|config| Self::from(&config))
}
}
impl TryFrom<&GitIgnore> for Config {
type Error = Error;
fn try_from(source: &GitIgnore) -> Result<Self, Error> {
let config = build(source)?;
match first_difference(&source.render(), &GitIgnore::from(&config).render()) {
Some((line, expected, actual)) => Err(Error::NotCanonical {
line,
expected,
actual,
}),
None => Ok(config),
}
}
}