-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcommon.rs
More file actions
422 lines (360 loc) · 13.3 KB
/
Copy pathcommon.rs
File metadata and controls
422 lines (360 loc) · 13.3 KB
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
//! Common trace file writer infrastructure
//!
//! Provides shared file I/O operations for all command-specific trace writers:
//! - File creation and writing
//! - Directory management
//! - Timestamp-based filename generation
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use super::error::TraceWriterError;
use crate::shared::Clock;
/// Timestamp format for trace filenames: YYYYmmdd-HHMMSS
/// Example: 20251008-143045
const TRACE_FILENAME_TIMESTAMP_FORMAT: &str = "%Y%m%d-%H%M%S";
/// Common trace file writer infrastructure
///
/// Provides shared functionality for all command-specific trace writers:
/// - File I/O operations
/// - Directory management
/// - Timestamp-based filename generation
///
/// This is used as a collaborator by command-specific writers.
pub(super) struct CommonTraceWriter {
traces_dir: PathBuf,
clock: Arc<dyn Clock>,
}
impl CommonTraceWriter {
/// Create a new common trace writer
///
/// # Arguments
///
/// * `traces_dir` - Directory where trace files will be written
/// * `clock` - Clock for timestamp generation
pub(super) fn new(traces_dir: impl Into<PathBuf>, clock: Arc<dyn Clock>) -> Self {
Self {
traces_dir: traces_dir.into(),
clock,
}
}
/// Write trace content to a file
///
/// Creates the traces directory if needed, generates a timestamp-based
/// filename, and writes the content.
///
/// # Arguments
///
/// * `command_name` - Name of the command (used in filename: `{timestamp}-{command_name}.log`)
/// * `content` - Content to write to the trace file
///
/// # Returns
///
/// Path to the created trace file
///
/// # Errors
///
/// Returns an error if directory creation or file writing fails
pub(super) fn write_trace(
&self,
command_name: &str,
content: &str,
) -> Result<PathBuf, TraceWriterError> {
self.ensure_traces_dir()?;
let trace_file = self.generate_trace_filename(command_name);
self.write_trace_file(&trace_file, content)?;
Ok(trace_file)
}
/// Generate a timestamp-based trace filename
///
/// Creates a filename in the format: `{timestamp}-{command_name}.log`
/// where timestamp is `YYYYmmdd-HHMMSS`.
///
/// # Arguments
///
/// * `command_name` - Name of the command to include in the filename
///
/// # Returns
///
/// Full path to the trace file
fn generate_trace_filename(&self, command_name: &str) -> PathBuf {
let timestamp = self.clock.now().format(TRACE_FILENAME_TIMESTAMP_FORMAT);
self.traces_dir
.join(format!("{timestamp}-{command_name}.log"))
}
/// Write content to a trace file
///
/// Creates the file and writes all content to it.
///
/// # Arguments
///
/// * `trace_file` - Path where the trace file should be created
/// * `content` - Content to write to the file
///
/// # Errors
///
/// Returns an error if file creation or writing fails
fn write_trace_file(&self, trace_file: &Path, content: &str) -> Result<(), TraceWriterError> {
let mut file = self.create_trace_file(trace_file)?;
file.write_all(content.as_bytes())
.map_err(|source| TraceWriterError::FileWrite {
path: trace_file.display().to_string(),
source,
})?;
Ok(())
}
/// Create a new trace file
///
/// # Arguments
///
/// * `trace_file` - Path where the file should be created
///
/// # Returns
///
/// File handle for writing
///
/// # Errors
///
/// Returns an error if file creation fails
#[allow(clippy::unused_self)] // Kept as instance method for consistency with other trace writer methods
fn create_trace_file(&self, trace_file: &Path) -> Result<fs::File, TraceWriterError> {
fs::File::create(trace_file).map_err(|source| TraceWriterError::FileWrite {
path: trace_file.display().to_string(),
source,
})
}
/// Ensure the traces directory exists
///
/// Creates the directory if it doesn't exist.
fn ensure_traces_dir(&self) -> Result<(), TraceWriterError> {
if !self.traces_dir.exists() {
fs::create_dir_all(&self.traces_dir).map_err(|source| {
TraceWriterError::DirectoryCreation {
path: self.traces_dir.display().to_string(),
source,
}
})?;
}
Ok(())
}
/// Get the traces directory path
pub(super) fn traces_dir(&self) -> &Path {
&self.traces_dir
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
// Test helpers - Arrange phase utilities
use crate::domain::environment::TRACES_DIR_NAME;
use crate::testing::MockClock;
use chrono::TimeZone;
use std::sync::Arc;
/// Create a test writer with a temporary directory
///
/// Returns (writer, `temp_dir`, `traces_dir`)
/// The `temp_dir` must be kept alive for the duration of the test
fn create_test_writer() -> (CommonTraceWriter, TempDir, PathBuf) {
use crate::domain::environment::TRACES_DIR_NAME;
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let traces_dir = temp_dir.path().join(TRACES_DIR_NAME);
let fixed_time = chrono::Utc.with_ymd_and_hms(2025, 10, 7, 12, 0, 0).unwrap();
let clock = Arc::new(MockClock::new(fixed_time));
let writer = CommonTraceWriter::new(traces_dir.clone(), clock);
(writer, temp_dir, traces_dir)
}
#[test]
fn it_should_create_common_trace_writer_with_directory() {
// Arrange
let (writer, _temp_dir, traces_dir) = create_test_writer();
// Assert
assert_eq!(writer.traces_dir(), traces_dir);
}
#[test]
fn it_should_create_traces_directory_on_first_write() {
// Arrange
let (writer, _temp_dir, traces_dir) = create_test_writer();
// Directory should not exist yet
assert!(!traces_dir.exists());
// Act
writer
.write_trace("test-command", "test content")
.expect("Failed to write trace");
// Assert
assert!(traces_dir.exists());
}
#[test]
fn it_should_write_trace_with_timestamp_and_command_name() {
// Arrange
let (writer, _temp_dir, _traces_dir) = create_test_writer();
// Act
let trace_file = writer
.write_trace("test-command", "test content")
.expect("Failed to write trace");
// Assert
assert!(trace_file.exists());
let filename = trace_file.file_name().unwrap().to_str().unwrap();
assert!(
filename.ends_with("-test-command.log"),
"Filename should end with '-test-command.log', got: {filename}"
);
}
#[test]
fn it_should_write_correct_content_to_trace_file() {
// Arrange
let (writer, _temp_dir, _traces_dir) = create_test_writer();
let test_content = "This is test trace content\nwith multiple lines\nand details";
// Act
let trace_file = writer
.write_trace("test-command", test_content)
.expect("Failed to write trace");
// Assert
let written_content =
std::fs::read_to_string(trace_file).expect("Failed to read trace file");
assert_eq!(written_content, test_content);
}
#[test]
fn it_should_generate_timestamp_in_correct_format() {
// Arrange
let (writer, _temp_dir, _traces_dir) = create_test_writer();
// Act
let trace_file = writer
.write_trace("test-command", "content")
.expect("Failed to write trace");
// Assert
let filename = trace_file.file_name().unwrap().to_str().unwrap();
// Verify filename format: {timestamp}-test-command.log
// Example: 20251007-143045-test-command.log
let parts: Vec<&str> = filename.split('-').collect();
assert!(
parts.len() >= 3,
"Filename should have at least 3 parts (date, time, command.log), got: {filename}"
);
// Verify first part is date (8 digits: YYYYmmdd)
assert_eq!(
parts[0].len(),
8,
"Date part should be 8 digits, got: {}",
parts[0]
);
assert!(
parts[0].chars().all(|c| c.is_ascii_digit()),
"Date part should be all digits, got: {}",
parts[0]
);
// Verify second part is time (6 digits: HHMMSS)
assert_eq!(
parts[1].len(),
6,
"Time part should be 6 digits, got: {}",
parts[1]
);
assert!(
parts[1].chars().all(|c| c.is_ascii_digit()),
"Time part should be all digits, got: {}",
parts[1]
);
}
#[test]
fn it_should_write_multiple_traces_to_same_directory() {
// Arrange
let (writer, _temp_dir, traces_dir) = create_test_writer();
// Act
let trace1 = writer
.write_trace("command1", "content 1")
.expect("Failed to write first trace");
let trace2 = writer
.write_trace("command2", "content 2")
.expect("Failed to write second trace");
// Assert
assert!(trace1.exists());
assert!(trace2.exists());
// Both files should be in the same directory
assert_eq!(trace1.parent().unwrap(), traces_dir);
assert_eq!(trace2.parent().unwrap(), traces_dir);
// Files should have different names (different commands)
assert_ne!(trace1, trace2);
}
#[test]
fn it_should_handle_empty_content() {
// Arrange
let (writer, _temp_dir, _traces_dir) = create_test_writer();
// Act
let trace_file = writer
.write_trace("test-command", "")
.expect("Failed to write empty trace");
// Assert
assert!(trace_file.exists());
let content = std::fs::read_to_string(trace_file).expect("Failed to read trace file");
assert_eq!(content, "");
}
#[test]
fn it_should_handle_large_content() {
// Arrange
let (writer, _temp_dir, _traces_dir) = create_test_writer();
let large_content = "x".repeat(10_000); // 10KB of content
// Act
let trace_file = writer
.write_trace("test-command", &large_content)
.expect("Failed to write large trace");
// Assert
assert!(trace_file.exists());
let content = std::fs::read_to_string(trace_file).expect("Failed to read trace file");
assert_eq!(content.len(), 10_000);
assert_eq!(content, large_content);
}
#[test]
fn it_should_handle_special_characters_in_content() {
// Arrange
let (writer, _temp_dir, _traces_dir) = create_test_writer();
let special_content = "Special chars: \n\t\r 你好 🚀 ⚡ €£¥";
// Act
let trace_file = writer
.write_trace("test-command", special_content)
.expect("Failed to write trace with special chars");
// Assert
assert!(trace_file.exists());
let content = std::fs::read_to_string(trace_file).expect("Failed to read trace file");
assert_eq!(content, special_content);
}
#[test]
fn it_should_return_error_for_invalid_directory_permissions() {
// This test verifies error handling when directory creation fails
// Note: This test is platform-dependent and may not work on all systems
// Skip on Windows as permission handling is different
#[cfg(not(target_os = "windows"))]
{
use std::fs;
use std::os::unix::fs::PermissionsExt;
// Arrange: Create a read-only parent directory
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let readonly_dir = temp_dir.path().join("readonly");
fs::create_dir(&readonly_dir).expect("Failed to create readonly dir");
// Make directory read-only
let mut perms = fs::metadata(&readonly_dir)
.expect("Failed to get metadata")
.permissions();
perms.set_mode(0o444); // Read-only
fs::set_permissions(&readonly_dir, perms).expect("Failed to set permissions");
let traces_dir = readonly_dir.join(TRACES_DIR_NAME);
let fixed_time = chrono::Utc.with_ymd_and_hms(2025, 10, 7, 12, 0, 0).unwrap();
let clock = Arc::new(MockClock::new(fixed_time));
let writer = CommonTraceWriter::new(traces_dir, clock);
// Act
let result = writer.write_trace("test-command", "content");
// Assert
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
TraceWriterError::DirectoryCreation { .. }
));
// Cleanup: Restore permissions so temp_dir can be deleted
let mut perms = fs::metadata(&readonly_dir)
.expect("Failed to get metadata")
.permissions();
perms.set_mode(0o755);
fs::set_permissions(&readonly_dir, perms).expect("Failed to restore permissions");
}
}
}