Skip to content

Commit 8ff2627

Browse files
committed
probe_or_exit for cleaner Cargo error output
1 parent a6717ef commit 8ff2627

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/lib.rs

+52
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,15 @@ pub fn find_library(name: &str) -> Result<Library, String> {
501501
probe_library(name).map_err(|e| e.to_string())
502502
}
503503

504+
/// Simple shortcut for using all default options for finding a library,
505+
/// and exiting the build script with a verbose error message on failure.
506+
///
507+
/// This is preferred over `probe_library().unwrap()`, because it can
508+
/// print a more readable output.
509+
pub fn probe_library_or_exit(name: &str) -> Library {
510+
Config::new().probe_or_exit(name)
511+
}
512+
504513
/// Simple shortcut for using all default options for finding a library.
505514
pub fn probe_library(name: &str) -> Result<Library, Error> {
506515
Config::new().probe(name)
@@ -543,6 +552,21 @@ impl Config {
543552
}
544553
}
545554

555+
/// Clone the Config, with output buffering enabled
556+
fn with_metadata_buffer(&self) -> Config {
557+
Config {
558+
statik: self.statik,
559+
min_version: self.min_version.clone(),
560+
max_version: self.max_version.clone(),
561+
extra_args: self.extra_args.clone(),
562+
print_system_cflags: self.print_system_cflags,
563+
print_system_libs: self.print_system_libs,
564+
cargo_metadata: self.cargo_metadata,
565+
env_metadata: self.env_metadata,
566+
metadata_buffer: Some(Mutex::default()),
567+
}
568+
}
569+
546570
/// Emit buffered metadata, if any
547571
fn print_bufferred(&self) {
548572
if let Some(mut buf) = self.metadata_buffer.as_ref().and_then(|m| m.lock().ok()) {
@@ -640,6 +664,34 @@ impl Config {
640664
self.probe(name).map_err(|e| e.to_string())
641665
}
642666

667+
/// Run `pkg-config` to find the library `name`, or exit the
668+
/// build script with a verbose error.
669+
///
670+
/// This is preferred over `probe().unwrap()`, because it can
671+
/// print a more readable error.
672+
///
673+
/// This will use all configuration previously set to specify how
674+
/// `pkg-config` is run.
675+
pub fn probe_or_exit(&self, name: &str) -> Library {
676+
let buffered = self.with_metadata_buffer();
677+
match buffered.probe(name) {
678+
Ok(lib) => {
679+
buffered.print_bufferred();
680+
lib
681+
}
682+
Err(err) => {
683+
println!(
684+
"cargo:warning={}",
685+
err.error_message().replace("\n", "\ncargo:warning=")
686+
);
687+
eprintln!("{}", err);
688+
689+
// The same error code as a panic, but it won't print an irrelevant backtrace
690+
std::process::exit(101);
691+
}
692+
}
693+
}
694+
643695
/// Run `pkg-config` to find the library `name`.
644696
///
645697
/// This will use all configuration previously set to specify how

0 commit comments

Comments
 (0)