1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
|
use anyhow::{Context as _, Result};
use log::debug;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::io::AsyncWriteExt as _;
use tokio::process::Command;
use crate::hook::HookResult;
/// Exit status of a build operation.
#[derive(Debug)]
pub enum BuildExitStatus {
Success,
Failed {
exit_code: Option<i32>,
error: String,
},
}
impl std::fmt::Display for BuildExitStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Success => write!(f, "success"),
Self::Failed { exit_code, error } => {
if let Some(code) = exit_code {
write!(f, "failed (exit code: {code}): {error}")
} else {
write!(f, "failed: {error}")
}
}
}
}
}
/// Metadata about a build for logging purposes.
#[derive(Debug)]
pub struct BuildLogMeta {
pub site_name: String,
pub timestamp: String,
pub git_commit: Option<String>,
pub container_image: String,
pub duration: Duration,
pub exit_status: BuildExitStatus,
}
/// Save build log to disk via streaming composition.
///
/// Writes the metadata header to the log file, then streams stdout and stderr
/// content from temporary files via `tokio::io::copy` (O(1) memory).
/// Deletes the temporary files after successful composition.
///
/// Creates a log file at `{log_dir}/{site_name}/{timestamp}.log`.
///
/// # Errors
///
/// Returns an error if the log directory cannot be created, the log file
/// cannot be written, or the temp files cannot be read.
pub async fn save_build_log(
log_dir: &Path,
meta: &BuildLogMeta,
stdout_file: &Path,
stderr_file: &Path,
) -> Result<PathBuf> {
let site_log_dir = log_dir.join(&meta.site_name);
let log_file = site_log_dir.join(format!("{}.log", meta.timestamp));
// Create logs directory if it doesn't exist
tokio::fs::create_dir_all(&site_log_dir)
.await
.with_context(|| {
format!(
"failed to create logs directory: {}",
site_log_dir.display()
)
})?;
// Write header + stream content from temp files
let mut log_writer = tokio::io::BufWriter::new(
tokio::fs::File::create(&log_file)
.await
.with_context(|| format!("failed to create log file: {}", log_file.display()))?,
);
let header = format_log_header(meta);
log_writer.write_all(header.as_bytes()).await?;
// Append stdout section
log_writer.write_all(b"\n=== STDOUT ===\n").await?;
let mut stdout_reader = tokio::fs::File::open(stdout_file)
.await
.with_context(|| format!("failed to open {}", stdout_file.display()))?;
tokio::io::copy(&mut stdout_reader, &mut log_writer).await?;
// Append stderr section
log_writer.write_all(b"\n\n=== STDERR ===\n").await?;
let mut stderr_reader = tokio::fs::File::open(stderr_file)
.await
.with_context(|| format!("failed to open {}", stderr_file.display()))?;
tokio::io::copy(&mut stderr_reader, &mut log_writer).await?;
log_writer.write_all(b"\n").await?;
log_writer.flush().await?;
drop(log_writer);
// Delete temp files (best-effort)
let _ = tokio::fs::remove_file(stdout_file).await;
let _ = tokio::fs::remove_file(stderr_file).await;
debug!(
"[{}] build log saved: {}",
meta.site_name,
log_file.display()
);
Ok(log_file)
}
/// Format a duration as a human-readable string (e.g., "45s" or "2m 30s").
#[must_use]
pub fn format_duration(d: Duration) -> String {
let secs = d.as_secs();
if secs >= 60 {
format!("{}m {}s", secs / 60, secs % 60)
} else {
format!("{secs}s")
}
}
/// Format the metadata header for a build log (without output sections).
fn format_log_header(meta: &BuildLogMeta) -> String {
let git_commit = meta.git_commit.as_deref().unwrap_or("unknown");
let duration_str = format_duration(meta.duration);
format!(
"=== BUILD LOG ===\n\
Site: {}\n\
Timestamp: {}\n\
Git Commit: {}\n\
Image: {}\n\
Duration: {}\n\
Status: {}",
meta.site_name,
meta.timestamp,
git_commit,
meta.container_image,
duration_str,
meta.exit_status,
)
}
/// Get the current git commit hash from a repository.
///
/// Returns the short (7 character) commit hash, or None if the repository
/// is not a valid git repository or the command fails.
pub async fn get_git_commit(clone_dir: &Path) -> Option<String> {
let mut cmd = Command::new("git");
cmd.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE");
let output = cmd
.args(["rev-parse", "--short", "HEAD"])
.current_dir(clone_dir)
.output()
.await
.ok()?;
if !output.status.success() {
return None;
}
let commit = String::from_utf8_lossy(&output.stdout).trim().to_owned();
if commit.is_empty() {
None
} else {
Some(commit)
}
}
/// Save hook log to disk via streaming composition.
///
/// Writes the metadata header to the log file, then streams stdout and stderr
/// content from temporary files via `tokio::io::copy` (O(1) memory).
/// Deletes the temporary files after successful composition.
///
/// Creates a log file at `{log_dir}/{site_name}/{timestamp}-hook.log`.
/// A log is written for every hook invocation regardless of outcome.
///
/// # Errors
///
/// Returns an error if the log directory cannot be created or the log file
/// cannot be written.
pub async fn save_hook_log(
log_dir: &Path,
site_name: &str,
timestamp: &str,
hook_result: &HookResult,
) -> Result<PathBuf> {
let site_log_dir = log_dir.join(site_name);
let log_file = site_log_dir.join(format!("{timestamp}-hook.log"));
tokio::fs::create_dir_all(&site_log_dir)
.await
.with_context(|| {
format!(
"failed to create logs directory: {}",
site_log_dir.display()
)
})?;
let mut log_writer = tokio::io::BufWriter::new(
tokio::fs::File::create(&log_file)
.await
.with_context(|| format!("failed to create hook log file: {}", log_file.display()))?,
);
let header = format_hook_log_header(site_name, timestamp, hook_result);
log_writer.write_all(header.as_bytes()).await?;
// Append stdout section
log_writer.write_all(b"\n=== STDOUT ===\n").await?;
let mut stdout_reader = tokio::fs::File::open(&hook_result.stdout_file)
.await
.with_context(|| format!("failed to open {}", hook_result.stdout_file.display()))?;
tokio::io::copy(&mut stdout_reader, &mut log_writer).await?;
// Append stderr section
log_writer.write_all(b"\n\n=== STDERR ===\n").await?;
let mut stderr_reader = tokio::fs::File::open(&hook_result.stderr_file)
.await
.with_context(|| format!("failed to open {}", hook_result.stderr_file.display()))?;
tokio::io::copy(&mut stderr_reader, &mut log_writer).await?;
log_writer.write_all(b"\n").await?;
log_writer.flush().await?;
drop(log_writer);
// Delete temp files (best-effort)
let _ = tokio::fs::remove_file(&hook_result.stdout_file).await;
let _ = tokio::fs::remove_file(&hook_result.stderr_file).await;
debug!("[{site_name}] hook log saved: {}", log_file.display());
Ok(log_file)
}
/// Format the metadata header for a hook log (without output sections).
fn format_hook_log_header(site_name: &str, timestamp: &str, result: &HookResult) -> String {
let command_str = result.command.join(" ");
let duration_str = format_duration(result.duration);
let status_str = if result.success {
"success".to_owned()
} else if let Some(code) = result.exit_code {
format!("failed (exit code {code})")
} else {
"failed (signal)".to_owned()
};
format!(
"=== HOOK LOG ===\n\
Site: {site_name}\n\
Timestamp: {timestamp}\n\
Command: {command_str}\n\
Duration: {duration_str}\n\
Status: {status_str}"
)
}
/// Combined deployment status (build + optional hook).
#[derive(Debug, Clone, serde::Serialize)]
pub struct DeploymentStatus {
pub site_name: String,
pub timestamp: String,
pub git_commit: String,
pub duration: String,
pub status: String,
pub log: String,
pub current_build: String,
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
mod tests {
use super::*;
use crate::test_support::{cleanup, temp_dir};
use tokio::fs;
/// Create a git Command isolated from parent git environment.
/// Prevents interference when tests run inside git hooks
/// (e.g., pre-commit hook running `cargo test`).
fn git_cmd() -> Command {
let mut cmd = Command::new("git");
cmd.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE");
cmd
}
#[tokio::test]
async fn save_build_log_creates_file_with_correct_content() {
let base_dir = temp_dir("logs-test").await;
let log_dir = base_dir.join("logs");
let meta = BuildLogMeta {
site_name: "test-site".to_owned(),
timestamp: "20260126-143000-123456".to_owned(),
git_commit: Some("abc123d".to_owned()),
container_image: "node:20-alpine".to_owned(),
duration: Duration::from_secs(45),
exit_status: BuildExitStatus::Success,
};
// Create temp files with content
let stdout_tmp = base_dir.join("stdout.tmp");
let stderr_tmp = base_dir.join("stderr.tmp");
fs::write(&stdout_tmp, "build output").await.unwrap();
fs::write(&stderr_tmp, "warning message").await.unwrap();
let result = save_build_log(&log_dir, &meta, &stdout_tmp, &stderr_tmp).await;
assert!(result.is_ok(), "save_build_log should succeed: {result:?}");
let log_path = result.unwrap();
// Verify file exists at expected path
assert_eq!(
log_path,
log_dir.join("test-site/20260126-143000-123456.log")
);
assert!(log_path.exists(), "log file should exist");
// Verify content
let content = fs::read_to_string(&log_path).await.unwrap();
assert!(content.contains("=== BUILD LOG ==="));
assert!(content.contains("Site: test-site"));
assert!(content.contains("Timestamp: 20260126-143000-123456"));
assert!(content.contains("Git Commit: abc123d"));
assert!(content.contains("Image: node:20-alpine"));
assert!(content.contains("Duration: 45s"));
assert!(content.contains("Status: success"));
assert!(content.contains("=== STDOUT ==="));
assert!(content.contains("build output"));
assert!(content.contains("=== STDERR ==="));
assert!(content.contains("warning message"));
// Verify temp files were deleted
assert!(!stdout_tmp.exists(), "stdout temp file should be deleted");
assert!(!stderr_tmp.exists(), "stderr temp file should be deleted");
cleanup(&base_dir).await;
}
#[tokio::test]
async fn save_build_log_handles_empty_output() {
let base_dir = temp_dir("logs-test").await;
let log_dir = base_dir.join("logs");
let meta = BuildLogMeta {
site_name: "empty-site".to_owned(),
timestamp: "20260126-150000-000000".to_owned(),
git_commit: None,
container_image: "alpine:latest".to_owned(),
duration: Duration::from_secs(5),
exit_status: BuildExitStatus::Success,
};
let stdout_tmp = base_dir.join("stdout.tmp");
let stderr_tmp = base_dir.join("stderr.tmp");
fs::write(&stdout_tmp, "").await.unwrap();
fs::write(&stderr_tmp, "").await.unwrap();
let result = save_build_log(&log_dir, &meta, &stdout_tmp, &stderr_tmp).await;
assert!(result.is_ok(), "save_build_log should succeed: {result:?}");
let log_path = result.unwrap();
let content = fs::read_to_string(&log_path).await.unwrap();
assert!(content.contains("Git Commit: unknown"));
assert!(content.contains("=== STDOUT ===\n\n"));
assert!(content.contains("=== STDERR ===\n\n"));
cleanup(&base_dir).await;
}
#[tokio::test]
async fn save_build_log_failed_status() {
let base_dir = temp_dir("logs-test").await;
let log_dir = base_dir.join("logs");
let meta = BuildLogMeta {
site_name: "failed-site".to_owned(),
timestamp: "20260126-160000-000000".to_owned(),
git_commit: Some("def456".to_owned()),
container_image: "node:18".to_owned(),
duration: Duration::from_secs(120),
exit_status: BuildExitStatus::Failed {
exit_code: Some(1),
error: "npm install failed".to_owned(),
},
};
let stdout_tmp = base_dir.join("stdout.tmp");
let stderr_tmp = base_dir.join("stderr.tmp");
fs::write(&stdout_tmp, "").await.unwrap();
fs::write(&stderr_tmp, "Error: ENOENT").await.unwrap();
let result = save_build_log(&log_dir, &meta, &stdout_tmp, &stderr_tmp).await;
assert!(result.is_ok());
let log_path = result.unwrap();
let content = fs::read_to_string(&log_path).await.unwrap();
assert!(content.contains("Duration: 2m 0s"));
assert!(content.contains("Status: failed (exit code: 1): npm install failed"));
cleanup(&base_dir).await;
}
#[tokio::test]
async fn save_build_log_deletes_temp_files() {
let base_dir = temp_dir("logs-test").await;
let log_dir = base_dir.join("logs");
let meta = BuildLogMeta {
site_name: "temp-test".to_owned(),
timestamp: "20260126-170000-000000".to_owned(),
git_commit: None,
container_image: "alpine:latest".to_owned(),
duration: Duration::from_secs(1),
exit_status: BuildExitStatus::Success,
};
let stdout_tmp = base_dir.join("stdout.tmp");
let stderr_tmp = base_dir.join("stderr.tmp");
fs::write(&stdout_tmp, "some output").await.unwrap();
fs::write(&stderr_tmp, "some errors").await.unwrap();
assert!(stdout_tmp.exists());
assert!(stderr_tmp.exists());
let result = save_build_log(&log_dir, &meta, &stdout_tmp, &stderr_tmp).await;
assert!(result.is_ok());
// Temp files must be gone
assert!(!stdout_tmp.exists(), "stdout temp file should be deleted");
assert!(!stderr_tmp.exists(), "stderr temp file should be deleted");
cleanup(&base_dir).await;
}
#[tokio::test]
async fn get_git_commit_returns_short_hash() {
let temp = temp_dir("logs-test").await;
// Initialize a git repo
git_cmd()
.args(["init"])
.current_dir(&temp)
.output()
.await
.unwrap();
// Configure git user for commit
git_cmd()
.args(["config", "user.email", "test@test.com"])
.current_dir(&temp)
.output()
.await
.unwrap();
git_cmd()
.args(["config", "user.name", "Test"])
.current_dir(&temp)
.output()
.await
.unwrap();
// Create a file and commit
fs::write(temp.join("file.txt"), "content").await.unwrap();
git_cmd()
.args(["add", "."])
.current_dir(&temp)
.output()
.await
.unwrap();
git_cmd()
.args(["commit", "-m", "initial"])
.current_dir(&temp)
.output()
.await
.unwrap();
let commit = get_git_commit(&temp).await;
assert!(commit.is_some(), "should return commit hash");
let hash = commit.unwrap();
assert!(!hash.is_empty(), "hash should not be empty");
assert!(hash.len() >= 7, "short hash should be at least 7 chars");
cleanup(&temp).await;
}
#[tokio::test]
async fn get_git_commit_returns_none_for_non_repo() {
let temp = temp_dir("logs-test").await;
// No git init - just an empty directory
let commit = get_git_commit(&temp).await;
assert!(commit.is_none(), "should return None for non-git directory");
cleanup(&temp).await;
}
#[tokio::test]
async fn save_hook_log_creates_file_with_correct_content() {
let base_dir = temp_dir("logs-test").await;
let log_dir = base_dir.join("logs");
let stdout_tmp = base_dir.join("hook-stdout.tmp");
let stderr_tmp = base_dir.join("hook-stderr.tmp");
fs::write(&stdout_tmp, "hook output").await.unwrap();
fs::write(&stderr_tmp, "").await.unwrap();
let hook_result = HookResult {
command: vec!["touch".to_owned(), "marker".to_owned()],
stdout_file: stdout_tmp.clone(),
stderr_file: stderr_tmp.clone(),
last_stderr: String::new(),
exit_code: Some(0),
duration: Duration::from_secs(1),
success: true,
};
let result = save_hook_log(
&log_dir,
"test-site",
"20260202-120000-000000",
&hook_result,
)
.await;
assert!(result.is_ok());
let log_path = result.unwrap();
assert_eq!(
log_path,
log_dir.join("test-site/20260202-120000-000000-hook.log")
);
assert!(log_path.exists());
let content = fs::read_to_string(&log_path).await.unwrap();
assert!(content.contains("=== HOOK LOG ==="));
assert!(content.contains("Site: test-site"));
assert!(content.contains("Command: touch marker"));
assert!(content.contains("Status: success"));
assert!(content.contains("=== STDOUT ==="));
assert!(content.contains("hook output"));
// Temp files should be deleted
assert!(!stdout_tmp.exists());
assert!(!stderr_tmp.exists());
cleanup(&base_dir).await;
}
#[tokio::test]
async fn save_hook_log_failure_status() {
let base_dir = temp_dir("logs-test").await;
let log_dir = base_dir.join("logs");
let stdout_tmp = base_dir.join("hook-stdout.tmp");
let stderr_tmp = base_dir.join("hook-stderr.tmp");
fs::write(&stdout_tmp, "").await.unwrap();
fs::write(&stderr_tmp, "error output").await.unwrap();
let hook_result = HookResult {
command: vec!["false".to_owned()],
stdout_file: stdout_tmp,
stderr_file: stderr_tmp,
last_stderr: "error output".to_owned(),
exit_code: Some(1),
duration: Duration::from_secs(0),
success: false,
};
let result = save_hook_log(
&log_dir,
"test-site",
"20260202-120000-000000",
&hook_result,
)
.await;
assert!(result.is_ok());
let log_path = result.unwrap();
let content = fs::read_to_string(&log_path).await.unwrap();
assert!(content.contains("Status: failed (exit code 1)"));
assert!(content.contains("error output"));
cleanup(&base_dir).await;
}
#[tokio::test]
async fn save_hook_log_signal_status() {
let base_dir = temp_dir("logs-test").await;
let log_dir = base_dir.join("logs");
let stdout_tmp = base_dir.join("hook-stdout.tmp");
let stderr_tmp = base_dir.join("hook-stderr.tmp");
fs::write(&stdout_tmp, "").await.unwrap();
fs::write(&stderr_tmp, "post-deploy hook timed out after 30s")
.await
.unwrap();
let hook_result = HookResult {
command: vec!["sleep".to_owned(), "100".to_owned()],
stdout_file: stdout_tmp,
stderr_file: stderr_tmp,
last_stderr: String::new(),
exit_code: None,
duration: Duration::from_secs(30),
success: false,
};
let result = save_hook_log(
&log_dir,
"test-site",
"20260202-120000-000000",
&hook_result,
)
.await;
assert!(result.is_ok());
let log_path = result.unwrap();
let content = fs::read_to_string(&log_path).await.unwrap();
assert!(content.contains("Status: failed (signal)"));
assert!(content.contains("timed out"));
cleanup(&base_dir).await;
}
}
|