use std::collections::BTreeSet;
use std::fmt;
use crate::dsl::{Diagnostic, Location, Policy};
pub mod casbin;
mod csv;
pub mod openfga;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Report {
pub converted: Vec<String>,
pub not_converted: Vec<Diagnostic>,
pub notes: Vec<Diagnostic>,
}
impl Report {
pub(crate) fn failed(&self) -> bool {
!self.not_converted.is_empty()
}
pub(crate) fn converted(&mut self, count: usize, what: &str) {
if count > 0 {
self.converted.push(format!("{count} {what}"));
}
}
pub(crate) fn refuse(&mut self, at: Option<Location>, message: impl Into<String>, hint: Option<&str>) {
let mut found = Diagnostic::new(at, message);
if let Some(hint) = hint {
found = found.with_hint(hint);
}
self.not_converted.push(found);
}
pub(crate) fn note(&mut self, at: Option<Location>, message: impl Into<String>) {
self.notes.push(Diagnostic::new(at, message));
}
}
impl fmt::Display for Report {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "converted:")?;
if self.converted.is_empty() {
writeln!(f, " nothing")?;
}
for line in &self.converted {
writeln!(f, " {line}")?;
}
if !self.notes.is_empty() {
writeln!(f, "converted with a narrower reach or dropped:")?;
for note in &self.notes {
writeln!(f, " {note}")?;
}
}
if !self.not_converted.is_empty() {
writeln!(f, "not converted:")?;
for item in &self.not_converted {
writeln!(f, " {item}")?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportError {
pub report: Report,
}
impl fmt::Display for ImportError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, item) in self.report.not_converted.iter().enumerate() {
if i > 0 {
writeln!(f)?;
}
write!(f, "{item}")?;
}
Ok(())
}
}
impl std::error::Error for ImportError {}
pub(crate) fn key_segment(text: &str) -> String {
let mapped: String = text
.chars()
.map(|c| {
let c = c.to_ascii_lowercase();
if c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' {
c
} else {
'_'
}
})
.collect();
if mapped.is_empty() { "_".to_string() } else { mapped }
}
pub(crate) fn unique_id(base: &str, used: &mut BTreeSet<String>) -> String {
let clean: String = base
.chars()
.map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' })
.collect();
let mut id = clean.clone();
let mut n = 2;
while !used.insert(id.clone()) {
id = format!("{clean}_{n}");
n += 1;
}
id
}
pub(crate) fn finish(policy: &Policy, report: &mut Report) {
if let Err(found) = policy.validate() {
for item in found {
report.refuse(
item.location.clone(),
format!("the imported policy is not valid: {}", item.message),
item.hint.as_deref(),
);
}
}
}
pub(crate) fn is_name(text: &str) -> bool {
let mut previous_joiner = true;
for c in text.chars() {
if c.is_ascii_alphanumeric() || c == '_' {
previous_joiner = false;
} else if (c == '.' || c == '-') && !previous_joiner {
previous_joiner = true;
} else {
return false;
}
}
!previous_joiner
}