libmagic-rs 0.5.0

A pure-Rust implementation of libmagic for file type identification
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
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
// Copyright (c) 2025-2026 the libmagic-rs contributors
// SPDX-License-Identifier: Apache-2.0

//! Command-line interface for libmagic-rs
//!
//! This binary provides a CLI tool for file type identification using magic rules,
//! serving as a drop-in replacement for the GNU `file` command.

use clap::{CommandFactory, Parser};
use clap_complete::Shell;
use clap_stdin::FileOrStdin;
use libmagic_rs::output::json::{format_json_line_output, format_json_output};
use libmagic_rs::parser::{MagicFileFormat, detect_format};
use libmagic_rs::{LibmagicError, MagicDatabase};
use std::fs;
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::process;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

/// A pure-Rust implementation of libmagic for file type identification
///
/// Supports analyzing multiple files in a single invocation. Each file is
/// processed sequentially with independent error handling.
///
/// Output formats:
///   Text (default): One line per file in format "filename: description"
///   JSON (single file): Pretty-printed JSON with matches array
///   JSON (multiple files): JSON Lines format with compact output per file
#[derive(Parser, Debug)]
#[command(
    name = "rmagic",
    version = env!("CARGO_PKG_VERSION"),
    author = "Rust Libmagic Contributors",
    about = "A pure-Rust implementation of libmagic for file type identification. Supports multiple files and stdin input.",
    after_help = "\
Examples:
  rmagic file1.bin file2.txt file3.dat
  rmagic -j file.bin              # Single file: pretty-printed JSON
  rmagic -j file1.bin file2.txt   # Multiple files: JSON Lines format
  rmagic -s -m custom.magic file1 file2
  rmagic -b file.bin              # Use built-in rules
  rmagic -b -s -j *.bin
  rmagic - < input.dat            # Read from stdin
  rmagic --generate-completion bash > rmagic.bash",
    group(clap::ArgGroup::new("format").args(["json", "text"]))
)]
pub struct Args {
    /// Files to analyze (use '-' for stdin)
    #[arg(value_name = "FILE", required_unless_present = "generate_completion", num_args = 1..)]
    pub files: Vec<FileOrStdin>,

    /// Output results in JSON format
    #[arg(short = 'j', long)]
    pub json: bool,

    /// Output results in text format (default)
    #[arg(long)]
    pub text: bool,

    /// Use custom magic file
    #[arg(short = 'm', long = "magic-file", value_name = "FILE")]
    pub magic_file: Option<PathBuf>,

    /// Exit with non-zero code on failures (I/O, parse, or evaluation errors).
    ///
    /// A "data" result (unknown file type) is not considered an error and will
    /// not cause a non-zero exit code, even in strict mode.
    #[arg(short = 's', long)]
    pub strict: bool,

    /// Use built-in magic rules instead of loading from file.
    ///
    /// Loads pre-compiled built-in rules for common file types (ELF, PE/DOS,
    /// ZIP, TAR, GZIP, JPEG, PNG, GIF, BMP, PDF). These rules are compiled
    /// at build time and provide basic file type detection without requiring
    /// external magic files.
    #[arg(short = 'b', long, conflicts_with = "magic_file")]
    pub use_builtin: bool,

    /// Timeout for evaluation in milliseconds (1-300000ms, 5 minutes max).
    ///
    /// Sets a per-file timeout for magic rule evaluation. If evaluation takes
    /// longer than this duration, the file is skipped with a timeout error.
    /// Each file gets its own independent timeout window.
    #[arg(short = 't', long = "timeout-ms", value_name = "MS",
          value_parser = clap::value_parser!(u64).range(1..=300_000))]
    pub timeout_ms: Option<u64>,

    /// Generate shell completions and exit
    #[arg(long, value_name = "SHELL")]
    pub generate_completion: Option<Shell>,
}

impl Args {
    /// Determine the output format based on flags
    pub fn output_format(&self) -> OutputFormat {
        if self.json {
            OutputFormat::Json
        } else {
            OutputFormat::Text
        }
    }

    /// Get the magic file path to use, with platform-appropriate defaults
    pub fn get_magic_file_path(&self) -> PathBuf {
        if let Some(ref custom_path) = self.magic_file {
            custom_path.clone()
        } else {
            Self::default_magic_file_path()
        }
    }

    /// Create an EvaluationConfig from command-line arguments
    ///
    /// Uses the timeout value from --timeout-ms if provided, with validation
    /// performed during config creation. Other config values use defaults.
    pub fn to_evaluation_config(&self) -> libmagic_rs::EvaluationConfig {
        libmagic_rs::EvaluationConfig {
            timeout_ms: self.timeout_ms,
            ..Default::default()
        }
    }

    /// Magic file search candidates in priority order.
    ///
    /// OpenBSD-inspired order: text files/directories first, then compiled .mgc files.
    /// Text files are preferred because they are human-readable, easier to debug,
    /// and better suited for version control and development workflows.
    #[cfg(unix)]
    const MAGIC_FILE_CANDIDATES: &'static [&'static str] = &[
        // Text directories first (highest priority for debugging and compatibility)
        "/usr/share/file/magic/Magdir", // OpenBSD-style magic directory
        "/usr/share/file/magic",        // Text magic directory/file
        // Text files
        "/usr/share/misc/magic",       // BSD text magic file
        "/usr/local/share/misc/magic", // FreeBSD/Homebrew text
        "/etc/magic",                  // System-wide text magic file
        "/opt/local/share/file/magic", // MacPorts text
        // Binary .mgc files last (fallback for performance)
        "/usr/share/file/magic.mgc",       // Most common on Linux/macOS
        "/usr/local/share/misc/magic.mgc", // Homebrew/FreeBSD
        "/opt/local/share/file/magic.mgc", // MacPorts
        "/etc/magic.mgc",                  // Alternative location
        "/usr/share/misc/magic.mgc",       // BSD variant
    ];

    /// Returns the list of magic file candidates in search order.
    ///
    /// This is primarily exposed for testing purposes to verify the search order.
    #[cfg(unix)]
    pub fn magic_file_candidates() -> &'static [&'static str] {
        Self::MAGIC_FILE_CANDIDATES
    }

    /// Get the default magic file path for the current platform
    ///
    /// This follows an OpenBSD-inspired approach, prioritizing text-based magic files
    /// and directories over compiled binary `.mgc` files. Text files are preferred
    /// because they are human-readable, easier to debug, and better suited for
    /// version control and development workflows.
    ///
    /// The search order is:
    /// 1. Text directories (e.g., `/usr/share/file/magic/Magdir`)
    /// 2. Text files (e.g., `/usr/share/misc/magic`)
    /// 3. Binary `.mgc` files (e.g., `/usr/share/file/magic.mgc`)
    ///
    /// If a text file/directory is found, it is returned immediately.
    /// If only binary files exist, the first binary file found is used as fallback.
    fn default_magic_file_path() -> PathBuf {
        #[cfg(unix)]
        {
            let mut first_binary: Option<PathBuf> = None;

            for candidate in Self::MAGIC_FILE_CANDIDATES {
                let path = PathBuf::from(candidate);
                if !path.exists() {
                    continue;
                }

                if let Ok(format) = detect_format(&path) {
                    match format {
                        // Accept text files and directories immediately (OpenBSD-style preference)
                        MagicFileFormat::Text | MagicFileFormat::Directory => return path,
                        // Track first binary file as fallback, but continue searching for text
                        MagicFileFormat::Binary => {
                            if first_binary.is_none() {
                                first_binary = Some(path);
                            }
                        }
                    }
                }
            }

            // If we found a binary file but no text file, use the binary as fallback
            if let Some(binary_path) = first_binary {
                return binary_path;
            }

            // Fallback to repo-provided text magic file if present
            let repo_magic = PathBuf::from("missing.magic");
            if repo_magic.exists() {
                return repo_magic;
            }

            // Fallback to third_party binary magic file for compatibility hints
            let dev_magic = PathBuf::from("third_party/magic.mgc");
            if dev_magic.exists() {
                return dev_magic;
            }

            // CI/CD fallback
            if std::env::var("CI").is_ok() || std::env::var("GITHUB_ACTIONS").is_ok() {
                return PathBuf::from("third_party/magic.mgc");
            }

            // Default fallback
            PathBuf::from("/usr/share/file/magic.mgc")
        }
        #[cfg(windows)]
        {
            // Try Windows-specific locations
            if let Ok(appdata) = std::env::var("APPDATA") {
                let magic_path = PathBuf::from(appdata).join("Magic").join("magic");
                if magic_path.exists() {
                    return magic_path;
                }
            }

            // Fallback to third_party (common in CI/CD)
            PathBuf::from("third_party/magic.mgc")
        }
        #[cfg(not(any(unix, windows)))]
        {
            PathBuf::from("third_party/magic.mgc")
        }
    }
}

/// Output format for file type identification results
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// Human-readable text output (default)
    Text,
    /// Structured JSON output
    Json,
}

fn main() {
    let args = Args::parse();

    // Handle shell completion generation
    if let Some(shell) = args.generate_completion {
        let mut cmd = Args::command();
        clap_complete::generate(shell, &mut cmd, "rmagic", &mut std::io::stdout());
        return;
    }

    // Set up signal handler for graceful Ctrl+C handling
    let interrupted = Arc::new(AtomicBool::new(false));
    let interrupted_clone = Arc::clone(&interrupted);
    if let Err(e) = ctrlc::set_handler(move || {
        interrupted_clone.store(true, Ordering::SeqCst);
    }) {
        eprintln!("Warning: failed to set signal handler: {e}");
    }

    let exit_code = match run_analysis(&args, &interrupted) {
        Ok(()) => {
            if interrupted.load(Ordering::SeqCst) {
                eprintln!("Interrupted");
                130
            } else {
                0
            }
        }
        Err(e) => handle_error(e),
    };

    process::exit(exit_code);
}

/// Handle different types of errors and return appropriate exit codes
///
/// Exit codes follow Unix conventions:
/// - 0: Success
/// - 1: General error
/// - 2: Misuse of shell command (invalid arguments)
/// - 3: File not found or access denied
/// - 4: Magic file not found or invalid
/// - 5: Evaluation timeout or resource limits exceeded
fn handle_error(error: LibmagicError) -> i32 {
    match error {
        LibmagicError::IoError(ref io_err) => handle_io_error(io_err),
        LibmagicError::ParseError(ref parse_err) => handle_parse_error_new(parse_err),
        LibmagicError::EvaluationError(ref eval_err) => handle_evaluation_error_new(eval_err),
        LibmagicError::Timeout { timeout_ms } => handle_timeout_error(timeout_ms),
        LibmagicError::ConfigError { ref reason } => {
            eprintln!("Configuration error: {reason}");
            1
        }
        LibmagicError::FileError(ref msg) => {
            eprintln!("File error: {msg}");
            3
        }
    }
}

/// Handle I/O errors with specific error messages
fn handle_io_error(io_err: &std::io::Error) -> i32 {
    match io_err.kind() {
        std::io::ErrorKind::NotFound => {
            eprintln!(
                "Error: File not found\nThe specified file does not exist or cannot be accessed.\nPlease check the file path and try again."
            );
            3
        }
        std::io::ErrorKind::PermissionDenied => {
            eprintln!(
                "Error: Permission denied\nYou do not have permission to access the specified file.\nPlease check file permissions or run with appropriate privileges."
            );
            3
        }
        std::io::ErrorKind::InvalidInput => {
            eprintln!(
                "Error: Invalid input\nThe file path or arguments provided are invalid.\nPlease check your input and try again."
            );
            2
        }
        _ => {
            eprintln!(
                "Error: File access failed\nFailed to access file: {}\nPlease check the file path and permissions.",
                io_err
            );
            3
        }
    }
}

/// Handle parse errors with detailed information
fn handle_parse_error_new(parse_err: &libmagic_rs::ParseError) -> i32 {
    eprintln!(
        "Error: Magic file parse error\n{}\nThe magic file contains invalid syntax or formatting.\nPlease check the magic file format or try a different magic file.",
        parse_err
    );
    4
}

/// Handle evaluation errors
fn handle_evaluation_error_new(eval_err: &libmagic_rs::EvaluationError) -> i32 {
    eprintln!(
        "Error: Rule evaluation failed\n{}\nFailed to evaluate magic rules against the file.\nThe file may be corrupted or the magic rules may be incompatible.",
        eval_err
    );
    1
}

/// Handle timeout errors
fn handle_timeout_error(timeout_ms: u64) -> i32 {
    eprintln!(
        "Error: Evaluation timeout\nFile analysis timed out after {}ms\nThe file may be too large or complex to analyze within the time limit.\nTry using a simpler magic file or increasing the timeout limit.",
        timeout_ms
    );
    5
}

/// Load magic database from file
///
/// Handles magic file discovery, validation, and database loading.
/// Returns the loaded database or an error if loading fails.
fn load_magic_database(args: &Args) -> Result<MagicDatabase, LibmagicError> {
    let config = args.to_evaluation_config();

    if args.use_builtin {
        return MagicDatabase::with_builtin_rules_and_config(config);
    }

    // Get magic file path
    let magic_file_path = args.get_magic_file_path();

    // Validate magic file exists
    if !magic_file_path.exists() {
        return Err(LibmagicError::ParseError(
            libmagic_rs::ParseError::invalid_syntax(
                0,
                format!(
                    "Magic file not found at {}. Please ensure a magic file is available at one of the standard locations or specify a custom path with --magic-file.",
                    magic_file_path.display()
                ),
            ),
        ));
    }

    // Validate magic file format
    validate_magic_file(&magic_file_path)?;

    // Load and return database with custom config
    MagicDatabase::load_from_file_with_config(&magic_file_path, config)
}

/// Output analysis result based on format
///
/// Handles output formatting for both JSON and text formats.
/// For multiple files with JSON format, outputs JSON Lines (compact, one per line).
/// For single file with JSON format, outputs pretty-printed JSON.
///
/// Writes to the provided buffered writer. The caller is responsible for flushing.
fn output_result(
    writer: &mut impl Write,
    file_path: &Path,
    result: &libmagic_rs::EvaluationResult,
    args: &Args,
    is_multiple_files: bool,
) -> Result<(), LibmagicError> {
    match args.output_format() {
        OutputFormat::Json => {
            // Convert library result to output format (handles match conversion + tag enrichment)
            let output_result =
                libmagic_rs::output::EvaluationResult::from_library_result(result, file_path);

            // Use JSON Lines format for multiple files, pretty JSON for single file
            let json_result = if is_multiple_files {
                format_json_line_output(file_path, &output_result.matches)
            } else {
                format_json_output(&output_result.matches)
            };

            match json_result {
                Ok(json_str) => {
                    writeln!(writer, "{json_str}").map_err(LibmagicError::IoError)?;
                }
                Err(e) => {
                    return Err(LibmagicError::EvaluationError(
                        libmagic_rs::EvaluationError::unsupported_type(format!(
                            "Failed to serialize JSON: {e}"
                        )),
                    ));
                }
            }
        }
        OutputFormat::Text => {
            writeln!(writer, "{}: {}", file_path.display(), result.description)
                .map_err(LibmagicError::IoError)?;
        }
    }
    Ok(())
}

/// Process a single file with the magic database
///
/// Handles file validation, evaluation, and output.
/// Returns Ok(()) on success or an error if processing fails.
fn process_file(
    writer: &mut impl Write,
    file_or_stdin: &FileOrStdin,
    db: &MagicDatabase,
    args: &Args,
) -> Result<(), LibmagicError> {
    if file_or_stdin.is_stdin() {
        use std::io::Read;

        let max_string_length = db.config().max_string_length;
        let mut buffer = Vec::with_capacity(max_string_length + 1);

        let reader = file_or_stdin.clone().into_reader().map_err(|e| {
            LibmagicError::IoError(std::io::Error::other(format!("Failed to open stdin: {e}")))
        })?;

        // Read one extra byte to detect true truncation
        let mut limited_reader = reader.take((max_string_length + 1) as u64);
        limited_reader.read_to_end(&mut buffer).map_err(|e| {
            LibmagicError::IoError(std::io::Error::new(
                e.kind(),
                format!("Failed to read stdin: {e}"),
            ))
        })?;

        // Warn only if we actually read more than max_string_length bytes
        if buffer.len() > max_string_length {
            eprintln!(
                "Warning: stdin input truncated to {} bytes",
                max_string_length
            );
            // Truncate the buffer back to max_string_length
            buffer.truncate(max_string_length);
        }

        let result = db.evaluate_buffer(&buffer)?;
        let stdin_path = PathBuf::from("stdin");
        let is_multiple_files = args.files.len() > 1;
        output_result(writer, &stdin_path, &result, args, is_multiple_files)?;
        return Ok(());
    }

    // Extract file path from FileOrStdin
    // Use the filename() method to get the path
    let file_path = PathBuf::from(file_or_stdin.filename());

    // Validate file exists and is accessible
    validate_input_file(&file_path)?;

    // Evaluate file
    let result = db.evaluate_file(&file_path)?;

    // Output results based on format
    let is_multiple_files = args.files.len() > 1;
    output_result(writer, &file_path, &result, args, is_multiple_files)?;

    Ok(())
}

fn run_analysis(args: &Args, interrupted: &AtomicBool) -> Result<(), LibmagicError> {
    // Validate input arguments
    validate_arguments(args)?;

    // Load magic database once (shared across all files)
    let db = load_magic_database(args)?;

    let mut writer = BufWriter::new(std::io::stdout().lock());
    let mut first_error: Option<LibmagicError> = None;

    // Process each file sequentially
    for file_or_stdin in &args.files {
        // Check for Ctrl+C between files
        if interrupted.load(Ordering::SeqCst) {
            break;
        }

        match process_file(&mut writer, file_or_stdin, &db, args) {
            Ok(()) => {} // Success, continue
            Err(e) => {
                // Print error with filename context but continue processing other files
                eprintln!("Error processing {}: {}", file_or_stdin.filename(), e);
                // Store first error for strict mode
                if first_error.is_none() {
                    first_error = Some(e);
                }
            }
        }
    }

    // Flush buffered output
    writer.flush().map_err(LibmagicError::IoError)?;

    // Exit code behavior based on --strict flag
    if let Some(error) = first_error
        && args.strict
    {
        return Err(error);
    }

    Ok(())
}

/// Validate command-line arguments
fn validate_arguments(args: &Args) -> Result<(), LibmagicError> {
    // Check if files vector is empty
    if args.files.is_empty() {
        return Err(LibmagicError::IoError(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "At least one file must be specified",
        )));
    }

    // Validate custom magic file path if provided and not using built-in rules
    if !args.use_builtin
        && let Some(ref magic_file) = args.magic_file
    {
        let magic_str = magic_file.to_string_lossy();
        if magic_str.trim().is_empty() {
            return Err(LibmagicError::ParseError(
                libmagic_rs::ParseError::invalid_syntax(0, "Magic file path cannot be empty"),
            ));
        }
    }

    Ok(())
}

/// Validate that the input file exists and is accessible
fn validate_input_file(file_path: &Path) -> Result<(), LibmagicError> {
    if !file_path.exists() {
        return Err(LibmagicError::IoError(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("File not found: {}", file_path.display()),
        )));
    }

    // Check if it's a directory
    if file_path.is_dir() {
        return Err(LibmagicError::IoError(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!("Path is a directory, not a file: {}", file_path.display()),
        )));
    }

    // Try to access the file to check permissions
    match fs::File::open(file_path) {
        Ok(_) => Ok(()),
        Err(e) => Err(LibmagicError::IoError(e)),
    }
}

/// Validate that the magic file exists and is readable
fn validate_magic_file(magic_file_path: &Path) -> Result<(), LibmagicError> {
    if !magic_file_path.exists() {
        return Err(LibmagicError::ParseError(
            libmagic_rs::ParseError::invalid_syntax(
                0,
                format!("Magic file not found: {}", magic_file_path.display()),
            ),
        ));
    }

    // Directories are supported via load_magic_file
    if magic_file_path.is_dir() {
        return Ok(());
    }

    // Try to read the magic file to check permissions and basic format
    // Handle both text magic files and binary .mgc files
    match fs::read(magic_file_path) {
        Ok(content) => {
            // Basic validation - check if file is completely empty
            if content.is_empty() {
                return Err(LibmagicError::ParseError(
                    libmagic_rs::ParseError::invalid_syntax(0, "Magic file is empty"),
                ));
            }

            // Check if it's a binary magic file (.mgc) - these start with specific magic bytes
            if content.starts_with(b"\x0d\x0a\x1a\x0a") || content.len() > 100_000 {
                // Looks like a binary magic file, just check it's readable
                Ok(())
            } else {
                // Try to parse as text magic file
                match std::str::from_utf8(&content) {
                    Ok(text_content) => {
                        if text_content.trim().is_empty() {
                            return Err(LibmagicError::ParseError(
                                libmagic_rs::ParseError::invalid_syntax(0, "Magic file is empty"),
                            ));
                        }
                        Ok(())
                    }
                    Err(_) => {
                        // Not valid UTF-8, might be a binary file - allow it
                        Ok(())
                    }
                }
            }
        }
        Err(e) => Err(LibmagicError::IoError(e)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_basic_file_argument() {
        let args = Args::try_parse_from(["rmagic", "test.bin"]).unwrap();
        assert_eq!(args.files.len(), 1);
        assert_eq!(args.files[0].filename(), "test.bin");
        assert!(!args.json);
        assert!(!args.text);
        assert_eq!(args.output_format(), OutputFormat::Text);
        assert!(args.magic_file.is_none());
    }

    #[test]
    fn test_json_output_flag() {
        let args = Args::try_parse_from(["rmagic", "test.bin", "--json"]).unwrap();
        assert_eq!(args.files.len(), 1);
        assert_eq!(args.files[0].filename(), "test.bin");
        assert!(args.json);
        assert!(!args.text);
        assert_eq!(args.output_format(), OutputFormat::Json);
    }

    #[test]
    fn test_text_output_flag() {
        let args = Args::try_parse_from(["rmagic", "test.bin", "--text"]).unwrap();
        assert_eq!(args.files.len(), 1);
        assert_eq!(args.files[0].filename(), "test.bin");
        assert!(!args.json);
        assert!(args.text);
        assert_eq!(args.output_format(), OutputFormat::Text);
    }

    #[test]
    fn test_magic_file_argument() {
        let args =
            Args::try_parse_from(["rmagic", "test.bin", "--magic-file", "custom.magic"]).unwrap();
        assert_eq!(args.files.len(), 1);
        assert_eq!(args.files[0].filename(), "test.bin");
        assert_eq!(args.magic_file, Some(PathBuf::from("custom.magic")));
    }

    #[test]
    fn test_all_arguments_combined() {
        let args = Args::try_parse_from([
            "rmagic",
            "test.bin",
            "--json",
            "--magic-file",
            "custom.magic",
        ])
        .unwrap();
        assert_eq!(args.files.len(), 1);
        assert_eq!(args.files[0].filename(), "test.bin");
        assert!(args.json);
        assert!(!args.text);
        assert_eq!(args.output_format(), OutputFormat::Json);
        assert_eq!(args.magic_file, Some(PathBuf::from("custom.magic")));
    }

    #[test]
    fn test_json_text_conflict() {
        // Should fail because --json and --text conflict
        let result = Args::try_parse_from(["rmagic", "test.bin", "--json", "--text"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_missing_file_argument() {
        // Should fail because file argument is required
        let result = Args::try_parse_from(["rmagic"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_output_format_default() {
        let args = Args::try_parse_from(["rmagic", "test.bin"]).unwrap();
        assert_eq!(args.output_format(), OutputFormat::Text);
    }

    #[test]
    fn test_output_format_json() {
        let args = Args::try_parse_from(["rmagic", "test.bin", "--json"]).unwrap();
        assert_eq!(args.output_format(), OutputFormat::Json);
    }

    #[test]
    fn test_output_format_text_explicit() {
        let args = Args::try_parse_from(["rmagic", "test.bin", "--text"]).unwrap();
        assert_eq!(args.output_format(), OutputFormat::Text);
    }

    #[test]
    fn test_args_defaults() {
        let args = Args::try_parse_from(["rmagic", "test.bin"]).unwrap();
        assert!(!args.strict, "strict should default to false");
        assert!(!args.use_builtin, "use_builtin should default to false");
    }

    #[test]
    fn test_args_strict_flag() {
        let args = Args::try_parse_from(["rmagic", "--strict", "test.bin"]).unwrap();
        assert!(args.strict);
    }

    #[test]
    fn test_args_strict_with_json() {
        let args = Args::try_parse_from(["rmagic", "--strict", "--json", "test.bin"]).unwrap();
        assert!(args.strict);
        assert!(args.json);
        assert_eq!(args.output_format(), OutputFormat::Json);
    }

    #[test]
    fn test_use_builtin_flag_parsing() {
        let args = Args::try_parse_from(["rmagic", "--use-builtin", "test.bin"]).unwrap();
        assert!(args.use_builtin);
    }

    #[test]
    fn test_args_single_file_backwards_compatible() {
        let args = Args::try_parse_from(["rmagic", "test.bin"]).unwrap();
        assert_eq!(args.files.len(), 1);
        assert!(!args.strict);
    }

    #[test]
    fn test_args_multiple_files() {
        let args = Args::try_parse_from(["rmagic", "file1.bin", "file2.bin", "file3.bin"]).unwrap();
        assert_eq!(args.files.len(), 3);
    }

    #[test]
    fn test_args_stdin_detection() {
        let args = Args::try_parse_from(["rmagic", "-"]).unwrap();
        assert_eq!(args.files.len(), 1);
        assert!(args.files[0].is_stdin());
    }

    #[test]
    fn test_complex_file_paths() {
        let args = Args::try_parse_from(["rmagic", "/path/to/complex file.bin"]).unwrap();
        assert_eq!(args.files.len(), 1);
        assert_eq!(args.files[0].filename(), "/path/to/complex file.bin");
    }

    #[test]
    fn test_magic_file_with_spaces() {
        let args = Args::try_parse_from([
            "rmagic",
            "test.bin",
            "--magic-file",
            "/path/to/magic file.magic",
        ])
        .unwrap();
        assert_eq!(
            args.magic_file,
            Some(PathBuf::from("/path/to/magic file.magic"))
        );
    }

    #[test]
    fn test_get_magic_file_path_custom() {
        let args =
            Args::try_parse_from(["rmagic", "test.bin", "--magic-file", "custom.magic"]).unwrap();
        assert_eq!(args.get_magic_file_path(), PathBuf::from("custom.magic"));
    }

    #[test]
    fn test_get_magic_file_path_default() {
        let args = Args::try_parse_from(["rmagic", "test.bin"]).unwrap();
        let default_path = args.get_magic_file_path();

        // Test that we get a platform-appropriate default
        // The actual path depends on what magic files exist on the system
        #[cfg(unix)]
        {
            // Get the actual candidates from the exposed constant
            let candidates = Args::magic_file_candidates();

            // Build list of valid paths (candidates + fallbacks)
            let mut valid_paths: Vec<&str> = candidates.to_vec();
            valid_paths.push("missing.magic");
            valid_paths.push("third_party/magic.mgc");

            // Should be one of the standard Unix magic file locations or fallback
            assert!(
                valid_paths.contains(&default_path.to_str().unwrap()),
                "Got unexpected path: {:?}",
                default_path
            );
        }

        #[cfg(windows)]
        assert_eq!(default_path, PathBuf::from("third_party/magic.mgc"));

        #[cfg(not(any(unix, windows)))]
        assert_eq!(default_path, PathBuf::from("third_party/magic.mgc"));
    }

    #[test]
    fn test_default_magic_file_path() {
        let default_path = Args::default_magic_file_path();

        // Test that we get a platform-appropriate default
        // The actual path depends on what magic files exist on the system
        #[cfg(unix)]
        {
            // Get the actual candidates from the exposed constant
            let candidates = Args::magic_file_candidates();

            // Build list of valid paths (candidates + fallbacks)
            let mut valid_paths: Vec<&str> = candidates.to_vec();
            valid_paths.push("missing.magic");
            valid_paths.push("third_party/magic.mgc");

            // Should be one of the standard Unix magic file locations or fallback
            assert!(
                valid_paths.contains(&default_path.to_str().unwrap()),
                "Got unexpected path: {:?}",
                default_path
            );
        }

        #[cfg(windows)]
        assert_eq!(default_path, PathBuf::from("third_party/magic.mgc"));

        #[cfg(not(any(unix, windows)))]
        assert_eq!(default_path, PathBuf::from("third_party/magic.mgc"));
    }

    // Error handling tests
    #[test]
    fn test_handle_error_file_not_found() {
        let error = LibmagicError::IoError(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "File not found",
        ));
        let exit_code = handle_error(error);
        assert_eq!(exit_code, 3);
    }

    #[test]
    fn test_handle_error_permission_denied() {
        let error = LibmagicError::IoError(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "Permission denied",
        ));
        let exit_code = handle_error(error);
        assert_eq!(exit_code, 3);
    }

    #[test]
    fn test_handle_error_invalid_input() {
        let error = LibmagicError::IoError(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "Invalid input",
        ));
        let exit_code = handle_error(error);
        assert_eq!(exit_code, 2);
    }

    #[test]
    fn test_handle_error_parse_error() {
        let error = LibmagicError::ParseError(libmagic_rs::ParseError::invalid_syntax(
            42,
            "Invalid syntax",
        ));
        let exit_code = handle_error(error);
        assert_eq!(exit_code, 4);
    }

    #[test]
    fn test_handle_error_evaluation_error() {
        let error = LibmagicError::EvaluationError(libmagic_rs::EvaluationError::unsupported_type(
            "Evaluation failed",
        ));
        let exit_code = handle_error(error);
        assert_eq!(exit_code, 1);
    }

    #[test]
    fn test_handle_error_timeout() {
        let error = LibmagicError::Timeout { timeout_ms: 5000 };
        let exit_code = handle_error(error);
        assert_eq!(exit_code, 5);
    }

    #[test]
    fn test_validate_arguments_empty_files() {
        // Test with empty files vector
        let _args = Args::try_parse_from(["rmagic", "test.bin"]).unwrap();
        // Manually create args with empty files for this test
        let args_empty = Args {
            files: vec![],
            json: false,
            text: false,
            magic_file: None,
            strict: false,
            use_builtin: false,
            timeout_ms: None,
            generate_completion: None,
        };
        let result = validate_arguments(&args_empty);
        assert!(result.is_err());
        match result.unwrap_err() {
            LibmagicError::IoError(e) => {
                assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput);
                assert!(
                    e.to_string()
                        .contains("At least one file must be specified")
                );
            }
            _ => panic!("Expected IoError with InvalidInput"),
        }
    }

    #[test]
    fn test_validate_arguments_empty_magic_file() {
        let args = Args::try_parse_from(["rmagic", "test.bin"]).unwrap();
        let args_with_empty_magic = Args {
            files: args.files,
            json: false,
            text: false,
            magic_file: Some(PathBuf::from("")),
            strict: false,
            use_builtin: false,
            timeout_ms: None,
            generate_completion: None,
        };
        let result = validate_arguments(&args_with_empty_magic);
        assert!(result.is_err());
        match result.unwrap_err() {
            LibmagicError::ParseError(parse_err) => {
                let msg = parse_err.to_string();
                assert!(msg.contains("Magic file path cannot be empty"));
            }
            _ => panic!("Expected ParseError"),
        }
    }

    #[test]
    fn test_validate_arguments_valid() {
        let args = Args::try_parse_from(["rmagic", "test.bin"]).unwrap();
        let args_with_magic = Args {
            files: args.files,
            json: false,
            text: false,
            magic_file: Some(PathBuf::from("magic.db")),
            strict: false,
            use_builtin: false,
            timeout_ms: None,
            generate_completion: None,
        };
        let result = validate_arguments(&args_with_magic);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_input_file_not_found() {
        let result = validate_input_file(&PathBuf::from("nonexistent_file.bin"));
        assert!(result.is_err());
        match result.unwrap_err() {
            LibmagicError::IoError(e) => {
                assert_eq!(e.kind(), std::io::ErrorKind::NotFound);
                assert!(e.to_string().contains("File not found"));
            }
            _ => panic!("Expected IoError with NotFound"),
        }
    }

    #[test]
    fn test_validate_input_file_directory() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        let result = validate_input_file(temp_dir.path());
        assert!(result.is_err());
        match result.unwrap_err() {
            LibmagicError::IoError(e) => {
                assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput);
                assert!(e.to_string().contains("Path is a directory"));
            }
            _ => panic!("Expected IoError with InvalidInput"),
        }
    }

    #[test]
    fn test_validate_input_file_valid() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let temp_file = temp_dir.path().join("test_validate_file.bin");
        fs::write(&temp_file, b"test content").expect("Failed to write test file");

        let result = validate_input_file(&temp_file);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_magic_file_not_found() {
        let result = validate_magic_file(&PathBuf::from("nonexistent_magic.db"));
        assert!(result.is_err());
        match result.unwrap_err() {
            LibmagicError::ParseError(parse_err) => {
                let msg = parse_err.to_string();
                assert!(msg.contains("Magic file not found"));
            }
            _ => panic!("Expected ParseError"),
        }
    }

    #[test]
    fn test_validate_magic_file_directory() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        let result = validate_magic_file(temp_dir.path());
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_magic_file_empty() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let temp_file = temp_dir.path().join("test_empty_magic.db");
        fs::write(&temp_file, "").expect("Failed to write test file");

        let result = validate_magic_file(&temp_file);
        assert!(result.is_err());
        match result.unwrap_err() {
            LibmagicError::ParseError(parse_err) => {
                let msg = parse_err.to_string();
                assert!(msg.contains("Magic file is empty"));
            }
            _ => panic!("Expected ParseError"),
        }
    }

    #[test]
    fn test_validate_magic_file_whitespace_only() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let temp_file = temp_dir.path().join("test_whitespace_magic.db");
        fs::write(&temp_file, "   \n\t  \r\n  ").expect("Failed to write test file");

        let result = validate_magic_file(&temp_file);
        assert!(result.is_err());
        match result.unwrap_err() {
            LibmagicError::ParseError(parse_err) => {
                let msg = parse_err.to_string();
                assert!(msg.contains("Magic file is empty"));
            }
            _ => panic!("Expected ParseError"),
        }
    }

    #[test]
    fn test_validate_magic_file_valid() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let temp_file = temp_dir.path().join("test_valid_magic.db");
        fs::write(&temp_file, "# Magic file\n0 string test Test file")
            .expect("Failed to write test file");

        let result = validate_magic_file(&temp_file);
        assert!(result.is_ok());
    }

    /// Verify that text files/directories are prioritized over binary .mgc files
    /// in the magic file search order (OpenBSD-style approach)
    #[test]
    #[cfg(unix)]
    fn test_magic_file_search_order_text_first() {
        let candidates = Args::magic_file_candidates();

        // Find the index of the first binary (.mgc) candidate
        let first_binary_index = candidates
            .iter()
            .position(|c| c.ends_with(".mgc"))
            .expect("Should have at least one .mgc candidate");

        // Verify all candidates before the first binary are text (non-.mgc)
        for (i, candidate) in candidates.iter().enumerate() {
            if i < first_binary_index {
                assert!(
                    !candidate.ends_with(".mgc"),
                    "Candidate at index {} should be text (not .mgc): {}",
                    i,
                    candidate
                );
            }
        }

        // Verify all candidates from first_binary_index onwards are binary (.mgc)
        for (i, candidate) in candidates.iter().enumerate() {
            if i >= first_binary_index {
                assert!(
                    candidate.ends_with(".mgc"),
                    "Candidate at index {} should be binary (.mgc): {}",
                    i,
                    candidate
                );
            }
        }

        // Verify we have both text and binary candidates
        assert!(
            first_binary_index > 0,
            "Should have at least one text candidate before binary candidates"
        );
        assert!(
            first_binary_index < candidates.len(),
            "Should have at least one binary candidate"
        );
    }

    /// Verify that Magdir has the highest priority in the search order
    #[test]
    #[cfg(unix)]
    fn test_magic_file_search_order_magdir_priority() {
        let candidates = Args::magic_file_candidates();

        // Verify the first candidate is the Magdir directory
        assert_eq!(
            candidates[0], "/usr/share/file/magic/Magdir",
            "First candidate should be the Magdir directory"
        );
    }

    /// Verify the exact sequence of magic file candidates
    #[test]
    #[cfg(unix)]
    fn test_magic_file_candidates_exact_sequence() {
        let candidates = Args::magic_file_candidates();

        // Verify the exact expected sequence
        let expected = [
            // Text directories first
            "/usr/share/file/magic/Magdir",
            "/usr/share/file/magic",
            // Text files
            "/usr/share/misc/magic",
            "/usr/local/share/misc/magic",
            "/etc/magic",
            "/opt/local/share/file/magic",
            // Binary .mgc files last
            "/usr/share/file/magic.mgc",
            "/usr/local/share/misc/magic.mgc",
            "/opt/local/share/file/magic.mgc",
            "/etc/magic.mgc",
            "/usr/share/misc/magic.mgc",
        ];

        assert_eq!(
            candidates.len(),
            expected.len(),
            "Candidate list length mismatch"
        );

        for (i, (actual, expected)) in candidates.iter().zip(expected.iter()).enumerate() {
            assert_eq!(
                actual, expected,
                "Candidate mismatch at index {}: got '{}', expected '{}'",
                i, actual, expected
            );
        }
    }

    /// Verify behavior: first existing candidate is chosen in order
    /// This test uses a temporary directory to simulate the search behavior
    #[test]
    #[cfg(unix)]
    fn test_magic_file_search_selects_first_existing() {
        use std::io::Write;

        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create a text magic file
        let text_magic_path = temp_dir.path().join("text_magic");
        let mut text_file =
            fs::File::create(&text_magic_path).expect("Failed to create text magic file");
        writeln!(text_file, "# Text magic file").expect("Failed to write");
        writeln!(text_file, "0 string test Test file").expect("Failed to write");

        // Create a binary magic file (simulated with .mgc extension)
        let binary_magic_path = temp_dir.path().join("binary.mgc");
        // Write some bytes that look like a binary magic file header
        fs::write(&binary_magic_path, b"\x1c\x04\x1e\xf1test")
            .expect("Failed to create binary magic file");

        // Verify text file exists and is detected as text format
        assert!(text_magic_path.exists());
        let text_format = detect_format(&text_magic_path);
        assert!(
            matches!(text_format, Ok(MagicFileFormat::Text)),
            "Text magic file should be detected as Text format, got {:?}",
            text_format
        );

        // Verify binary file exists and is detected as binary format
        assert!(binary_magic_path.exists());
        let binary_format = detect_format(&binary_magic_path);
        assert!(
            matches!(binary_format, Ok(MagicFileFormat::Binary)),
            "Binary magic file should be detected as Binary format, got {:?}",
            binary_format
        );
    }

    /// Verify that binary files are selected as fallback when no text files exist
    #[test]
    #[cfg(unix)]
    fn test_magic_file_search_binary_fallback() {
        // This test verifies the logic by checking the candidate list structure
        let candidates = Args::magic_file_candidates();

        // Count text and binary candidates
        let text_count = candidates.iter().filter(|c| !c.ends_with(".mgc")).count();
        let binary_count = candidates.iter().filter(|c| c.ends_with(".mgc")).count();

        // Verify we have both types
        assert!(text_count > 0, "Should have text candidates");
        assert!(binary_count > 0, "Should have binary candidates");

        // Verify the structure allows binary fallback:
        // - Text candidates come first (they will be checked first)
        // - Binary candidates come after (they serve as fallback)
        // The search loop tracks first_binary and returns it if no text is found
        let first_text_idx = candidates
            .iter()
            .position(|c| !c.ends_with(".mgc"))
            .unwrap();
        let first_binary_idx = candidates.iter().position(|c| c.ends_with(".mgc")).unwrap();

        assert!(
            first_text_idx < first_binary_idx,
            "Text candidates should come before binary candidates"
        );
    }
}