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
/// Format detection module for identifying structured data formats
///
/// This module provides heuristic-based format detection to optimize parsing
/// performance by trying the most likely formats first.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum DetectedFormat {
Json,
JsonArray,
Toml,
Yaml,
Csv,
Logfmt,
PlainText,
}
impl DetectedFormat {
/// Check if this detected format is compatible with a forced format
///
/// This allows forced formats to include related variants and processing modes.
/// For example, --json should allow both Json and JsonArray detection,
/// --yaml should work with both document and line-by-line YAML, etc.
pub fn is_compatible_with(&self, forced: &DetectedFormat) -> bool {
match (self, forced) {
// JSON family - Json and JsonArray are interchangeable with --json
(DetectedFormat::Json, DetectedFormat::Json) => true,
(DetectedFormat::JsonArray, DetectedFormat::Json) => true,
(DetectedFormat::Json, DetectedFormat::JsonArray) => true,
(DetectedFormat::JsonArray, DetectedFormat::JsonArray) => true,
// YAML family - can be processed as documents or line-by-line
(DetectedFormat::Yaml, DetectedFormat::Yaml) => true,
// TOML family - can be processed as documents or line-by-line
(DetectedFormat::Toml, DetectedFormat::Toml) => true,
// CSV family - can be processed as complete documents or streaming
(DetectedFormat::Csv, DetectedFormat::Csv) => true,
// Logfmt - typically line-by-line but can be document-level
(DetectedFormat::Logfmt, DetectedFormat::Logfmt) => true,
// PlainText - always compatible with itself
(DetectedFormat::PlainText, DetectedFormat::PlainText) => true,
// Cross-format compatibility could be added here in the future
// For example, if we wanted --structured to match JSON, YAML, TOML
// Everything else is incompatible
_ => false,
}
}
}
pub struct FormatDetector;
impl FormatDetector {
/// Analyze input and return likely formats with confidence scores
///
/// Returns a vector of (format, confidence) pairs sorted by confidence (highest first).
/// Confidence scores range from 0.0 to 1.0.
pub fn detect(input: &str) -> Vec<(DetectedFormat, f32)> {
let mut candidates = Vec::new();
// Fast path: check first few bytes for common structural indicators
let prefix = &input[..input.len().min(100)];
let trimmed_prefix = prefix.trim_start();
// High confidence structural indicators
if trimmed_prefix.starts_with('{') {
candidates.push((DetectedFormat::Json, 0.9));
}
if trimmed_prefix.starts_with('[') {
candidates.push((DetectedFormat::JsonArray, 0.9));
}
if trimmed_prefix.starts_with("---") {
candidates.push((DetectedFormat::Yaml, 0.95));
}
// Heuristic-based detection for formats without clear delimiters
if Self::is_likely_toml(input) {
candidates.push((DetectedFormat::Toml, 0.8));
}
if Self::is_likely_yaml(input) && !trimmed_prefix.starts_with("---") {
// Lower confidence if we didn't already detect YAML via document marker
candidates.push((DetectedFormat::Yaml, 0.7));
}
if Self::is_likely_csv(input) {
candidates.push((DetectedFormat::Csv, 0.6));
}
if Self::is_likely_logfmt(input) {
candidates.push((DetectedFormat::Logfmt, 0.5));
}
// Always include plain text as fallback
candidates.push((DetectedFormat::PlainText, 0.1));
// Sort by confidence (highest first)
candidates.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
// Remove duplicates while preserving highest confidence
let mut seen = std::collections::HashSet::new();
candidates.retain(|(format, _)| seen.insert(format.clone()));
candidates
}
/// Check if content looks like TOML format
///
/// TOML characteristics:
/// - Key = value assignments
/// - Section headers in brackets [section]
/// - Comments starting with #
pub fn is_likely_toml(input: &str) -> bool {
let lines: Vec<&str> = input.lines().take(10).collect(); // Check first 10 lines
let mut toml_indicators = 0;
for line in &lines {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
// Look for key = value pattern typical of TOML (with spaces around =)
if trimmed.contains(" = ") && !trimmed.starts_with('"') {
toml_indicators += 2;
}
// Look for TOML section headers
if trimmed.starts_with('[') && trimmed.ends_with(']') && !trimmed.contains(':') {
toml_indicators += 3;
}
// TOML table arrays
if trimmed.starts_with("[[") && trimmed.ends_with("]]") {
toml_indicators += 3;
}
}
toml_indicators >= 2
}
/// Check if content looks like YAML format
///
/// YAML characteristics:
/// - Key: value patterns (colon followed by space)
/// - List items starting with dash and space
/// - Indentation-based structure
/// - Document markers (---)
pub fn is_likely_yaml(input: &str) -> bool {
let lines: Vec<&str> = input.lines().take(10).collect(); // Check first 10 lines
// YAML document start indicator
if input.trim_start().starts_with("---") {
return true;
}
let mut yaml_indicators = 0;
for line in &lines {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
// Look for YAML key: value pattern (with colon and space)
if trimmed.contains(": ") && !trimmed.starts_with('"') && !trimmed.contains(" = ") {
yaml_indicators += 1;
}
// Look for YAML list items
if trimmed.starts_with("- ") {
yaml_indicators += 1;
}
// Look for indented structure (strong indicator of YAML)
if line.starts_with(" ") && (line.contains(": ") || line.trim().starts_with("- ")) {
yaml_indicators += 2;
}
}
yaml_indicators >= 2
}
/// Check if content looks like CSV format
///
/// CSV characteristics:
/// - Comma-separated values
/// - Consistent number of fields per line
/// - Optional quoted fields
pub fn is_likely_csv(input: &str) -> bool {
let lines: Vec<&str> = input.lines().take(5).collect();
if lines.is_empty() {
return false;
}
// Check if lines contain commas and have consistent field counts
let mut field_counts = Vec::new();
let mut has_commas = false;
for line in &lines {
if line.trim().is_empty() {
continue;
}
let field_count = line.matches(',').count() + 1;
field_counts.push(field_count);
if line.contains(',') {
has_commas = true;
}
}
// Must have commas and either single line with commas or consistent field counts across multiple lines
has_commas
&& (field_counts.len() == 1
|| (field_counts.len() > 1 && field_counts.windows(2).all(|w| w[0] == w[1])))
}
/// Check if content looks like logfmt format
///
/// Logfmt characteristics:
/// - key=value pairs
/// - Space-separated key=value pairs
/// - Values may be quoted
pub fn is_likely_logfmt(input: &str) -> bool {
let lines: Vec<&str> = input.lines().take(5).collect();
for line in &lines {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
// Count key=value patterns
let kv_pairs = trimmed
.split_whitespace()
.filter(|part| part.contains('=') && !part.starts_with('=') && !part.ends_with('='))
.count();
// If most space-separated parts look like key=value, it's likely logfmt
let total_parts = trimmed.split_whitespace().count();
if total_parts > 0 && kv_pairs as f32 / total_parts as f32 > 0.5 {
return true;
}
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_json_detection() {
let json_input = r#"{"name": "Alice", "age": 30}"#;
let detected = FormatDetector::detect(json_input);
assert_eq!(detected[0].0, DetectedFormat::Json);
assert!(detected[0].1 > 0.8);
}
#[test]
fn test_json_array_detection() {
let json_array_input = r#"[{"name": "Alice"}, {"name": "Bob"}]"#;
let detected = FormatDetector::detect(json_array_input);
assert_eq!(detected[0].0, DetectedFormat::JsonArray);
assert!(detected[0].1 > 0.8);
}
#[test]
fn test_yaml_detection() {
let yaml_input = r#"---
name: Alice
age: 30
address:
street: 123 Main St
city: Anytown"#;
let detected = FormatDetector::detect(yaml_input);
assert_eq!(detected[0].0, DetectedFormat::Yaml);
assert!(detected[0].1 > 0.9);
}
#[test]
fn test_toml_detection() {
let toml_input = r#"name = "Alice"
age = 30
[address]
street = "123 Main St"
city = "Anytown""#;
assert!(FormatDetector::is_likely_toml(toml_input));
let detected = FormatDetector::detect(toml_input);
let toml_detected = detected
.iter()
.find(|(format, _)| format == &DetectedFormat::Toml);
assert!(toml_detected.is_some());
assert!(toml_detected.unwrap().1 > 0.7);
}
#[test]
fn test_csv_detection() {
let csv_input = r#"name,age,city
Alice,30,Anytown
Bob,25,Other City"#;
assert!(FormatDetector::is_likely_csv(csv_input));
let detected = FormatDetector::detect(csv_input);
let csv_detected = detected
.iter()
.find(|(format, _)| format == &DetectedFormat::Csv);
assert!(csv_detected.is_some());
}
#[test]
fn test_logfmt_detection() {
let logfmt_input =
r#"level=info msg="User logged in" user_id=123 timestamp="2023-01-01T10:00:00Z""#;
assert!(FormatDetector::is_likely_logfmt(logfmt_input));
let detected = FormatDetector::detect(logfmt_input);
let logfmt_detected = detected
.iter()
.find(|(format, _)| format == &DetectedFormat::Logfmt);
assert!(logfmt_detected.is_some());
}
#[test]
fn test_format_detection_order() {
let json_input = r#"{"name": "Alice", "age": 30}"#;
let detected = FormatDetector::detect(json_input);
// Should be sorted by confidence (highest first)
for window in detected.windows(2) {
assert!(window[0].1 >= window[1].1);
}
}
#[test]
fn test_no_duplicate_formats() {
let mixed_input = r#"{"name": "Alice", "age": 30}"#; // Could be detected as JSON
let detected = FormatDetector::detect(mixed_input);
let mut seen_formats = std::collections::HashSet::new();
for (format, _) in detected {
assert!(seen_formats.insert(format), "Duplicate format detected");
}
}
}