use crate::token::Token;
use std::io::Result;
use std::path::{Path, PathBuf};
use base64::Engine;
pub fn normalize<P: AsRef<Path>>(path: P) -> String {
try_normalize(path.as_ref()).unwrap_or_else(|_| format!("{}", path.as_ref().display()))
}
fn try_normalize<P: AsRef<Path>>(path: P) -> Result<String> {
let full_path = std::fs::canonicalize(path.as_ref())?;
let mut cwd = std::env::current_dir()?;
let mut ups = 0;
loop {
if let Ok(path) = full_path.strip_prefix(&cwd.clone()) {
let mut new_path = PathBuf::new();
for _ in 0..ups {
new_path.push("../");
}
new_path.push(path);
return Ok(format!("{}", new_path.display()));
} else if !cwd.pop() {
return Ok(format!("{}", full_path.display()));
} else {
ups += 1;
}
}
}
pub fn insert_title(tokens: &mut Vec<Token>) {
for token in tokens.iter() {
if let &Token::Header(1, _) = token {
return;
}
}
tokens.insert(0, Token::Header(1, vec![]));
}
pub fn u8_to_base64(s: &[u8]) -> String {
base64::engine::general_purpose::STANDARD_NO_PAD.encode(s)
}