use std::path::{Path, PathBuf};
use crate::error::TraceError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TraceMode {
Off,
#[default]
OnFailure,
Always,
}
impl TraceMode {
#[must_use]
pub fn writes(self, passed: bool) -> bool {
match self {
TraceMode::Off => false,
TraceMode::OnFailure => !passed,
TraceMode::Always => true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FramePolicy {
None,
#[default]
EveryStep,
ActionsOnly,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ByteSize(u64);
impl ByteSize {
#[must_use]
pub const fn bytes(bytes: u64) -> Self {
Self(bytes)
}
#[must_use]
pub const fn kib(kib: u64) -> Self {
Self(kib.saturating_mul(1024))
}
#[must_use]
pub const fn mib(mib: u64) -> Self {
Self(mib.saturating_mul(1024 * 1024))
}
#[must_use]
pub const fn get(self) -> u64 {
self.0
}
}
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraceConfig {
mode: TraceMode,
out_dir: PathBuf,
max_size: ByteSize,
frames: FramePolicy,
}
impl Default for TraceConfig {
fn default() -> Self {
Self {
mode: TraceMode::default(),
out_dir: PathBuf::from("target/icedwright"),
max_size: ByteSize::mib(64),
frames: FramePolicy::default(),
}
}
}
const TRACE_VAR: &str = "ICEDWRIGHT_TRACE";
const OUT_DIR_VAR: &str = "ICEDWRIGHT_OUT_DIR";
const MAX_MB_VAR: &str = "ICEDWRIGHT_TRACE_MAX_MB";
impl TraceConfig {
pub fn new() -> Self {
Self::default()
}
pub fn mode(self, mode: TraceMode) -> Self {
Self { mode, ..self }
}
pub fn out_dir(self, dir: impl Into<PathBuf>) -> Self {
Self {
out_dir: dir.into(),
..self
}
}
pub fn max_size(self, bytes: ByteSize) -> Self {
Self {
max_size: bytes,
..self
}
}
pub fn frames(self, policy: FramePolicy) -> Self {
Self {
frames: policy,
..self
}
}
pub fn from_env(self, env: &impl Fn(&str) -> Option<String>) -> Result<Self, TraceError> {
let mut config = self;
if let Some(value) = env(TRACE_VAR) {
config.mode = match value.as_str() {
"off" => TraceMode::Off,
"on-failure" => TraceMode::OnFailure,
"always" => TraceMode::Always,
_ => {
return Err(TraceError::BadEnv {
var: TRACE_VAR,
value,
expected: "off, on-failure or always",
});
}
};
}
if let Some(value) = env(OUT_DIR_VAR) {
if value.is_empty() {
return Err(TraceError::BadEnv {
var: OUT_DIR_VAR,
value,
expected: "a directory path",
});
}
config.out_dir = PathBuf::from(value);
}
if let Some(value) = env(MAX_MB_VAR) {
let mib = value.trim().parse::<u64>().ok().filter(|mib| *mib > 0);
let Some(mib) = mib else {
return Err(TraceError::BadEnv {
var: MAX_MB_VAR,
value,
expected: "a whole number of MiB above zero",
});
};
config.max_size = ByteSize::mib(mib);
}
Ok(config)
}
#[must_use]
pub fn trace_mode(&self) -> TraceMode {
self.mode
}
#[must_use]
pub fn output_dir(&self) -> &Path {
&self.out_dir
}
#[must_use]
pub fn size_cap(&self) -> ByteSize {
self.max_size
}
#[must_use]
pub fn frame_policy(&self) -> FramePolicy {
self.frames
}
#[must_use]
pub fn trace_path(&self, module_path: &str, test: &str) -> PathBuf {
let mut path = self.out_dir.join("traces");
module_path
.split("::")
.filter(|part| !part.is_empty())
.for_each(|part| path.push(part));
path.push(format!("{test}.iwtrace"));
path
}
}
#[cfg(test)]
mod tests {
use super::*;
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
move |name| {
vars.iter()
.find(|(var, _)| *var == name)
.map(|(_, value)| (*value).to_owned())
}
}
#[test]
fn defaults() {
let config = TraceConfig::new();
assert_eq!(config.trace_mode(), TraceMode::OnFailure);
assert_eq!(config.output_dir(), Path::new("target/icedwright"));
assert_eq!(config.size_cap(), ByteSize::mib(64));
assert_eq!(config.frame_policy(), FramePolicy::EveryStep);
}
#[test]
fn builder_sets_each_field() {
let config = TraceConfig::new()
.mode(TraceMode::Always)
.out_dir("/tmp/out")
.max_size(ByteSize::kib(3))
.frames(FramePolicy::ActionsOnly);
assert_eq!(config.trace_mode(), TraceMode::Always);
assert_eq!(config.output_dir(), Path::new("/tmp/out"));
assert_eq!(config.size_cap().get(), 3072);
assert_eq!(config.frame_policy(), FramePolicy::ActionsOnly);
}
type Vars<'a> = &'a [(&'a str, &'a str)];
#[test]
fn environment_table() -> Result<(), TraceError> {
let cases: &[(Vars<'_>, TraceMode, &str, u64)] = &[
(&[], TraceMode::OnFailure, "target/icedwright", 64),
(
&[("ICEDWRIGHT_TRACE", "off")],
TraceMode::Off,
"target/icedwright",
64,
),
(
&[("ICEDWRIGHT_TRACE", "always")],
TraceMode::Always,
"target/icedwright",
64,
),
(
&[
("ICEDWRIGHT_TRACE", "on-failure"),
("ICEDWRIGHT_OUT_DIR", "out"),
],
TraceMode::OnFailure,
"out",
64,
),
(
&[("ICEDWRIGHT_TRACE_MAX_MB", "8")],
TraceMode::OnFailure,
"target/icedwright",
8,
),
];
for (vars, mode, dir, mib) in cases {
let config = TraceConfig::new().from_env(&env(vars))?;
assert_eq!(config.trace_mode(), *mode, "{vars:?}");
assert_eq!(config.output_dir(), Path::new(dir), "{vars:?}");
assert_eq!(config.size_cap(), ByteSize::mib(*mib), "{vars:?}");
}
Ok(())
}
#[test]
fn invalid_environment_values_name_the_variable() {
let cases: &[(&str, &str, &str)] = &[
(
"ICEDWRIGHT_TRACE",
"yes",
"ICEDWRIGHT_TRACE=\"yes\" is not valid: off, on-failure or always",
),
(
"ICEDWRIGHT_OUT_DIR",
"",
"ICEDWRIGHT_OUT_DIR=\"\" is not valid: a directory path",
),
(
"ICEDWRIGHT_TRACE_MAX_MB",
"0",
"ICEDWRIGHT_TRACE_MAX_MB=\"0\" is not valid: a whole number of MiB above zero",
),
(
"ICEDWRIGHT_TRACE_MAX_MB",
"1.5",
"ICEDWRIGHT_TRACE_MAX_MB=\"1.5\" is not valid: a whole number of MiB above zero",
),
];
for (var, value, message) in cases {
let vars = [(*var, *value)];
let error = TraceConfig::new().from_env(&env(&vars)).err();
assert_eq!(error.map(|e| e.to_string()).as_deref(), Some(*message));
}
}
#[test]
fn modes_decide_what_is_written() {
assert!(!TraceMode::Off.writes(false));
assert!(!TraceMode::OnFailure.writes(true));
assert!(TraceMode::OnFailure.writes(false));
assert!(TraceMode::Always.writes(true));
}
#[test]
fn trace_paths_follow_the_module_path() {
let path = TraceConfig::new().trace_path("examples_notes::ui", "restoring_a_note");
assert_eq!(
path,
Path::new("target/icedwright/traces/examples_notes/ui/restoring_a_note.iwtrace")
);
}
}