conan2 0.1.9

Pulls the C/C++ library linking flags from Conan dependencies
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
//! # conan2-rs
//!
//! ## Introduction
//!
//! `conan2-rs` is a Cargo build script wrapper of the Conan C/C++ package manager
//! (version 2.0 only).
//!
//! It automatically pulls the C/C++ library linking flags from Conan dependencies
//! and passes them to `rustc`.
//!
//! ## Adding C/C++ dependencies using Conan
//!
//! The simplest way to add C/C++ dependencies to a Rust project using Conan
//! is to add a plain `conanfile.txt` file as follows:
//!
//! ```text
//! [requires]
//! libxml2/2.15.0
//! openssl/3.6.0
//! zlib/1.3.1
//! ```
//!
//! ## Example usage
//!
//! Add `conan2` to the `Cargo.toml` build dependencies section:
//!
//! ```toml
//! [build-dependencies]
//! conan2 = "0.1"
//! ```
//!
//! Add the following lines to the project `build.rs` script to invoke `conan install`
//! and pass the Conan dependency information to Cargo automatically:
//!
//! ```no_run
//! use conan2::ConanInstall;
//!
//! ConanInstall::new().run().parse().emit();
//! ```
//!
//! The most commonly used `build_type` Conan setting will be defined automatically
//! depending on the current Cargo build profile: `debug` or `release`.
//!
//! The Conan executable is assumed to be named `conan` unless
//! the `CONAN` environment variable is set to override.
//!
//! ## Advanced usage
//!
//! ### Automatic Conan profile inference from Cargo target
//!
//! Using custom Conan profiles with names derived from the Cargo target information
//! and a reduced output verbosity level:
//!
//! ```no_run
//! use conan2::{ConanInstall, ConanScope, ConanVerbosity};
//!
//! let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
//! let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
//! let conan_profile = format!("{}-{}", target_os, target_arch);
//!
//! ConanInstall::new()
//!     .profile(&conan_profile)
//!     .build_type("RelWithDebInfo") // Override the Cargo build profile
//!     .build("missing")
//!     .verbosity(ConanVerbosity::Error) // Silence Conan warnings
//!     .option(ConanScope::Global, "shared", "True") // Add some package options
//!     .option(ConanScope::Local, "power", "10")
//!     .option(ConanScope::Package("foolib"), "frob", "max")
//!     .option(ConanScope::Package("barlib/1.0"), "zoom", "True")
//!     .config("tools.build:skip_test", "True") // Add some Conan configs
//!     .remote("conancenter") // The default Conan remote, just to test `--remote`
//!     .arg("--core-conf")
//!     .arg("core:non_interactive=True")
//!     .run()
//!     .parse()
//!     .emit();
//! ```
//!
//! ### Automatic Conan profile creation
//!
//! Creating a custom default Conan profile on the fly with zero configuration:
//!
//! ```no_run
//! use conan2::{ConanInstall, ConanVerbosity};
//!
//! ConanInstall::new()
//!     .profile("cargo")
//!     .detect_profile() // Run `conan profile detect --exist-ok` for the above
//!     .run()
//!     .parse()
//!     .emit();
//! ```
//!
//! ### Using separate host and build profiles
//!
//! Using different values for `--profile:host` and `--profile:build`
//! arguments of `conan install` command:
//!
//! ```no_run
//! use conan2::{ConanInstall, ConanVerbosity};
//!
//! ConanInstall::new()
//!     .host_profile("cargo-host")
//!     .build_profile("cargo-build")
//!     .run()
//!     .parse()
//!     .emit();
//! ```
//!
//! ### Getting C/C++ include paths from Conan dependencies
//!
//! To use the list of include paths, do the following after
//! parsing the `conan install` output:
//!
//! ```no_run
//! use conan2::ConanInstall;
//!
//! let metadata = ConanInstall::new().run().parse();
//!
//! for path in metadata.include_paths() {
//!     // Add "-I{path}" to CXXFLAGS or something.
//! }
//!
//! metadata.emit();
//! ```

#![deny(missing_docs)]

use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::io::{BufRead, Cursor, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};

use serde_json::{Map, Value};

/// Conan binary override environment variable
const CONAN_ENV: &str = "CONAN";

/// Default Conan binary name
const DEFAULT_CONAN: &str = "conan";

/// `conan` command verbosity level
///
/// Defines the level of detail of the Conan command output.
///
/// Enum variants correspond to the following options:
/// `-vquiet`, `-verror`, `-vwarning`, `-vnotice`, `-vstatus`,
/// `-v` or `-vverbose`, `-vv` or `-vdebug`, `-vvv` or `-vtrace`.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ConanVerbosity {
    /// `-vquiet`
    Quiet,
    /// `-verror`
    Error,
    /// `-vwarning`
    #[default]
    Warning,
    /// `-vnotice`
    Notice,
    /// `-vstatus`
    Status,
    /// `-vverbose`
    Verbose,
    /// `-vdebug`
    Debug,
    /// `-vtrace`
    Trace,
}

/// `conan install` command option scope kind
///
/// Defines the Conan install command option scope variant:
/// local, global or per-package.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub enum ConanScope<'a> {
    /// `--options *:key=value`
    #[default]
    Global,
    /// `--options &:key=value`
    Local,
    /// `--options package:key=value`
    Package(&'a str),
}

/// `conan install` command builder
///
/// This opaque type implements a command line builder for
/// the `conan install` command invocation.
#[derive(Default)]
pub struct ConanInstall {
    /// Conan generators output directory
    output_folder: Option<PathBuf>,
    /// Conan recipe file path
    recipe_path: Option<PathBuf>,
    /// Conan host profile name
    profile: Option<String>,
    /// Conan build profile name
    build_profile: Option<String>,
    /// Conan profile auto-detection flag
    new_profile: bool,
    /// Conan build policy
    build: Option<String>,
    /// Conan build type setting:
    /// one of "Debug", "Release", "RelWithDebInfo" and "MinSizeRel"
    build_type: Option<String>,
    /// Custom remote name
    remote: Option<String>,
    /// Conan conf options stored as `{key}={value}`
    confs: Vec<(String, String)>,
    /// Conan package build options stored as `{scope}:{key}={value}`
    options: Vec<(String, String, String)>,
    /// Conan output verbosity level
    verbosity: ConanVerbosity,
    /// Extra `conan install` arguments
    extra_args: Vec<String>,
}

/// `conan install` command output data
pub struct ConanOutput(Output);

/// Build script instructions for Cargo
pub struct CargoInstructions {
    /// Raw build script output
    out: Vec<u8>,
    /// C include paths collected from the packages
    includes: BTreeSet<PathBuf>,
    /// C library search paths collected from the packages
    lib_dirs: BTreeSet<PathBuf>,
}

/// Conan dependency graph as a JSON-based tree structure
struct ConanDependencyGraph(Value);

impl std::fmt::Display for ConanVerbosity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConanVerbosity::Quiet => f.write_str("quiet"),
            ConanVerbosity::Error => f.write_str("error"),
            ConanVerbosity::Warning => f.write_str("warning"),
            ConanVerbosity::Notice => f.write_str("notice"),
            ConanVerbosity::Status => f.write_str("status"),
            ConanVerbosity::Verbose => f.write_str("verbose"),
            ConanVerbosity::Debug => f.write_str("debug"),
            ConanVerbosity::Trace => f.write_str("trace"),
        }
    }
}

impl std::fmt::Display for ConanScope<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConanScope::Global => f.write_str("*"),
            ConanScope::Local => f.write_str("&"),
            ConanScope::Package(name) => {
                if name.contains('/') {
                    // "name/version" combination works as it is.
                    f.write_str(name)
                } else {
                    // Bare package names are not accepted by Conan for some reason.
                    write!(f, "{name}/*")
                }
            }
        }
    }
}

impl ConanInstall {
    /// Creates a new `conan install` command with the default recipe path (`.`).
    #[must_use]
    pub fn new() -> ConanInstall {
        ConanInstall::default()
    }

    /// Creates a new `conan install` command with the user-provided recipe path.
    #[must_use]
    pub fn with_recipe(recipe_path: &Path) -> ConanInstall {
        ConanInstall {
            recipe_path: Some(recipe_path.to_owned()),
            ..Default::default()
        }
    }

    /// Sets a custom Conan generator output folder path.
    ///
    /// Matches `--output-folder` Conan executable option.
    ///
    /// This method should not be used in most cases:
    ///
    /// The Cargo-provided `OUT_DIR` environment variable value is used
    /// as the default when the command is invoked from a build script.
    pub fn output_folder(&mut self, output_folder: &Path) -> &mut ConanInstall {
        self.output_folder = Some(output_folder.to_owned());
        self
    }

    /// Sets the Conan profile name to use for installing dependencies.
    ///
    /// Matches `--profile` Conan executable option.
    pub fn profile(&mut self, profile: &str) -> &mut ConanInstall {
        self.profile = Some(profile.to_owned());
        self
    }

    /// Sets the Conan host profile name to use for installing dependencies.
    ///
    /// Matches `--profile:host` Conan executable option.
    pub fn host_profile(&mut self, profile: &str) -> &mut ConanInstall {
        self.profile(profile)
    }

    /// Sets the Conan build profile name to use for installing dependencies.
    ///
    /// Matches `--profile:build` Conan executable option.
    pub fn build_profile(&mut self, profile: &str) -> &mut ConanInstall {
        self.build_profile = Some(profile.to_owned());
        self
    }

    /// Auto-detects and creates the Conan profile to use for installing dependencies.
    ///
    /// Schedules `conan profile detect --exist-ok` to run before running `conan install`.
    pub fn detect_profile(&mut self) -> &mut ConanInstall {
        self.new_profile = true;
        self
    }

    /// Overrides the default Conan build type setting value for `conan install`.
    ///
    /// Matches `--settings build_type={value}` Conan executable option.
    ///
    /// NOTE: The default value for this setting will be inferred automatically
    ///       depending on the current Cargo build profile as either
    ///       `"Debug"` or `"Release"`.
    pub fn build_type(&mut self, build_type: &str) -> &mut ConanInstall {
        self.build_type = Some(build_type.to_owned());
        self
    }

    /// Specifies the custom remote name for `conan install`.
    ///
    /// Matches `--remote` Conan executable option.
    pub fn remote(&mut self, remote: &str) -> &mut ConanInstall {
        self.remote = Some(remote.to_owned());
        self
    }

    /// Adds the Conan configuration options (confs).
    ///
    /// Matches `--conf {key}={value}` Conan executable option.
    /// Can be called multiple times per Conan invocation.
    pub fn config(&mut self, key: &str, value: &str) -> &mut ConanInstall {
        self.confs.push((key.to_owned(), value.to_owned()));

        self
    }

    /// Adds the Conan package options to use for installing dependencies.
    ///
    /// Matches `--options {scope}:{key}={value}` Conan executable option.
    /// Can be called multiple times per Conan invocation.
    pub fn option(&mut self, scope: ConanScope, key: &str, value: &str) -> &mut ConanInstall {
        self.options
            .push((scope.to_string(), key.to_owned(), value.to_owned()));

        self
    }

    /// Sets the Conan dependency build policy for `conan install`.
    ///
    /// Matches `--build` Conan executable option.
    pub fn build(&mut self, build: &str) -> &mut ConanInstall {
        self.build = Some(build.to_owned());
        self
    }

    /// Sets the Conan command verbosity level.
    ///
    /// Matches `-v` Conan executable option.
    pub fn verbosity(&mut self, verbosity: ConanVerbosity) -> &mut ConanInstall {
        self.verbosity = verbosity;
        self
    }

    /// Adds one extra command line argument to the final `conan install` run.
    ///
    /// Can be called multiple times per Conan invocation.
    /// This method is a proxy for [`std::process::Command::arg()`].
    pub fn arg(&mut self, arg: &str) -> &mut ConanInstall {
        self.extra_args.push(arg.to_owned());
        self
    }

    /// Runs the `conan install` command and captures its JSON-formatted output.
    ///
    /// # Panics
    ///
    /// Panics if the Conan executable cannot be found.
    #[must_use]
    pub fn run(&self) -> ConanOutput {
        let conan = std::env::var_os(CONAN_ENV).unwrap_or_else(|| DEFAULT_CONAN.into());
        let recipe = self.recipe_path.as_deref().unwrap_or(Path::new("."));

        let output_folder = match &self.output_folder {
            Some(s) => s.clone(),
            None => std::env::var_os("OUT_DIR")
                .expect("OUT_DIR environment variable must be set")
                .into(),
        };

        if self.new_profile {
            Self::run_profile_detect(&conan, self.profile.as_deref());

            if self.build_profile != self.profile {
                Self::run_profile_detect(&conan, self.build_profile.as_deref());
            };
        }

        let mut command = Command::new(conan);
        command
            .arg("install")
            .arg(recipe)
            .arg(format!("-v{}", self.verbosity))
            .arg("--format")
            .arg("json")
            .arg("--output-folder")
            .arg(output_folder);

        if let Some(remote) = self.remote.as_deref() {
            command.arg("--remote");
            command.arg(remote);
        }

        if let Some(profile) = self.profile.as_deref() {
            command.arg("--profile:host").arg(profile);
        }

        if let Some(build_profile) = self.build_profile.as_deref() {
            command.arg("--profile:build").arg(build_profile);
        }

        if let Some(build) = self.build.as_deref() {
            command.arg("--build");
            command.arg(build);
        }

        if let Some(build_type) = self.build_type.as_deref() {
            // Prefer the user-provided build setting values.
            command.arg("--settings");
            command.arg(format!("build_type={build_type}"));
        } else {
            // Otherwise, use additional environment variables set by Cargo.
            Self::add_settings_from_env(&mut command);
        }

        for (scope, key, value) in &self.options {
            command.arg("--options");
            command.arg(format!("{scope}:{key}={value}"));
        }

        for (key, value) in &self.confs {
            command.arg("--conf");
            command.arg(format!("{key}={value}"));
        }

        self.extra_args.iter().for_each(|x| {
            command.arg(x);
        });

        let output = command
            .output()
            .expect("failed to run the Conan executable");

        ConanOutput(output)
    }

    /// Creates a new profile with `conan profile detect` if required.
    fn run_profile_detect(conan: &OsStr, profile: Option<&str>) {
        let mut command = Command::new(conan);
        command.arg("profile").arg("detect").arg("--exist-ok");

        if let Some(profile) = profile {
            println!("running 'conan profile detect' for profile '{profile}'");

            command.arg("--name").arg(profile);
        } else {
            println!("running 'conan profile detect' for the default profile");
        }

        let status = command
            .status()
            .expect("failed to run the Conan executable");

        #[allow(clippy::manual_assert)]
        if !status.success() {
            panic!("'conan profile detect' command failed: {status}");
        }
    }

    /// Adds automatic Conan settings arguments derived
    /// from the environment variables set by Cargo.
    ///
    /// The following Conan settings are auto-detected and set:
    ///
    /// - `build_type`
    fn add_settings_from_env(command: &mut Command) {
        match std::env::var("PROFILE").as_deref() {
            Ok("debug") => {
                command.arg("-s");
                command.arg("build_type=Debug");
            }
            Ok("release") => {
                command.arg("-s");
                command.arg("build_type=Release");
            }
            _ => (),
        }
    }
}

impl ConanOutput {
    /// Parses `conan install` command output and generates build script
    /// instructions for Cargo.
    ///
    /// # Panics
    ///
    /// Panics if the Conan command invocation failed or
    /// the JSON-formatted Conan output could not be parsed.
    #[must_use]
    pub fn parse(self) -> CargoInstructions {
        // Panic if the `conan install` command has failed.
        self.ensure_success();

        let mut cargo = CargoInstructions::new();

        // Re-run the build script if `CONAN` environment variable changes.
        cargo.rerun_if_env_changed(CONAN_ENV);

        // Pass Conan warnings through to Cargo using build script instructions.
        for line in Cursor::new(self.stderr()).lines() {
            if let Some(msg) = line.unwrap().strip_prefix("WARN: ") {
                cargo.warning(msg);
            }
        }

        // Parse the JSON-formatted `conan install` command output.
        let metadata: Value =
            serde_json::from_slice(self.stdout()).expect("failed to parse JSON output");

        // Walk the dependency graph and collect the C/C++ libraries.
        ConanDependencyGraph(metadata).traverse(&mut cargo);

        cargo
    }

    /// Ensures that the Conan command has been executed successfully.
    ///
    /// # Panics
    ///
    /// Panics with an error message if the Conan command invocation failed.
    pub fn ensure_success(&self) {
        if self.is_success() {
            return;
        }

        let code = self.status_code();
        let msg = String::from_utf8_lossy(self.stderr());

        panic!("Conan failed with status {code}: {msg}");
    }

    /// Checks the Conan install command execution status.
    #[must_use]
    pub fn is_success(&self) -> bool {
        self.0.status.success()
    }

    /// Gets the Conan install command execution status code.
    #[must_use]
    pub fn status_code(&self) -> i32 {
        self.0.status.code().unwrap_or_default()
    }

    /// Gets the Conan JSON-formatted output as bytes.
    #[must_use]
    pub fn stdout(&self) -> &[u8] {
        &self.0.stdout
    }

    /// Gets the Conan command error message as bytes.
    #[must_use]
    pub fn stderr(&self) -> &[u8] {
        &self.0.stderr
    }
}

impl CargoInstructions {
    /// Emits build script instructions for Cargo into `stdout`.
    ///
    /// # Panics
    ///
    /// Panics if the Cargo build instructions can not be written to `stdout`.
    pub fn emit(&self) {
        std::io::stdout().write_all(self.as_bytes()).unwrap();
    }

    /// Gets the Cargo instruction lines as bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.out
    }

    /// Gets the C/C++ include directory paths for all dependencies.
    #[must_use]
    pub fn include_paths(&self) -> Vec<PathBuf> {
        self.includes.iter().cloned().collect()
    }

    /// Gets the C/C++ library search directory paths for all dependencies.
    #[must_use]
    pub fn library_paths(&self) -> Vec<PathBuf> {
        self.lib_dirs.iter().cloned().collect()
    }

    /// Creates a new empty Cargo instructions list.
    fn new() -> CargoInstructions {
        CargoInstructions {
            out: Vec::with_capacity(1024),
            includes: BTreeSet::new(),
            lib_dirs: BTreeSet::new(),
        }
    }

    /// Adds `cargo:warning={message}` instruction.
    fn warning(&mut self, message: &str) {
        writeln!(self.out, "cargo:warning={message}").unwrap();
    }

    /// Adds `cargo:rerun-if-env-changed={val}` instruction.
    fn rerun_if_env_changed(&mut self, val: &str) {
        writeln!(self.out, "cargo:rerun-if-env-changed={val}").unwrap();
    }

    /// Adds `cargo:rustc-cdylib-link-arg={val}` instruction.
    fn rustc_cdylib_link_arg(&mut self, val: &str) {
        writeln!(self.out, "cargo:rustc-cdylib-link-arg={val}").unwrap();
    }

    /// Adds `cargo:rustc-link-arg-bins={val}` instruction.
    fn rustc_link_arg_bins(&mut self, val: &str) {
        writeln!(self.out, "cargo:rustc-link-arg-bins={val}").unwrap();
    }

    /// Adds `cargo:rustc-link-lib=[(dylib|static)=]{lib}` instruction.
    ///
    /// The library linking type (dynamic or static) may be inferred
    /// from the file name pattern on Linux-like platforms.
    fn rustc_link_lib(&mut self, lib: &str) {
        // When the full library file name is supplied,
        // convert `libfoo.a` and `libfoo.so` into `foo` automatically.
        if let Some(lib) = lib.strip_prefix("lib") {
            if let Some(lib) = lib.strip_suffix(".a") {
                self.rustc_link_lib_kind(lib, Some("static"));
                return;
            } else if let Some(lib) = lib.strip_suffix(".so") {
                self.rustc_link_lib_kind(lib, Some("dylib"));
                return;
            }
        }

        self.rustc_link_lib_kind(lib, None);
    }

    /// Adds `cargo:rustc-link-lib=[{kind}=]{lib}` instruction.
    fn rustc_link_lib_kind(&mut self, lib: &str, kind: Option<&str>) {
        match kind {
            Some(kind) => {
                writeln!(self.out, "cargo:rustc-link-lib={kind}={lib}").unwrap();
            }
            None => {
                writeln!(self.out, "cargo:rustc-link-lib={lib}").unwrap();
            }
        }
    }

    /// Adds `cargo:rustc-link-search={path}` instruction.
    fn rustc_link_search(&mut self, path: &str) {
        let lib_dir = path.into();
        if !self.lib_dirs.contains(&lib_dir) {
            writeln!(self.out, "cargo:rustc-link-search={path}").unwrap();
            self.lib_dirs.insert(lib_dir);
        }
    }

    /// Adds `cargo:include={path}` instruction.
    fn include(&mut self, path: &str) {
        let include_dir = path.into();
        if !self.includes.contains(&include_dir) {
            writeln!(self.out, "cargo:include={path}").unwrap();
            self.includes.insert(include_dir);
        }
    }
}

impl ConanDependencyGraph {
    /// Traverses the dependency graph and emits the `rustc` link instructions
    /// in the correct linking order.
    fn traverse(self, cargo: &mut CargoInstructions) {
        // Consumer package node id: the root of the graph
        let root_node_id = "0";

        self.visit_dependency(cargo, root_node_id);
    }

    /// Visits the dependencies recursively starting from node `node_id`
    /// and emits `rustc` link instructions.
    fn visit_dependency(&self, cargo: &mut CargoInstructions, node_id: &str) {
        let Some(node) = self.find_node(node_id) else {
            return;
        };

        if let Some(Value::Object(cpp_info)) = node.get("cpp_info") {
            for cpp_comp_name in cpp_info.keys() {
                Self::visit_cpp_component(cargo, cpp_info, cpp_comp_name);
            }
        };

        // Recursively visit transitive dependencies.
        if let Some(Value::Object(dependencies)) = node.get("dependencies") {
            for dependency_id in dependencies.keys() {
                self.visit_dependency(cargo, dependency_id);
            }
        };
    }

    /// Visits the dependency package components recursively starting from
    /// the component named `comp_name` and emits `rustc` link instructions.
    fn visit_cpp_component(
        cargo: &mut CargoInstructions,
        cpp_info: &Map<String, Value>,
        comp_name: &str,
    ) {
        let Some(component) = Self::find_cpp_component(cpp_info, comp_name) else {
            return;
        };

        // 1. Emit packaged library link instructions for `rustc`.
        if let Some(Value::Array(libs)) = component.get("libs") {
            // FIXME: Many non-library Conan packages in the wild have
            //        non-empty "libdirs" attribute arrays.
            //        Ignore them and do not emit bogus library search paths.
            if !libs.is_empty() {
                // 1.1. Emit linker search directory instructions for `rustc`.
                if let Some(Value::Array(libdirs)) = component.get("libdirs") {
                    for libdir in libdirs {
                        if let Value::String(libdir) = libdir {
                            cargo.rustc_link_search(libdir);
                        }
                    }
                }
            }

            // 1.2. Emit library link by name (`-lfoo`) instructions for `rustc`.
            for lib in libs {
                if let Value::String(lib) = lib {
                    cargo.rustc_link_lib(lib);
                }
            }
        }

        // 2. Emit system library link by name (`-lbar`) instructions for `rustc`.
        if let Some(Value::Array(system_libs)) = component.get("system_libs") {
            for system_lib in system_libs {
                if let Value::String(system_lib) = system_lib {
                    cargo.rustc_link_lib(system_lib);
                }
            }
        };

        // 3. Emit `cargo:include=DIR` metadata for Rust dependencies.
        if let Some(Value::Array(includedirs)) = component.get("includedirs") {
            for include in includedirs {
                if let Value::String(include) = include {
                    cargo.include(include);
                }
            }
        };

        // 4. Emit `cargo:rustc-cdylib-link-arg=FLAGS` metadata for `rustc`.
        if let Some(Value::Array(flags)) = component.get("sharedlinkflags") {
            for flag in flags {
                if let Value::String(flag) = flag {
                    cargo.rustc_cdylib_link_arg(flag);
                }
            }
        }

        // 5. Emit `cargo:rustc-link-arg-bins=FLAGS` metadata for `rustc`.
        if let Some(Value::Array(flags)) = component.get("exelinkflags") {
            for flag in flags {
                if let Value::String(flag) = flag {
                    cargo.rustc_link_arg_bins(flag);
                }
            }
        }

        // 6. Recursively visit dependency component requirements.
        if let Some(Value::Array(requires)) = component.get("requires") {
            for requirement in requires {
                if let Value::String(req_comp_name) = requirement {
                    Self::visit_cpp_component(cargo, cpp_info, req_comp_name);
                }
            }
        };
    }

    /// Gets the dependency node field map by the node `id` key.
    fn find_node(&self, id: &str) -> Option<&Map<String, Value>> {
        let Value::Object(root) = &self.0 else {
            panic!("root JSON object expected");
        };

        let Some(Value::Object(graph)) = root.get("graph") else {
            panic!("root 'graph' object expected");
        };

        let Some(Value::Object(nodes)) = graph.get("nodes") else {
            panic!("root 'nodes' object expected");
        };

        if let Some(Value::Object(node)) = nodes.get(id) {
            Some(node)
        } else {
            None
        }
    }

    /// Gets the dependency component field map by its name.
    fn find_cpp_component<'a>(
        cpp_info: &'a Map<String, Value>,
        name: &str,
    ) -> Option<&'a Map<String, Value>> {
        if let Some(Value::Object(component)) = cpp_info.get(name) {
            Some(component)
        } else {
            None
        }
    }
}