1#[macro_export]
63macro_rules! simple_time_operation {
64 ($name:expr, $block:block) => {{
65 let start = std::time::Instant::now();
66 let result = $block;
67 let elapsed = start.elapsed();
68 $crate::simple_tracing::SimpleTracer::performance($name, elapsed.as_millis() as u64);
69 result
70 }};
71}
72
73use std::path::Path;
74use std::time::Instant;
75
76pub struct SimpleTracer;
78
79impl SimpleTracer {
80 pub fn is_enabled() -> bool {
82 std::env::var("GGEN_TRACE").is_ok()
83 }
84
85 pub fn trace_level() -> TraceLevel {
87 match std::env::var("GGEN_TRACE")
88 .unwrap_or_default()
89 .to_lowercase()
90 .as_str()
91 {
92 "error" => TraceLevel::Error,
93 "warn" => TraceLevel::Warn,
94 "info" => TraceLevel::Info,
95 "debug" => TraceLevel::Debug,
96 "trace" => TraceLevel::Trace,
97 "1" | "true" | "yes" => TraceLevel::Debug,
98 "0" | "false" | "no" => TraceLevel::Error,
99 _ => TraceLevel::Info,
100 }
101 }
102
103 pub fn trace(level: TraceLevel, message: &str, context: Option<&str>) {
105 if !Self::is_enabled() {
106 return;
107 }
108
109 let current_level = Self::trace_level();
110 if level as u8 > current_level as u8 {
111 return;
112 }
113
114 let prefix = match level {
115 TraceLevel::Error => "ERROR",
116 TraceLevel::Warn => "WARN ",
117 TraceLevel::Info => "INFO ",
118 TraceLevel::Debug => "DEBUG",
119 TraceLevel::Trace => "TRACE",
120 };
121
122 match level {
123 TraceLevel::Error => {
124 if let Some(ctx) = context {
125 log::error!("[GGEN {}] {}: {}", prefix, ctx, message);
126 } else {
127 log::error!("[GGEN {}] {}", prefix, message);
128 }
129 }
130 TraceLevel::Warn => {
131 if let Some(ctx) = context {
132 log::warn!("[GGEN {}] {}: {}", prefix, ctx, message);
133 } else {
134 log::warn!("[GGEN {}] {}", prefix, message);
135 }
136 }
137 TraceLevel::Info => {
138 if let Some(ctx) = context {
139 log::info!("[GGEN {}] {}: {}", prefix, ctx, message);
140 } else {
141 log::info!("[GGEN {}] {}", prefix, message);
142 }
143 }
144 TraceLevel::Debug | TraceLevel::Trace => {
145 if let Some(ctx) = context {
146 log::debug!("[GGEN {}] {}: {}", prefix, ctx, message);
147 } else {
148 log::debug!("[GGEN {}] {}", prefix, message);
149 }
150 }
151 }
152 }
153
154 pub fn template_start(template_path: &Path) {
156 Self::trace(
157 TraceLevel::Info,
158 &format!("Starting template processing: {}", template_path.display()),
159 None,
160 );
161 }
162
163 pub fn template_complete(template_path: &Path, output_path: &Path, content_size: usize) {
165 Self::trace(
166 TraceLevel::Info,
167 &format!(
168 "Template processing complete: {} -> {} ({} bytes)",
169 template_path.display(),
170 output_path.display(),
171 content_size
172 ),
173 None,
174 );
175 }
176
177 pub fn frontmatter_processed(frontmatter: &crate::template_types::Frontmatter) {
179 Self::trace(
180 TraceLevel::Debug,
181 &format!(
182 "Frontmatter processed: to={:?}, inject={}",
183 frontmatter.to,
184 frontmatter.flags.inject ),
186 Some("frontmatter"),
187 );
188 }
189
190 pub fn context_blessed(vars_count: usize) {
192 Self::trace(
193 TraceLevel::Debug,
194 &format!(
195 "Context blessed: {} variables (Name, locals added)",
196 vars_count
197 ),
198 Some("context"),
199 );
200 }
201
202 pub fn rdf_loading(files: &[String], inline_blocks: usize, triples: usize) {
204 Self::trace(
205 TraceLevel::Info,
206 &format!(
207 "RDF loaded: {} files, {} inline blocks, {} triples",
208 files.len(),
209 inline_blocks,
210 triples
211 ),
212 Some("rdf"),
213 );
214 }
215
216 pub fn sparql_query(query: &str, result_count: Option<usize>) {
218 let count_str = result_count
219 .map(|c| c.to_string())
220 .unwrap_or_else(|| "N/A".to_string());
221 Self::trace(
222 TraceLevel::Debug,
223 &format!("SPARQL query: {} results", count_str),
224 Some("sparql"),
225 );
226 Self::trace(TraceLevel::Trace, query, Some("sparql"));
227 }
228
229 pub fn file_injection(target_path: &Path, mode: &str, success: bool) {
231 let status = if success { "completed" } else { "failed" };
232 Self::trace(
233 TraceLevel::Info,
234 &format!("File injection {}: {} mode", status, mode),
235 Some(&format!("injection:{}", target_path.display())),
236 );
237 }
238
239 pub fn shell_hook(command: &str, timing: &str, exit_code: i32) {
241 let status = if exit_code == 0 {
242 "completed"
243 } else {
244 "failed"
245 };
246 Self::trace(
247 TraceLevel::Info,
248 &format!(
249 "Shell hook {}: {} (exit code: {})",
250 status, timing, exit_code
251 ),
252 Some(&format!("hook:{}", command)),
253 );
254 }
255
256 pub fn performance(operation: &str, duration_ms: u64) {
258 Self::trace(
259 TraceLevel::Debug,
260 &format!("Performance: {} took {}ms", operation, duration_ms),
261 Some("performance"),
262 );
263 }
264
265 pub fn dry_run(output_path: &Path, content_size: usize) {
267 Self::trace(
268 TraceLevel::Info,
269 &format!(
270 "DRY RUN: Would generate {} ({} bytes)",
271 output_path.display(),
272 content_size
273 ),
274 Some("dry_run"),
275 );
276 }
277
278 pub fn backup_created(original_path: &Path, backup_path: &Path) {
280 Self::trace(
281 TraceLevel::Info,
282 &format!(
283 "Backup created: {} -> {}",
284 original_path.display(),
285 backup_path.display()
286 ),
287 Some("backup"),
288 );
289 }
290
291 pub fn skip_condition(condition: &str, reason: &str) {
293 Self::trace(
294 TraceLevel::Info,
295 &format!("Skipped: {} ({})", condition, reason),
296 Some("skip"),
297 );
298 }
299
300 pub fn error(error: &crate::utils::error::Error, context: &str) {
302 Self::trace(
303 TraceLevel::Error,
304 &format!("Error in {}: {}", context, error),
305 Some("error"),
306 );
307 }
308
309 pub fn warning(message: &str, context: Option<&str>) {
311 Self::trace(TraceLevel::Warn, message, context);
312 }
313}
314
315#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
316pub enum TraceLevel {
317 Error = 0,
318 Warn = 1,
319 Info = 2,
320 Debug = 3,
321 Trace = 4,
322}
323
324pub struct SimpleTimer {
326 start: Instant,
327 operation: String,
328}
329
330impl SimpleTimer {
331 pub fn start(operation: &str) -> Self {
333 Self {
334 start: Instant::now(),
335 operation: operation.to_string(),
336 }
337 }
338
339 pub fn finish(self) {
341 let duration = self.start.elapsed();
342 SimpleTracer::performance(&self.operation, duration.as_millis() as u64);
343 }
344}
345
346#[cfg(test)]
347mod tests {
348 use super::*;
349 use crate::time_operation;
350 use std::fs;
351 use tempfile::TempDir;
352
353 #[test]
354 fn test_trace_level_ordering() {
355 assert!(TraceLevel::Error < TraceLevel::Warn);
356 assert!(TraceLevel::Warn < TraceLevel::Info);
357 assert!(TraceLevel::Info < TraceLevel::Debug);
358 assert!(TraceLevel::Debug < TraceLevel::Trace);
359 }
360
361 #[test]
362 fn test_simple_timer() {
363 let timer = SimpleTimer::start("test_operation");
364 std::thread::sleep(std::time::Duration::from_millis(10));
365 timer.finish(); }
367
368 #[test]
369 fn test_tracing_methods() {
370 let temp_dir = TempDir::new().unwrap();
371 let test_path = temp_dir.path().join("test.tmpl");
372 fs::write(&test_path, "test content").unwrap();
373
374 SimpleTracer::template_start(&test_path);
376 SimpleTracer::template_complete(&test_path, &test_path, 100);
377
378 let frontmatter = crate::template_types::Frontmatter::default();
379 SimpleTracer::frontmatter_processed(&frontmatter);
380
381 SimpleTracer::context_blessed(5);
382 SimpleTracer::rdf_loading(&["file1.ttl".to_string()], 2, 100);
383 SimpleTracer::sparql_query("SELECT * WHERE { ?s ?p ?o }", Some(10));
384
385 SimpleTracer::file_injection(&test_path, "append", true);
386 SimpleTracer::shell_hook("echo 'test'", "before", 0);
387 SimpleTracer::performance("test_operation", 50);
388 SimpleTracer::dry_run(&test_path, 500);
389 SimpleTracer::backup_created(&test_path, &temp_dir.path().join("backup.tmpl"));
390 SimpleTracer::skip_condition("skip_if", "pattern found");
391
392 let error = crate::utils::error::Error::new("Test error");
393 SimpleTracer::error(&error, "test context");
394 SimpleTracer::warning("Test warning", Some("test context"));
395 SimpleTracer::warning("Test warning", None);
396 }
397
398 #[test]
399 fn test_tracing_environment_variables() {
400 let test_values = [
402 "error", "warn", "info", "debug", "trace", "1", "0", "true", "false",
403 ];
404
405 for value in &test_values {
406 std::env::set_var("GGEN_TRACE", value);
407 let level = SimpleTracer::trace_level();
408 assert!(matches!(
409 level,
410 TraceLevel::Error
411 | TraceLevel::Warn
412 | TraceLevel::Info
413 | TraceLevel::Debug
414 | TraceLevel::Trace
415 ));
416 }
417 }
418
419 #[test]
420 fn test_time_operation_macro() {
421 let result = time_operation!("test_op", {
422 std::thread::sleep(std::time::Duration::from_millis(2));
423 42
424 });
425 assert_eq!(result, 42);
426 }
427}