use toml_edit::TomlError;
use crate::decor::Marker;
use crate::error::Error;
use crate::merge::{MergeEngine, Merged};
use crate::path::DottedPath;
use crate::source::SourceDocument;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeOptions {
pub(crate) marker: Marker,
pub(crate) migrations: Vec<Migration>,
pub(crate) align: bool,
pub(crate) commented: bool,
}
impl Default for MergeOptions {
fn default() -> Self {
Self {
marker: Marker::default(),
migrations: Vec::new(),
align: true,
commented: true,
}
}
}
impl MergeOptions {
pub fn new() -> Self {
Self::default()
}
pub fn defaults_commented(mut self, yes: bool) -> Self {
self.commented = yes;
self
}
pub fn comments_defaults(&self) -> bool {
self.commented
}
pub fn markers(mut self, prose: impl Into<String>, sample: impl Into<String>) -> Self {
self.marker = Marker::new(prose, sample);
self
}
pub fn migrate(mut self, from: &str, to: &str) -> Self {
self.migrations.push(Migration {
from: DottedPath::parse(from),
to: DottedPath::parse(to),
});
self
}
pub fn align_values(mut self, yes: bool) -> Self {
self.align = yes;
self
}
pub fn aligns_values(&self) -> bool {
self.align
}
pub fn prose_marker(&self) -> &str {
self.marker.prose()
}
pub fn sample_marker(&self) -> &str {
self.marker.sample()
}
pub fn merge(&self, default_src: &str, user_src: &str) -> Result<Merged, Error> {
let defaults =
SourceDocument::parse(default_src).map_err(|source| Error::DefaultParse { source })?;
if defaults.has_text_but_no_keys()
&& !default_src.lines().any(|line| self.marker.owns(line))
{
return Err(Error::DefaultsDeclareNoKeys);
}
let (user, spans) = SourceDocument::parse_with_spans(user_src)
.map_err(|source| Error::UserParse { source })?;
let migrations = self.resolved_migrations()?;
Ok(MergeEngine::new(defaults, user, user_src, self.clone(), migrations, spans).run())
}
fn resolved_migrations(&self) -> Result<Vec<ResolvedMigration>, Error> {
self.migrations
.iter()
.map(|migration| {
Ok(ResolvedMigration {
from: migration
.from
.clone()
.map_err(|source| Error::MigrationPath { source })?,
to: migration
.to
.clone()
.map_err(|source| Error::MigrationPath { source })?,
})
})
.collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Migration {
pub(crate) from: Result<DottedPath, TomlError>,
pub(crate) to: Result<DottedPath, TomlError>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ResolvedMigration {
pub(crate) from: DottedPath,
pub(crate) to: DottedPath,
}