mirror of
https://seed.radicle.dev/rad:z3qg5TKmN83afz2fj9z3fQjU8vaYE.git
synced 2026-11-15 16:00:39 +08:00
100 lines
2.5 KiB
Rust
100 lines
2.5 KiB
Rust
use std::{
|
|
fs::{File, OpenOptions},
|
|
io::Write,
|
|
path::{Path, PathBuf},
|
|
};
|
|
|
|
#[derive(Debug)]
|
|
pub struct LogFile {
|
|
filename: PathBuf,
|
|
file: File,
|
|
}
|
|
|
|
impl LogFile {
|
|
pub fn open(filename: &Path) -> Result<Self, LogError> {
|
|
let file = OpenOptions::new()
|
|
.append(true)
|
|
.create(true)
|
|
.open(filename)
|
|
.map_err(|e| LogError::OpenLogFile(filename.into(), e))?;
|
|
Ok(Self {
|
|
filename: filename.into(),
|
|
file,
|
|
})
|
|
}
|
|
|
|
pub fn h1(&mut self, text: &str) -> Result<(), LogError> {
|
|
self.write_str("# ")?;
|
|
self.write_str(text)?;
|
|
self.write_str("\n\n")?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn h2(&mut self, text: &str) -> Result<(), LogError> {
|
|
self.write_str("## ")?;
|
|
self.write_str(text)?;
|
|
self.write_str("\n\n")?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn h3(&mut self, text: &str) -> Result<(), LogError> {
|
|
self.write_str("### ")?;
|
|
self.write_str(text)?;
|
|
self.write_str("\n\n")?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn bullet_point(&mut self, text: String) -> Result<(), LogError> {
|
|
self.write(text)?;
|
|
self.write_str("\n")?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn writeln(&mut self, text: String) -> Result<(), LogError> {
|
|
self.writeln_str(&text)?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn writeln_str(&mut self, text: &str) -> Result<(), LogError> {
|
|
self.write_str(text)?;
|
|
self.write_str("\n")?;
|
|
Ok(())
|
|
}
|
|
|
|
pub fn fenced(&mut self, msg: &str, data: &[u8]) -> Result<(), LogError> {
|
|
const FENCED_BLOCK: &str = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
|
|
self.h3(msg)?;
|
|
self.write_str(FENCED_BLOCK)?;
|
|
if !data.is_empty() {
|
|
let text = String::from_utf8_lossy(data);
|
|
self.write_str(&text)?;
|
|
if !text.ends_with('\n') {
|
|
self.write_str("\n")?;
|
|
}
|
|
}
|
|
self.write_str(FENCED_BLOCK)?;
|
|
self.write_str("\n")?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub fn write(&mut self, msg: String) -> Result<(), LogError> {
|
|
self.write_str(&msg)
|
|
}
|
|
|
|
pub fn write_str(&mut self, msg: &str) -> Result<(), LogError> {
|
|
self.file
|
|
.write_all(msg.as_bytes())
|
|
.map_err(|e| LogError::WriteLogFile(self.filename.clone(), e))
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum LogError {
|
|
#[error("failed to open log file {0}")]
|
|
OpenLogFile(PathBuf, #[source] std::io::Error),
|
|
|
|
#[error("failed to write to log file {0}")]
|
|
WriteLogFile(PathBuf, #[source] std::io::Error),
|
|
}
|