ffcv 1.1.1

Firefox Configuration Viewer - Parse and query Firefox preference files
Documentation
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
use crate::cli;
use ffcv::PrefValue;
use ffcv::PrefValueExt;
use ffcv::{
    find_all_firefox_installations, find_firefox_installation, find_profile_path,
    list_profiles as list_profiles_impl, merge_all_preferences, query_preferences, MergeConfig,
    PrefSource,
};

/// Configuration parameters for viewing Firefox configuration
pub struct ViewConfigParams<'a> {
    pub stdin: bool,
    pub profile_name: &'a str,
    pub profiles_dir_opt: Option<&'a std::path::Path>,
    pub install_dir_opt: Option<&'a std::path::Path>,
    pub max_file_size: usize,
    pub query_patterns: &'a [&'a str],
    pub get: Option<String>,
    pub output_type: cli::OutputType,
    pub show_only_modified: bool,
    pub all: bool,
    pub unexplained_only: bool,
}

/// List all available Firefox profiles
pub fn list_profiles(
    profiles_dir_opt: Option<&std::path::Path>,
) -> Result<(), Box<dyn std::error::Error>> {
    let profiles = list_profiles_impl(profiles_dir_opt).map_err(|e| {
        anyhow::anyhow!(
            "Failed to list profiles: {}. Make sure Firefox is installed.",
            e
        )
    })?;

    let json = serde_json::to_string_pretty(&profiles)?;
    println!("{}", json);
    Ok(())
}

/// List Firefox installations
pub fn list_installations(all: bool) -> Result<(), Box<dyn std::error::Error>> {
    let installations = if all {
        find_all_firefox_installations()
            .map_err(|e| anyhow::anyhow!("Failed to find Firefox installations: {}", e))?
    } else {
        match find_firefox_installation()
            .map_err(|e| anyhow::anyhow!("Failed to find Firefox installation: {}", e))?
        {
            Some(install) => vec![install],
            None => {
                // Return empty JSON array when no installation found
                println!("[]");
                return Ok(());
            }
        }
    };

    // Always output JSON array (even if empty)
    let json = serde_json::to_string_pretty(&installations)?;
    println!("{}", json);

    Ok(())
}

/// Read preference content from standard input
fn read_stdin_content(max_file_size: usize) -> Result<String, Box<dyn std::error::Error>> {
    use std::io::{self, Read};

    let mut buffer = String::new();
    let bytes_read = io::stdin().read_to_string(&mut buffer).map_err(|e| {
        anyhow::anyhow!(
            "Failed to read from stdin: {}. Make sure to pipe prefs.js content.",
            e
        )
    })?;

    if bytes_read > max_file_size {
        return Err(anyhow::anyhow!(
            "Input from stdin exceeds maximum size limit: {} bytes > {} bytes. \
             Use --max-file-size to increase the limit.",
            bytes_read,
            max_file_size
        )
        .into());
    }

    Ok(buffer)
}

/// View configuration for a specific profile
pub fn view_config(params: ViewConfigParams) -> Result<(), Box<dyn std::error::Error>> {
    // If stdin mode, use old behavior (only parse user prefs)
    if params.stdin {
        let content = read_stdin_content(params.max_file_size)?;

        // Parse preferences (always returns Vec<PrefEntry> with types)
        let preferences: Vec<ffcv::PrefEntry> = ffcv::parse_prefs_js(&content).map_err(|e| {
            anyhow::anyhow!(
                "Failed to parse preferences from stdin: {}. The input may be malformed.",
                e
            )
        })?;

        output_preferences(&preferences, &params)?;
        return Ok(());
    }

    // Normal mode: merge all preference sources
    let profile_path = find_profile_path(params.profile_name, params.profiles_dir_opt).map_err(|e| {
        anyhow::anyhow!(
            "Failed to find profile '{}': {}. Make sure Firefox is installed and the profile exists.\n\
             Use 'ffcv profile' to see available profiles.",
            params.profile_name,
            e
        )
    })?;

    // Configure merge
    let merge_config = MergeConfig {
        include_builtins: params.all,
        include_globals: params.all,
        include_user: true,
        continue_on_error: true,
    };

    // Merge all preferences
    let merged = merge_all_preferences(&profile_path, params.install_dir_opt, &merge_config)
        .map_err(|e| anyhow::anyhow!("Failed to merge preferences: {}", e))?;

    // Display warnings
    for warning in &merged.warnings {
        eprintln!("Warning: {}", warning);
    }

    // Get preferences from merged result
    let preferences = merged.entries;

    output_preferences(&preferences, &params)?;

    Ok(())
}

/// Output preferences based on configuration
fn output_preferences(
    preferences: &[ffcv::PrefEntry],
    params: &ViewConfigParams,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut output_prefs = preferences.to_vec();

    // Handle --get mode: single preference retrieval with raw output
    if let Some(ref get_key) = params.get {
        if let Some(entry) = output_prefs.iter().find(|e| e.key == *get_key) {
            // Check unexplained-only flag
            if params.unexplained_only && entry.explanation.is_some() {
                return Err(anyhow::anyhow!(
                    "Preference '{}' has an explanation, but --unexplained-only was specified",
                    get_key
                )
                .into());
            }
            output_raw_value(&entry.value)?;
            return Ok(());
        }
        // If preference not found, return error
        return Err(anyhow::anyhow!("Preference '{}' not found", get_key).into());
    }

    // Apply --show-only-modified filter if flag is set
    if params.show_only_modified {
        output_prefs.retain(|entry| {
            // Keep only user-set preferences
            entry.source == Some(PrefSource::User)
        });
    }

    // Apply queries if provided
    if !params.query_patterns.is_empty() {
        output_prefs = query_preferences(&output_prefs, params.query_patterns)
            .map_err(|e| anyhow::anyhow!("Failed to apply query: {}", e))?;
    }

    // Apply unexplained-only filter if flag is set
    if params.unexplained_only {
        output_prefs.retain(|entry| {
            // Keep only preferences that don't have explanations
            entry.explanation.is_none()
        });
    }

    let json = match params.output_type {
        cli::OutputType::JsonObject => {
            // Convert Vec<PrefEntry> to BTreeMap for JSON object output (sorted by key)
            // Note: json-object does NOT include source or source_file
            let json_map: std::collections::BTreeMap<String, serde_json::Value> = output_prefs
                .iter()
                .map(|entry| (entry.key.clone(), entry.value.to_json_value()))
                .collect();
            serde_json::to_string_pretty(&json_map)?
        }
        cli::OutputType::JsonArray => {
            // Use Vec<PrefEntry> directly for array output
            // Note: json-array DOES include source and source_file (full entry)
            let mut sorted_entries = output_prefs.clone();

            // Sort alphabetically by key for deterministic output order
            sorted_entries.sort_by(|a, b| a.key.cmp(&b.key));

            serde_json::to_string_pretty(&sorted_entries)?
        }
    };

    println!("{}", json);
    Ok(())
}

/// Output a single preference value in raw format (no JSON wrapping)
fn output_raw_value(value: &PrefValue) -> Result<(), Box<dyn std::error::Error>> {
    match value {
        PrefValue::String(s) => println!("{}", s),
        PrefValue::Bool(b) => println!("{}", b),
        PrefValue::Integer(i) => println!("{}", i),
        PrefValue::Float(f) => println!("{}", f),
        PrefValue::Null => println!("null"),
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use ffcv::PrefType;
    use ffcv::PrefValue;
    use ffcv::PrefValueExt;

    /// Helper function to test the output formatting logic
    fn format_value(value: &PrefValue) -> String {
        match value {
            PrefValue::Integer(i) => format!("{}", i),
            PrefValue::Float(f) => format!("{}", f),
            PrefValue::String(s) => s.clone(),
            PrefValue::Bool(b) => format!("{}", b),
            PrefValue::Null => "null".to_string(),
        }
    }

    #[test]
    fn test_pref_entry_serialization() {
        // Test that PrefEntry serializes correctly
        let entry = ffcv::PrefEntry {
            key: "test.key".to_string(),
            value: PrefValue::String("test value".to_string()),
            pref_type: PrefType::User,
            explanation: None,
            source: Some(ffcv::PrefSource::User),
            source_file: Some("prefs.js".to_string()),
            locked: None,
        };

        let json_str = serde_json::to_string(&entry).unwrap();
        assert!(json_str.contains("\"pref_type\":\"user\""));
        assert!(json_str.contains("\"key\":\"test.key\""));
        // PrefValue::String serializes as {"String": "test value"}
        assert!(json_str.contains("\"value\":{\"String\":\"test value\"}"));
        // explanation should not be present when None
        assert!(!json_str.contains("explanation"));
    }

    #[test]
    fn test_pref_type_serialization() {
        // Test all pref type variants serialize correctly
        let tests = vec![
            (PrefType::User, "user"),
            (PrefType::Default, "default"),
            (PrefType::Locked, "locked"),
            (PrefType::Sticky, "sticky"),
        ];

        for (pref_type, expected_str) in tests {
            let json_str = serde_json::to_string(&pref_type).unwrap();
            assert_eq!(json_str, format!("\"{}\"", expected_str));
        }
    }

    #[test]
    fn test_json_array_output_with_types() {
        // Test that json-array output is sorted alphabetically by key
        let input = r#"
            user_pref("user.pref", "value1");
            pref("default.pref", "value2");
            lock_pref("locked.pref", "value3");
            sticky_pref("sticky.pref", "value4");
        "#;

        let mut array_output = ffcv::parse_prefs_js(input).unwrap();

        // Sort to match production code behavior
        array_output.sort_by(|a, b| a.key.cmp(&b.key));

        let json_str = serde_json::to_string_pretty(&array_output).unwrap();

        // Verify pref_type field is present for all entries
        assert!(json_str.contains("pref_type"));
        assert!(json_str.contains("\"user\""));
        assert!(json_str.contains("\"default\""));
        assert!(json_str.contains("\"locked\""));
        assert!(json_str.contains("\"sticky\""));

        // Verify keys are present
        assert!(json_str.contains("user.pref"));
        assert!(json_str.contains("default.pref"));
        assert!(json_str.contains("locked.pref"));
        assert!(json_str.contains("sticky.pref"));

        // Verify structure (should have key, value, pref_type for each entry)
        // explanation should NOT be present since these prefs don't have explanations
        let parsed: Vec<serde_json::Value> = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed.len(), 4);

        // Verify alphabetical ordering
        let keys: Vec<&str> = parsed
            .iter()
            .map(|entry| entry["key"].as_str().unwrap())
            .collect();
        assert_eq!(
            keys,
            vec!["default.pref", "locked.pref", "sticky.pref", "user.pref"]
        );

        for entry in parsed {
            assert!(entry.is_object());
            let obj = entry.as_object().unwrap();
            assert!(obj.contains_key("key"));
            assert!(obj.contains_key("value"));
            assert!(obj.contains_key("pref_type"));
            // explanation field should not be present for these unexplained prefs
            assert!(!obj.contains_key("explanation"));
        }
    }

    #[test]
    fn test_output_raw_value_integer() {
        let value = PrefValue::Integer(3);
        let output = format_value(&value);
        assert_eq!(output, "3");
        assert!(!output.contains('.'));
    }

    #[test]
    fn test_output_raw_value_negative_integer() {
        let value = PrefValue::Integer(-42);
        let output = format_value(&value);
        assert_eq!(output, "-42");
        assert!(!output.contains('.'));
    }

    #[test]
    fn test_output_raw_value_zero() {
        let value = PrefValue::Integer(0);
        let output = format_value(&value);
        assert_eq!(output, "0");
        assert!(!output.contains('.'));
    }

    #[test]
    fn test_output_raw_value_float() {
        let value = PrefValue::Float(2.5);
        let output = format_value(&value);
        assert_eq!(output, "2.5");
        assert!(output.contains('.'));
    }

    #[test]
    fn test_output_raw_value_float_whole_number() {
        // 3.0 is a whole number, so it should be Integer(3), not Float(3.0)
        let value = PrefValue::Integer(3);
        let output = format_value(&value);
        assert_eq!(output, "3");
        assert!(!output.contains('.'));
    }

    #[test]
    fn test_output_raw_value_string() {
        let value = PrefValue::String("test value".to_string());
        let output = format_value(&value);
        assert_eq!(output, "test value");
    }

    #[test]
    fn test_output_raw_value_bool() {
        let value = PrefValue::Bool(true);
        let output = format_value(&value);
        assert_eq!(output, "true");

        let value = PrefValue::Bool(false);
        let output = format_value(&value);
        assert_eq!(output, "false");
    }

    #[test]
    fn test_output_raw_value_null() {
        let value = PrefValue::Null;
        let output = format_value(&value);
        assert_eq!(output, "null");
    }

    #[test]
    fn test_pref_entry_serialization_with_explanation() {
        // Test that PrefEntry includes explanation field in JSON output
        let entry = ffcv::PrefEntry {
            key: "javascript.enabled".to_string(),
            value: PrefValue::Bool(true),
            pref_type: PrefType::Default,
            explanation: Some("Master switch to enable or disable JavaScript execution."),
            source: Some(ffcv::PrefSource::User),
            source_file: Some("prefs.js".to_string()),
            locked: None,
        };

        let json_str = serde_json::to_string(&entry).unwrap();
        assert!(json_str.contains("\"explanation\":"));
        assert!(json_str.contains("Master switch to enable or disable JavaScript execution"));
    }

    #[test]
    fn test_pref_entry_serialization_without_explanation() {
        // Test that PrefEntry without explanation does not include the field
        let entry = ffcv::PrefEntry {
            key: "unknown.pref".to_string(),
            value: PrefValue::String("test".to_string()),
            pref_type: PrefType::User,
            explanation: None,
            source: Some(ffcv::PrefSource::User),
            source_file: Some("prefs.js".to_string()),
            locked: None,
        };

        let json_str = serde_json::to_string(&entry).unwrap();
        // explanation field should not be in output when None
        assert!(!json_str.contains("explanation"));
    }

    #[test]
    fn test_json_array_output_includes_explanations() {
        // Test full pipeline with explanations
        let input = r#"
            user_pref("javascript.enabled", true);
            user_pref("browser.startup.homepage", "https://example.com");
        "#;

        let mut array_output = ffcv::parse_prefs_js(input).unwrap();

        // Sort to match production code behavior
        array_output.sort_by(|a, b| a.key.cmp(&b.key));

        let json_str = serde_json::to_string_pretty(&array_output).unwrap();

        // Verify javascript.enabled has its explanation
        assert!(json_str.contains("Master switch to enable or disable JavaScript"));

        // Verify entries are handled correctly
        let parsed: Vec<serde_json::Value> = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed.len(), 2);

        // Find entries by key instead of by index (deterministic regardless of order)
        let js_entry = parsed
            .iter()
            .find(|entry| entry["key"] == "javascript.enabled")
            .expect("javascript.enabled should be present")
            .as_object()
            .unwrap();
        assert!(js_entry.contains_key("explanation"));

        let homepage_entry = parsed
            .iter()
            .find(|entry| entry["key"] == "browser.startup.homepage")
            .expect("browser.startup.homepage should be present")
            .as_object()
            .unwrap();
        assert!(!homepage_entry.contains_key("explanation"));
    }

    #[test]
    fn test_json_object_output_sorted_alphabetically() {
        // Test that JSON object output maintains alphabetical key order
        let input = r#"
            user_pref("zebra.pref", "value1");
            user_pref("apple.pref", "value2");
            user_pref("banana.pref", "value3");
        "#;

        let prefs = ffcv::parse_prefs_js(input).unwrap();

        // Create JSON object output using BTreeMap
        let json_map: std::collections::BTreeMap<String, serde_json::Value> = prefs
            .iter()
            .map(|entry| (entry.key.clone(), entry.value.to_json_value()))
            .collect();

        let json_str = serde_json::to_string_pretty(&json_map).unwrap();
        let parsed: serde_json::Map<String, serde_json::Value> =
            serde_json::from_str(&json_str).unwrap();

        // Verify keys are in alphabetical order
        let keys: Vec<&String> = parsed.keys().collect();
        assert_eq!(keys, vec!["apple.pref", "banana.pref", "zebra.pref"]);
    }

    #[test]
    fn test_stdin_size_limit_enforcement() {
        // Create a large string that exceeds a small limit
        let large_content = "user_pref(\"test\", \"x\");".repeat(1000);
        let small_limit = 100;

        // The real test is in the integration test with actual large files
        // This test documents the expected behavior
        assert!(large_content.len() > small_limit);
    }

    #[test]
    fn test_max_file_size_parameter() {
        // Test that max_file_size parameter is properly typed
        let max_size: usize = 10_485_760; // 10MB in bytes
        assert_eq!(max_size, 10_485_760);

        // Test that we can calculate MB from bytes
        let size_in_mb = max_size / 1_048_576;
        assert_eq!(size_in_mb, 10);
    }
}