use std::{
fs::{create_dir_all, write},
path::Path,
process,
};
use toml_edit::{Document, Table, TomlError};
use crate::utils::to_out;
#[derive(Debug)]
pub struct Toml {
pub doc: Document,
}
impl Toml {
pub fn parse(input: &str) -> Result<Toml, TomlError> {
match input.parse::<Document>() {
Ok(doc) => Ok(Toml { doc }),
Err(e) => Err(e),
}
}
pub fn table(&self) -> &Table {
self.doc.as_table()
}
pub fn table_mut(&mut self) -> &mut Table {
self.doc.as_table_mut()
}
pub fn toml_string(&self) -> String {
self.doc.to_string_in_original_order().trim().to_string()
}
pub fn write<P: AsRef<Path>>(&self, path: P) {
let parent = path.as_ref().parent().unwrap();
if !parent.is_dir() {
create_dir_all(parent).unwrap();
}
if let Err(e) = write(path, self.toml_string()) {
to_out(format!("写入文件失败:\n {}", e));
process::exit(18);
}
}
}