cyme 3.0.1

List system USB buses and devices. A modern cross-platform lsusb
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
//! Where the magic happens for `cyme` binary!
#[cfg(feature = "watch")]
use clap::{Parser, Subcommand, ValueEnum};
#[cfg(not(feature = "watch"))]
use clap::{Parser, ValueEnum};
use colored::*;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use simple_logger::SimpleLogger;
use std::collections::HashSet;
use std::env;
use std::path::{Path, PathBuf};
use terminal_size::terminal_size;

use cyme::config::Config;
use cyme::display::{self, Block, DeviceBlocks};
use cyme::error::{Error, ErrorKind, Result};
use cyme::lsusb;
use cyme::profiler;
use cyme::types::VidPid;
use cyme::usb::BaseClass;
use std::str::FromStr;

#[cfg(feature = "watch")]
mod watch;

const MAX_VERBOSITY: u8 = 4;

#[derive(Parser, Debug, Default, Serialize, Deserialize)]
#[skip_serializing_none]
#[command(author, version, about, long_about = None, max_term_width=80)]
struct Args {
    /// Attempt to maintain compatibility with lsusb output
    #[arg(short, long, default_value_t = false)]
    lsusb: bool,

    /// Dump USB device hierarchy as a tree
    #[arg(short, long, default_value_t = false)]
    tree: bool,

    /// Show only devices with the specified vendor and product ID numbers (in hexadecimal) in format VID:[PID]
    #[arg(short = 'd', long, action = clap::ArgAction::Append, value_name = "VID:[PID]", aliases = &["filter-vidpid"])]
    vidpid: Vec<VidPid>,

    /// Show only devices with specified device and/or bus numbers (in decimal) in format [[bus]:][devnum]
    #[arg(short, long)]
    show: Option<String>,

    /// Selects which device lsusb will examine - supplied as Linux /dev/bus/usb/BBB/DDD style path
    #[arg(short = 'D', long)]
    device: Option<String>,

    /// Filter on string contained in name
    #[arg(long, action = clap::ArgAction::Append)]
    filter_name: Vec<String>,

    /// Filter on string contained in serial
    #[arg(long, action = clap::ArgAction::Append)]
    filter_serial: Vec<String>,

    /// Filter on USB class code
    #[arg(long, action = clap::ArgAction::Append)]
    filter_class: Vec<BaseClass>,

    /// Exclude devices matching KEY=VALUE criteria. KEY is one of: vidpid, name, serial, class, bus, number.
    /// Comma-separate multiple KEY=VALUE pairs to AND them (one occurrence). Repeat the arg to OR exclusions.
    #[arg(long, action = clap::ArgAction::Append, value_name = "KEY=VALUE")]
    filter_exclude: Vec<String>,

    /// Verbosity level (repeat provides count): 1 prints device configurations; 2 prints interfaces; 3 prints interface endpoints; 4 prints everything and more blocks
    #[arg(short = 'v', long, default_value_t = 0, action = clap::ArgAction::Count)]
    verbose: u8,

    /// Specify the blocks which will be displayed for each device and in what order. Supply arg multiple times or csv to specify multiple blocks.
    ///
    /// [default: bus-number,device-number,icon,vendor-id,product-id,name,serial,speed]
    #[arg(short, long, value_enum, value_delimiter = ',', num_args = 1..)]
    blocks: Option<Vec<display::DeviceBlocks>>,

    /// Specify the blocks which will be displayed for each bus and in what order. Supply arg multiple times or csv to specify multiple blocks.
    ///
    /// [default: port-path,name,host-controller,host-controller-device]
    #[arg(long, value_enum, value_delimiter = ',', num_args = 1..)]
    bus_blocks: Option<Vec<display::BusBlocks>>,

    /// Specify the blocks which will be displayed for each configuration and in what order. Supply arg multiple times or csv to specify multiple blocks.
    ///
    /// [default: number,icon-attributes,max-power,name]
    #[arg(long, value_enum, value_delimiter = ',', num_args = 1..)]
    config_blocks: Option<Vec<display::ConfigurationBlocks>>,

    /// Specify the blocks which will be displayed for each interface and in what order. Supply arg multiple times or csv to specify multiple blocks.
    ///
    /// [default: port-path,icon,alt-setting,base-class,sub-class]
    #[arg(long, value_enum, value_delimiter = ',', num_args = 1..)]
    interface_blocks: Option<Vec<display::InterfaceBlocks>>,

    /// Specify the blocks which will be displayed for each endpoint and in what order. Supply arg multiple times or csv to specify multiple blocks.
    ///
    /// [default: number,direction,transfer-type,sync-type,usage-type,max-packet-size]
    #[arg(long, value_enum, value_delimiter = ',', num_args = 1..)]
    endpoint_blocks: Option<Vec<display::EndpointBlocks>>,

    /// Operation to perform on the blocks supplied via --blocks, --bus-blocks, --config-blocks, --interface-blocks and --endpoint-blocks
    ///
    /// Default is 'add' for ease of use, 'new' is more explicit and was legacy behaviour (< 2.3.0)
    ///
    /// [default: add]
    #[arg(long, value_enum)]
    block_operation: Option<display::BlockOperation>,

    /// Print more blocks by default at each verbosity
    ///
    /// Only works if --blocks,--x--blocks not supplied as args or in config
    #[arg(short, long, default_value_t = false)]
    more: bool,

    /// Sort devices operation
    ///
    /// [default: device-number (flat), branch-position (tree)]
    #[arg(long, value_enum)]
    sort_devices: Option<display::Sort>,

    /// Sort devices by bus number. If using any sort-devices other than no-sort, this happens automatically
    #[arg(long, default_value_t = false)]
    sort_buses: bool,

    /// Group devices by value when listing
    ///
    /// [default: no-group]
    #[arg(long, value_enum)]
    group_devices: Option<display::Group>,

    /// Hide empty buses when printing tree; those with no devices.
    // these are a bit confusing, could make value enum with hide_empty, hide...
    #[arg(long, default_value_t = false)]
    hide_buses: bool,

    /// Hide empty hubs when printing tree; those with no devices. When listing will hide hubs regardless of whether empty of not
    #[arg(long, default_value_t = false)]
    hide_hubs: bool,

    /// Show root hubs when listing; Linux only
    #[arg(long, default_value_t = false)]
    list_root_hubs: bool,

    /// Show base16 values as base10 decimal instead
    #[arg(long, default_value_t = false)]
    decimal: bool,

    /// Disable padding to align blocks - will cause --headings to become maligned
    #[arg(long, default_value_t = false)]
    no_padding: bool,

    /// Output coloring mode
    ///
    /// [default: auto]
    #[arg(long, value_enum, aliases = &["colour"])]
    color: Option<display::ColorWhen>,

    /// Disable coloured output, can also use NO_COLOR environment variable
    #[arg(long, default_value_t = false, hide = true, aliases = &["no_colour"])]
    no_color: bool,

    /// Output character encoding
    ///
    /// [default: glyphs]
    #[arg(long, value_enum)]
    encoding: Option<display::Encoding>,

    /// Disables icons and utf-8 characters
    #[arg(long, default_value_t = false, hide = true)]
    ascii: bool,

    /// Disables all Block icons by not using any IconTheme. Providing custom XxxxBlocks without any icons is a nicer way to do this
    #[arg(long, default_value_t = false, hide = true)]
    no_icons: bool,

    /// When to print icon blocks
    ///
    /// [default: auto]
    #[arg(long, value_enum, aliases = &["icon_when"])]
    icon: Option<display::IconWhen>,

    /// Show block headings
    #[arg(long, default_value_t = false)]
    headings: bool,

    /// Output as json format after sorting, filters and tree settings are applied; without -tree will be flattened dump of devices
    #[arg(long, default_value_t = false, overrides_with = "lsusb")]
    json: bool,

    /// Read from json output rather than profiling system
    #[arg(long)]
    from_json: Option<PathBuf>,

    /// Force pure libusb profiler on macOS rather than combining system_profiler output
    ///
    /// Has no effect on other platforms or when using nusb
    #[arg(short = 'F', long, default_value_t = false)]
    force_libusb: bool,

    /// Path to user config file to use for custom icons, colours and default settings
    #[arg(short = 'c', long)]
    config: Option<PathBuf>,

    /// Filter devices after profiling rather than during.
    ///
    /// This is slower but can be used as a fallback if the optimized profiling is causing issues.
    #[arg(long, default_value_t = false, hide = true)]
    filter_post: bool,

    /// Turn debugging information on. Alternatively can use RUST_LOG env: INFO, DEBUG, TRACE
    #[arg(short = 'z', long, action = clap::ArgAction::Count)]
    // short -d taken by lsusb compat vid:pid
    debug: u8,

    /// Mask serial numbers with '*' or random chars
    #[arg(long)]
    mask_serials: Option<display::MaskSerial>,

    /// Apply muted colour to hub device lines instead of per-block colours
    #[arg(long, default_value_t = false)]
    mute_hubs: bool,

    /// Generate cli completions and man page
    #[cfg(feature = "cli_generate")]
    #[arg(long, hide = true, exclusive = true)]
    gen: bool,

    /// Use the system_profiler command on macOS to get USB data
    ///
    /// If not using nusb this is the default for macOS, merging with libusb data for verbose output. nusb uses IOKit directly so does not use system_profiler by default
    #[arg(long, default_value_t = false)]
    system_profiler: bool,

    /// Watch sub-command
    #[cfg(feature = "watch")]
    #[command(subcommand)]
    command: Option<SubCommand>,
}

#[cfg(feature = "watch")]
#[derive(Subcommand, Debug, Serialize, Deserialize)]
enum SubCommand {
    /// Watch for USB devices being connected and disconnected
    Watch,
}

/// Print in bold red and exit with error
macro_rules! eprintexit {
    ($error:expr) => {
        // `stringify!` will convert the expression *as it is* into a string.
        eprintln!(
            "{}\n{}",
            "cyme encountered a runtime error:".bold().red(),
            $error.to_string().bold().red()
        );
        std::process::exit(1);
    };
}

/// Print in bold orange warning and log
#[allow(unused_macros)]
macro_rules! wprintln {
    ($error:expr) => {
        // `stringify!` will convert the expression *as it is* into a string.
        println!("{}", $error.to_string().bold().yellow());
        log::warn!($error)
    };
}

/// Merges non-Option Config with passed `Args`
///
/// Args will override Config if set
fn merge_config(c: &mut Config, a: &Args) {
    c.lsusb |= a.lsusb;
    c.tree |= a.tree;
    c.more |= a.more;
    c.hide_buses |= a.hide_buses;
    c.hide_hubs |= a.hide_hubs;
    c.list_root_hubs |= a.list_root_hubs;
    c.decimal |= a.decimal;
    c.no_padding |= a.no_padding;
    c.ascii |= a.ascii;
    c.headings |= a.headings;
    c.force_libusb |= a.force_libusb;
    c.no_icons |= a.no_icons;
    c.no_color |= a.no_color;
    c.json |= a.json;
    // override group devices if passed
    if a.group_devices.is_some() {
        c.group_devices = a.group_devices;
    }
    if a.encoding.is_some() {
        c.encoding = a.encoding;
    }
    if a.sort_devices.is_some() {
        c.sort_devices = a.sort_devices;
    }
    if a.icon.is_some() {
        c.icon_when = a.icon;
    }
    if a.color.is_some() {
        c.color_when = a.color;
    }
    if a.mask_serials.is_some() {
        c.mask_serials = a.mask_serials;
    }
    if a.block_operation.is_some() {
        c.block_operation = a.block_operation;
    }
    c.mute_hubs |= a.mute_hubs;
    c.sort_buses |= a.sort_buses;
    // take larger debug level
    c.verbose = c.verbose.max(a.verbose);
}

/// Parse the show Option<bus>:device lsusb format
fn parse_show(s: &str) -> Result<(Option<u8>, Option<u8>)> {
    if s.contains(':') {
        let split: Vec<&str> = s.split(':').collect();
        let bus: Option<u8> = split
            .first()
            .filter(|v| !v.is_empty())
            .map_or(Ok(None), |v| {
                v.parse::<u8>()
                    .map(Some)
                    .map_err(|e| Error::new(ErrorKind::Parsing, &e.to_string()))
            })?;
        let device = split
            .last()
            .filter(|v| !v.is_empty())
            .map_or(Ok(None), |v| {
                v.parse::<u8>()
                    .map(Some)
                    .map_err(|e| Error::new(ErrorKind::Parsing, &e.to_string()))
            })?;

        Ok((bus, device))
    } else {
        let device: Option<u8> = s
            .trim()
            .parse::<u8>()
            .map(Some)
            .map_err(|e| Error::new(ErrorKind::Parsing, &e.to_string()))?;

        Ok((None, device))
    }
}

/// Parse a --filter-exclude KEY=VALUE[,KEY=VALUE...] string into a Filter
fn parse_exclude(s: &str) -> Result<profiler::Filter> {
    let mut f = profiler::Filter::default();
    for part in s.split(',') {
        let (key, value) = part.split_once('=').ok_or_else(|| {
            Error::new(
                ErrorKind::InvalidArg,
                &format!("Expected KEY=VALUE format in '--filter-exclude {s}'"),
            )
        })?;
        match key.trim() {
            "vidpid" => {
                let vp = VidPid::from_str(value.trim())?;
                f.vid = vp.0;
                f.pid = vp.1;
            }
            "name" => f.name = Some(value.to_string()),
            "serial" => f.serial = Some(value.to_string()),
            "class" => {
                f.class = Some(
                    BaseClass::from_str(value.trim(), true).map_err(|e| {
                        Error::new(ErrorKind::Parsing, &e.to_string())
                    })?,
                )
            }
            "bus" => {
                f.bus = Some(value.trim().parse::<u8>().map_err(|e| {
                    Error::new(ErrorKind::Parsing, &e.to_string())
                })?)
            }
            "number" => {
                f.number = Some(value.trim().parse::<u8>().map_err(|e| {
                    Error::new(ErrorKind::Parsing, &e.to_string())
                })?)
            }
            _ => {
                return Err(Error::new(
                    ErrorKind::InvalidArg,
                    &format!("Unknown exclude key '{key}'; expected one of: vidpid, name, serial, class, bus, number"),
                ))
            }
        }
    }
    Ok(f)
}

/// Parse devpath supplied by --device into a show format
///
/// Could be a regex match r"^[\/|\w+\/]+(?'bus'\d{3})\/(?'devno'\d{3})$" but this saves another crate
fn parse_devpath(s: &str) -> Result<(Option<u8>, Option<u8>)> {
    if s.contains('/') {
        let split: Vec<&str> = s.split('/').collect();
        // second to last
        let bus: Option<u8> = split.get(split.len() - 2).map_or(Ok(None), |v| {
            v.parse::<u8>()
                .map(Some)
                .map_err(|e| Error::new(ErrorKind::Parsing, &e.to_string()))
        })?;
        // last
        let device = split.last().map_or(Ok(None), |v| {
            v.parse::<u8>()
                .map(Some)
                .map_err(|e| Error::new(ErrorKind::Parsing, &e.to_string()))
        })?;

        Ok((bus, device))
    } else {
        Err(Error::new(
            ErrorKind::InvalidArg,
            &format!("Invalid device path {s}"),
        ))
    }
}

#[allow(unused_variables)]
fn is_watch(args: &Args) -> bool {
    #[cfg(feature = "watch")]
    {
        matches!(args.command, Some(SubCommand::Watch))
    }
    #[cfg(not(feature = "watch"))]
    {
        false
    }
}

/// macOS can use system_profiler to get USB data and merge with libusb so separate function
#[cfg(target_os = "macos")]
fn get_system_profile_macos(
    config: &Config,
    args: &Args,
    filter: Option<profiler::DeviceFilter>,
) -> Result<profiler::SystemProfile> {
    // if requested or only have libusb, use system_profiler and merge with libusb
    if args.system_profiler || !cfg!(feature = "nusb") {
        if !config.force_libusb
            && args.device.is_none() // device path requires extra
                && args.filter_class.is_empty() // class filter requires extra
                && !((config.tree && config.lsusb) || config.verbose > 0 || config.more)
        {
            profiler::macos::get_spusb().map_or_else(
                |e| {
                    // For non-zero return, report but continue in this case
                    if e.kind() == ErrorKind::SystemProfiler {
                        eprintln!("Failed to run 'system_profiler -json SPUSBDataType', fallback to cyme profiler; Error({e})");
                        get_system_profile(config, args, filter)
                    } else {
                        Err(e)
                    }
                },
                Ok,
            )
        } else if !config.force_libusb {
            if cfg!(feature = "libusb") {
                log::warn!("Merging macOS system_profiler output with libusb for verbose data. Apple internal devices will not be obtained");
            }
            let depth = if config.verbose >= 2
                || (config.json && config.verbose >= 1)
                || (config.lsusb && (args.device.is_some() || config.tree || config.verbose > 0))
                || is_watch(args)
            // watch needs full data to be able to show changes properly since only new devices are re-profiled
            {
                profiler::ProfileDepth::Full
            } else if config.verbose == 1
                || !args.filter_class.is_empty()
                || config.json
                || config.more
            {
                profiler::ProfileDepth::Standard
            } else {
                profiler::ProfileDepth::Identity
            };

            let options = profiler::ProfilerOptions {
                filter,
                depth,
                tree: config.tree,
            };
            profiler::macos::get_spusb_with_options(&options).map_or_else(
                |e| {
                    // For non-zero return, report but continue in this case
                    if e.kind() == ErrorKind::SystemProfiler {
                        eprintln!("Failed to run 'system_profiler -json SPUSBDataType', fallback to cyme profiler; Error({e})");
                        get_system_profile(config, args, options.filter)
                    } else {
                        Err(e)
                    }
                },
                Ok,
            )
        } else {
            get_system_profile(config, args, filter)
        }
    } else {
        get_system_profile(config, args, filter)
    }
}

/// Detects and switches between verbose profiler (extra) and normal profiler
fn get_system_profile(
    config: &Config,
    args: &Args,
    filter: Option<profiler::DeviceFilter>,
) -> Result<profiler::SystemProfile> {
    let depth = if config.verbose >= 2
        || (config.json && config.verbose >= 1)
        || (config.lsusb && (args.device.is_some() || config.tree || config.verbose > 0))
        || is_watch(args)
    // watch needs full data to be able to show changes properly since only new devices are re-profiled
    {
        profiler::ProfileDepth::Full
    } else if config.verbose == 1 || !args.filter_class.is_empty() || config.json || config.more {
        profiler::ProfileDepth::Standard
    } else {
        profiler::ProfileDepth::Identity
    };

    let options = profiler::ProfilerOptions {
        filter,
        depth,
        tree: config.tree,
    };
    profiler::get_spusb_with_options(&options)
}

fn print_lsusb(
    sp_usb: &profiler::SystemProfile,
    device: &Option<String>,
    settings: &display::PrintSettings,
) -> Result<()> {
    // device specific overrides tree on lsusb
    if settings.tree && device.is_none() {
        if !cfg!(target_os = "linux") {
            log::warn!("Most of the data in a lsusb style tree is applicable to Linux only!");
        }
        lsusb::print_tree(sp_usb, settings)
    } else {
        // can't print verbose if not using libusb
        if !(cfg!(feature = "libusb") || cfg!(feature = "nusb"))
            && (settings.verbosity > 0 || device.is_some())
        {
            return Err(Error::new(ErrorKind::Unsupported, "nusb or libusb feature is required to do this, install with `cargo install --features nusb/libusb`"));
        }

        let devices = sp_usb.flattened_devices();
        // even though we filtered using filter.show and using prepare, keep this here because it will match the exact Linux dev path and exit error if it doesn't match like lsusb
        if let Some(dev_path) = &device {
            lsusb::dump_one_device(&devices, dev_path)?
        } else {
            lsusb::print(&devices, settings.verbosity > 0);
        }
    };

    Ok(())
}

/// Generates extra CLI information for packaging
#[cfg(feature = "cli_generate")]
#[cold]
fn print_man() -> Result<()> {
    use clap::CommandFactory;
    use clap_complete::generate_to;
    use clap_complete::shells::*;
    use std::fs;
    use std::path::PathBuf;

    let outdir = std::env::var_os("BUILD_SCRIPT_DIR")
        .or_else(|| std::env::var_os("OUT_DIR"))
        .unwrap_or_else(|| "./doc".into());
    fs::create_dir_all(&outdir)?;
    println!("Generating CLI info to {outdir:?}");

    let mut app = Args::command();

    // completions
    let bin_name = app.get_name().to_string();
    generate_to(Bash, &mut app, &bin_name, &outdir).expect("Failed to generate Bash completions");
    generate_to(Fish, &mut app, &bin_name, &outdir).expect("Failed to generate Fish completions");
    generate_to(Zsh, &mut app, &bin_name, &outdir).expect("Failed to generate Zsh completions");
    generate_to(PowerShell, &mut app, &bin_name, &outdir)
        .expect("Failed to generate PowerShell completions");

    // man page
    let man = clap_mangen::Man::new(app);
    let mut buffer: Vec<u8> = Default::default();
    man.render(&mut buffer)?;

    std::fs::write(PathBuf::from(&outdir).join("cyme.1"), buffer)?;

    // example config
    std::fs::write(
        PathBuf::from(&outdir).join("cyme_example_config.json"),
        serde_json::to_string_pretty(&Config::example())?,
    )?;

    // example config with filter
    std::fs::write(
        PathBuf::from(&outdir).join("cyme_example_filter_config.json"),
        serde_json::to_string_pretty(&Config::example_with_filter())?,
    )?;

    Ok(())
}

fn load_config<P: AsRef<Path>>(path: Option<P>) -> Result<Config> {
    if let Some(p) = path {
        let config = Config::from_file(p);
        log::info!("Using user config {config:?}");
        config
    } else {
        Config::sys()
    }
}

/// Set log level
pub fn set_log_level(debug: u8) -> Result<()> {
    let mut builder = SimpleLogger::new();
    let mut env_levels: HashSet<(String, log::LevelFilter)> = HashSet::new();

    let global_level = match debug {
        0 => {
            env_levels.insert(("udevrs".to_string(), log::LevelFilter::Off));
            env_levels.insert(("nusb".to_string(), log::LevelFilter::Off));
            log::LevelFilter::Error
        }
        1 => {
            env_levels.insert(("udevrs".to_string(), log::LevelFilter::Warn));
            env_levels.insert(("nusb".to_string(), log::LevelFilter::Warn));
            env_levels.insert(("cyme".to_string(), log::LevelFilter::Info));
            log::LevelFilter::Error
        }
        2 => {
            env_levels.insert(("udevrs".to_string(), log::LevelFilter::Info));
            env_levels.insert(("nusb".to_string(), log::LevelFilter::Info));
            env_levels.insert(("cyme".to_string(), log::LevelFilter::Debug));
            log::LevelFilter::Error
        }
        3 => {
            env_levels.insert(("udevrs".to_string(), log::LevelFilter::Debug));
            env_levels.insert(("nusb".to_string(), log::LevelFilter::Debug));
            env_levels.insert(("cyme".to_string(), log::LevelFilter::Trace));
            log::LevelFilter::Error
        }
        _ => log::LevelFilter::Trace,
    };

    if let Ok(rust_log) = std::env::var("RUST_LOG") {
        rust_log
            .split(',')
            .filter(|s| !s.is_empty())
            .map(|s| {
                let mut split = s.split('=');
                let k = split.next().unwrap();
                let v = split.next().and_then(|s| s.parse().ok());
                (k.to_string(), v)
            })
            .filter(|(_, v)| v.is_some())
            .map(|(k, v)| (k, v.unwrap()))
            .for_each(|(k, v)| {
                env_levels.replace((k, v));
            });
    }

    for (k, v) in env_levels {
        builder = builder.with_module_level(&k, v);
    }

    builder
        .with_utc_timestamps()
        .with_level(global_level)
        .env()
        .init()
        .map_err(|e| {
            Error::new(
                ErrorKind::Other("logger"),
                &format!("Failed to set log level: {e}"),
            )
        })?;

    #[cfg(feature = "libusb")]
    profiler::libusb::set_log_level(debug);

    Ok(())
}

/// Merge with arg blocks with config blocks (or default if None) depending on BlockOperation
fn merge_blocks(config: &Config, args: &Args, settings: &mut display::PrintSettings) -> Result<()> {
    let block_op = config.block_operation.unwrap_or_default();
    if let Some(blocks) = &args.blocks {
        let mut device_blocks = config.blocks.to_owned().unwrap_or(if settings.more {
            DeviceBlocks::default_blocks(true)
        } else if settings.tree {
            DeviceBlocks::default_device_tree_blocks()
        } else {
            DeviceBlocks::default_blocks(false)
        });
        block_op.run(&mut device_blocks, blocks)?;
        settings.device_blocks = Some(device_blocks);
    }

    if let Some(blocks) = &args.bus_blocks {
        settings.bus_blocks =
            Some(block_op.new_or_op(config.bus_blocks.to_owned(), blocks, settings.more)?);
    }

    if let Some(blocks) = &args.config_blocks {
        settings.config_blocks =
            Some(block_op.new_or_op(settings.config_blocks.to_owned(), blocks, settings.more)?);
    }

    if let Some(blocks) = &args.interface_blocks {
        settings.interface_blocks = Some(block_op.new_or_op(
            settings.interface_blocks.to_owned(),
            blocks,
            settings.more,
        )?);
    }

    if let Some(blocks) = &args.endpoint_blocks {
        settings.endpoint_blocks =
            Some(block_op.new_or_op(settings.endpoint_blocks.to_owned(), blocks, settings.more)?);
    }

    Ok(())
}

/// Build inclusion filters via cross-product of multi-value args.
/// Each unique combination of (vidpid, name, serial, class) becomes one Filter.
/// bus/number are always AND'd into every filter (single-value).
fn build_inclusion_filters(
    vidpids: &[VidPid],
    bus: Option<u8>,
    number: Option<u8>,
    names: &[String],
    serials: &[String],
    classes: &[BaseClass],
) -> Vec<profiler::Filter> {
    // Empty slice → one None sentinel so the cross-product iterates at least once;
    // an absent dimension means "no constraint on that field".
    let vids: Vec<Option<VidPid>> = if vidpids.is_empty() {
        vec![None]
    } else {
        vidpids.iter().copied().map(Some).collect()
    };
    let names: Vec<Option<&String>> = if names.is_empty() {
        vec![None]
    } else {
        names.iter().map(Some).collect()
    };
    let serials: Vec<Option<&String>> = if serials.is_empty() {
        vec![None]
    } else {
        serials.iter().map(Some).collect()
    };
    let classes: Vec<Option<BaseClass>> = if classes.is_empty() {
        vec![None]
    } else {
        classes.iter().copied().map(Some).collect()
    };

    let mut filters = Vec::new();
    for vid in &vids {
        for name in &names {
            for serial in &serials {
                for class in &classes {
                    let (vid_val, pid_val) = vid.map_or((None, None), |v| (v.0, v.1));
                    filters.push(profiler::Filter {
                        vid: vid_val,
                        pid: pid_val,
                        bus,
                        number,
                        name: name.map(|n| n.to_owned()),
                        serial: serial.map(|s| s.to_owned()),
                        class: *class,
                        case_sensitive: false,
                    });
                }
            }
        }
    }
    filters
}

fn cyme() -> Result<()> {
    let mut args = Args::parse();

    #[cfg(feature = "cli_generate")]
    if args.gen {
        print_man()?;
        std::process::exit(0);
    }

    // set the module debug level, will also check env if args.debug == 0
    set_log_level(args.debug)?;

    let mut config = load_config(args.config.as_deref())?;

    // add any config ENV override
    if config.print_non_critical_profiler_stderr {
        std::env::set_var("CYME_PRINT_NON_CRITICAL_PROFILER_STDERR", "1");
    }

    // legacy arg, hidden but still support with new format
    if args.ascii {
        args.encoding = Some(display::Encoding::Ascii);
    }

    // legacy arg, hidden but still support with new format
    if args.no_color {
        args.color = Some(display::ColorWhen::Never);
    }

    if args.verbose >= MAX_VERBOSITY {
        args.more = true;
    }

    merge_config(&mut config, &args);

    // set the output colouring mode
    // display::print will check based on print settings but let's ensure
    match config.color_when {
        Some(display::ColorWhen::Always) => {
            env::set_var("NO_COLOR", "0");
            colored::control::set_override(true);
            config.no_color = false;
        }
        Some(display::ColorWhen::Never) => {
            // set env to be sure too
            env::set_var("NO_COLOR", "1");
            colored::control::set_override(false);
            config.no_color = true;
        }
        _ => (),
    };

    let filter = {
        // args.vidpid is already Vec<VidPid> — parsed and validated by clap
        let vidpids = &args.vidpid;

        // Parse show/device into bus/number (single-value)
        let (bus, number) = if let Some(devpath) = &args.device {
            parse_devpath(devpath.as_str()).map_err(|e| {
                Error::new(
                    ErrorKind::InvalidArg,
                    &format!(
                        "Failed to parse devpath '{devpath}', should end with 'BUS/DEVNO'; Error({e})"
                    ),
                )
            })?
        } else if let Some(show) = &args.show {
            parse_show(show.as_str()).map_err(|e| {
                Error::new(
                    ErrorKind::InvalidArg,
                    &format!("Failed to parse show parameter '{show}'; Error({e})"),
                )
            })?
        } else {
            (None, None)
        };

        // Parse exclusion filters
        let exclude_filters: Vec<profiler::Filter> = args
            .filter_exclude
            .iter()
            .map(|s| {
                parse_exclude(s.as_str()).map_err(|e| {
                    Error::new(
                        ErrorKind::InvalidArg,
                        &format!("Failed to parse filter-exclude '{s}'; Error({e})"),
                    )
                })
            })
            .collect::<Result<_>>()?;

        let include_root_hubs = config.lsusb
            || config.json
            || config.list_root_hubs
            || args.device.is_some()
            || args.show.is_some();

        let has_inclusion_criteria = !vidpids.is_empty()
            || !args.filter_name.is_empty()
            || !args.filter_serial.is_empty()
            || !args.filter_class.is_empty()
            || bus.is_some()
            || number.is_some();
        // Convert config FilterEntry structs to Filter (validated at config load time)
        let config_include: Vec<profiler::Filter> = config
            .filter_include
            .iter()
            .cloned()
            .map(profiler::Filter::from)
            .collect();
        let config_exclude: Vec<profiler::Filter> = config
            .filter_exclude
            .iter()
            .cloned()
            .map(profiler::Filter::from)
            .collect();

        let has_any_criteria = has_inclusion_criteria
            || !exclude_filters.is_empty()
            || config.hide_hubs
            || config.hide_buses
            || !config_include.is_empty()
            || !config_exclude.is_empty();

        if has_any_criteria || cfg!(target_os = "linux") {
            let mut f = profiler::DeviceFilter::default();

            // Config filters first, then CLI (both OR'd together)
            f.filters.extend(config_include);
            if has_inclusion_criteria {
                f.filters.extend(build_inclusion_filters(
                    vidpids,
                    bus,
                    number,
                    &args.filter_name,
                    &args.filter_serial,
                    &args.filter_class,
                ));
            }
            f.exclude_filters.extend(config_exclude);
            f.exclude_filters.extend(exclude_filters);

            f.exclude_empty_bus = config.hide_buses;
            f.exclude_empty_hub = config.hide_hubs;
            f.include_root_hubs = include_root_hubs;

            if !f.filters.is_empty() || !f.exclude_filters.is_empty() {
                log::info!(
                    "Device filter active: {} inclusion filter(s), {} exclusion filter(s)",
                    f.filters.len(),
                    f.exclude_filters.len()
                );
            }

            Some(f)
        } else {
            None
        }
    };

    let mut spusb = if let Some(file_path) = args.from_json.clone() {
        match profiler::read_json_dump(&file_path) {
            Ok(s) => s,
            Err(e) => {
                log::warn!(
                    "Failed to read json dump, attempting as flattened with phony bus: Error({e})"
                );
                profiler::read_flat_json_to_phony_bus(&file_path)?
            }
        }
    } else {
        #[cfg(target_os = "macos")]
        {
            get_system_profile_macos(
                &config,
                &args,
                if args.filter_post {
                    None
                } else {
                    filter.clone()
                },
            )?
        }

        #[cfg(not(target_os = "macos"))]
        {
            get_system_profile(
                &config,
                &args,
                if args.filter_post {
                    None
                } else {
                    filter.clone()
                },
            )?
        }
    };

    // create print settings from config - merged with arg flags above
    let mut settings = config.print_settings();
    settings.terminal_size = terminal_size().map(|(w, h)| (w.0, h.0));
    merge_blocks(&config, &args, &mut settings)?;

    log::trace!("Returned system_profiler data\n\r{spusb:#?}");

    #[cfg(feature = "watch")]
    if matches!(args.command, Some(SubCommand::Watch)) {
        // pass spusb to watch so that it can be based on from_json
        // note: profiler will have been forced to full depth (get_system..) for watch to be able to show changes properly since only new devices are re-profiled based on supplied options to stream
        // ideally watch would generate own spusb or trigger when print options change but this works..
        if settings.json {
            watch::watch_usb_devices_json(spusb, filter, settings)?;
        } else {
            watch::watch_usb_devices(spusb, filter, settings, config)?;
        }
        return Ok(());
    }

    display::prepare(&mut spusb, filter.as_ref(), &settings);

    if config.lsusb {
        print_lsusb(&spusb, &args.device, &settings)?;
    } else {
        // check and report if was looking for args.device
        #[allow(clippy::unnecessary_unwrap)]
        if args.device.is_some() && spusb.is_empty() {
            return Err(Error::new(
                ErrorKind::NotFound,
                &format!("Unable to find device at {:?}", args.device.unwrap()),
            ));
        }
        display::print(&spusb, &settings);
    }

    Ok(())
}

fn main() {
    cyme().unwrap_or_else(|e| {
        eprintexit!(e);
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[ignore]
    #[test]
    fn test_output_args() {
        let mut args = Args {
            ..Default::default()
        };
        args.blocks = Some(vec![display::DeviceBlocks::BusNumber]);
        println!("{}", serde_json::to_string_pretty(&args).unwrap());
    }

    #[test]
    fn test_parse_show() {
        assert_eq!(parse_show("1").unwrap(), (None, Some(1)));
        assert_eq!(parse_show("1:124").unwrap(), (Some(1), Some(124)));
        assert_eq!(parse_show("1:").unwrap(), (Some(1), None));
        // too big
        assert!(parse_show("55233:12323").is_err());
        assert!(parse_show("dfg:sdfd").is_err());
    }

    #[test]
    fn test_parse_devpath() {
        assert_eq!(
            parse_devpath("/dev/bus/usb/001/003").unwrap(),
            (Some(1), Some(3))
        );
        assert_eq!(
            parse_devpath("/dev/bus/usb/004/003").unwrap(),
            (Some(4), Some(3))
        );
        assert_eq!(
            parse_devpath("/dev/bus/usb/004/3").unwrap(),
            (Some(4), Some(3))
        );
        assert_eq!(parse_devpath("004/3").unwrap(), (Some(4), Some(3)));
        assert!(parse_devpath("004/").is_err());
        assert!(parse_devpath("sas/ssas").is_err());
    }
}