use anyhow::{Context, Result};
use base64::Engine;
use std::path::Path;
const BASE64_BINARY_EXTENSIONS: &[&str] = &["jar"];
pub fn is_base64_binary_output(path: &Path) -> bool {
path.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| BASE64_BINARY_EXTENSIONS.contains(&extension))
}
pub fn decode_base64_binary(path: &Path, content: &str) -> Result<Vec<u8>> {
base64::engine::general_purpose::STANDARD
.decode(content)
.with_context(|| format!("failed to decode base64 for {}", path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn jar_output_is_recognised_and_other_extensions_are_not() {
assert!(is_base64_binary_output(Path::new(
"packages/kotlin-android/gradle/wrapper/gradle-wrapper.jar"
)));
assert!(!is_base64_binary_output(Path::new("packages/node/package.json")));
assert!(!is_base64_binary_output(Path::new("gradlew")));
}
#[test]
fn decoding_names_the_path_when_the_content_is_not_base64() {
let error = decode_base64_binary(Path::new("packages/demo/wrapper.jar"), "not base64!")
.expect_err("malformed base64 must not decode");
assert!(
format!("{error:#}").contains("packages/demo/wrapper.jar"),
"the decode failure must name the offending path, got: {error:#}"
);
}
}