Skip to content

Commit

Permalink
refactor: reorganize imports and improve code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Ayodeji Ige committed Nov 27, 2024
1 parent d73113d commit 64935b5
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 102 deletions.
64 changes: 39 additions & 25 deletions crates/wdk-build/src/cargo_make.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,13 @@ const CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY_ENV_VAR: &str =
const CARGO_MAKE_CURRENT_TASK_NAME_ENV_VAR: &str = "CARGO_MAKE_CURRENT_TASK_NAME";

/// The environment variable that cargo-make uses to store driver model type
const WDK_BUILD_METADATA_DRIVER_MODEL_DRIVER_TYPE_ENV_VAR: &str = "WDK_BUILD_METADATA-DRIVER_MODEL-DRIVER_TYPE";
const WDK_BUILD_METADATA_DRIVER_MODEL_DRIVER_TYPE_ENV_VAR: &str =
"WDK_BUILD_METADATA-DRIVER_MODEL-DRIVER_TYPE";

/// The environment variable that cargo-make uses to store additional files to be pacakaged with the driver
const WDK_BUILD_METADATA_DRIVER_INSTALL_PACKAGE_FILES_ENV_VAR: &str = "WDK_BUILD_METADATA-DRIVER_INSTALL-PACKAGE_FILES";
/// The environment variable that cargo-make uses to store additional files to
/// be pacakaged with the driver
const WDK_BUILD_METADATA_DRIVER_INSTALL_PACKAGE_FILES_ENV_VAR: &str =
"WDK_BUILD_METADATA-DRIVER_INSTALL-PACKAGE_FILES";

/// `clap` uses an exit code of 2 for usage errors: <https://github.com/clap-rs/clap/blob/14fd853fb9c5b94e371170bbd0ca2bf28ef3abff/clap_builder/src/util/mod.rs#L30C18-L30C28>
const CLAP_USAGE_EXIT_CODE: i32 = 2;
Expand Down Expand Up @@ -731,7 +734,7 @@ pub fn copy_to_driver_package_folder<P: AsRef<Path>>(path_to_copy: P) -> Result<
std::fs::create_dir(&package_folder_path)?;
}

eprintln!("Copying {:?} to {:?}", path_to_copy, package_folder_path);
eprintln!("Copying {path_to_copy:?} to {package_folder_path:?}");
let destination_path = package_folder_path.join(
path_to_copy
.file_name()
Expand Down Expand Up @@ -1124,50 +1127,61 @@ pub fn driver_sample_infverif_condition_script() -> anyhow::Result<()> {
/// # Panics
///
/// Panics if `CARGO_MAKE_CURRENT_TASK_NAME` is not set in the environment
/// Panics if `WDK_BUILD_METADATA_DRIVER_MODEL_DRIVER_TYPE` is not set in the environment
/// Panics if `WDK_BUILD_METADATA_DRIVER_MODEL_DRIVER_TYPE` is not set in the
/// environment
pub fn driver_model_is_not_package_condition_script() -> anyhow::Result<()> {
condition_script(|| {
let driver_type = env::var(WDK_BUILD_METADATA_DRIVER_MODEL_DRIVER_TYPE_ENV_VAR).expect("A driver type should exist in the WDK build metadata");
let driver_type = env::var(WDK_BUILD_METADATA_DRIVER_MODEL_DRIVER_TYPE_ENV_VAR)
.expect("A driver type should exist in the WDK build metadata");
if driver_type == "PACKAGE" {
// cargo_make will interpret returning an error from the rust-script
// condition_script as skipping the task
return Err::<(), anyhow::Error>(anyhow::Error::msg(format!(
"Skipping {} task The driver model is a package.",
env::var(CARGO_MAKE_CURRENT_TASK_NAME_ENV_VAR).expect("CARGO_MAKE_CURRENT_TASK_NAME should be set by cargo-make")
env::var(CARGO_MAKE_CURRENT_TASK_NAME_ENV_VAR)
.expect("CARGO_MAKE_CURRENT_TASK_NAME should be set by cargo-make")
)));
}
Ok(())
})
}

/// Copy the addition files specified in the wdk metadata to the Driver Package folder
/// Copy the addition files specified in the wdk metadata to the Driver Package
/// folder
///
/// # Errors
///
/// This function returns an error if the package files specified in the
/// metadata are not found.
///
/// # Panics
///
/// Panics if `WDK_BUILD_METADATA_DRIVER_INSTALL_PACKAGE_FILES` is not set in the environment
///
/// Panics if `WDK_BUILD_METADATA_DRIVER_INSTALL_PACKAGE_FILES` is not set in
/// the environment
pub fn copy_package_files_to_driver_package_folder() -> Result<(), ConfigError> {
let package_files: Vec<String> = env::var(WDK_BUILD_METADATA_DRIVER_INSTALL_PACKAGE_FILES_ENV_VAR)
.expect("The package files should be set by the wdk-build-init task")
.split_terminator(metadata::ser::SEQ_ELEMENT_SEPARATOR)
.map(String::from)
.collect();
let package_files: Vec<String> =
env::var(WDK_BUILD_METADATA_DRIVER_INSTALL_PACKAGE_FILES_ENV_VAR)
.expect("The package files should be set by the wdk-build-init task")
.split_terminator(metadata::ser::SEQ_ELEMENT_SEPARATOR)
.map(String::from)
.collect();

let env_variable_regex = regex::Regex::new(r"\$\{(\w+)\}").unwrap();
package_files
.iter()
.try_for_each(|package_file|{
// Evaluate environment variables in the package file path.
let package_file_evaluated = env_variable_regex.replace_all(package_file, |captures: &regex::Captures| {
package_files.iter().try_for_each(|package_file| {
// Evaluate environment variables in the package file path.
let package_file_evaluated = env_variable_regex
.replace_all(package_file, |captures: &regex::Captures| {
print!("Evaluating environment variable {}", &captures[1]);
env::var(&captures[1]).unwrap_or_else(|_| {
panic!("The environment variable {} should be set", &captures[1])
})
}).to_string();
})
.to_string();

let package_file_path = Path::new(&package_file_evaluated);
copy_to_driver_package_folder(package_file_path)
})?;

let package_file_path = Path::new(&package_file_evaluated);
copy_to_driver_package_folder(package_file_path)
})?;

Ok(())
}

Expand Down
47 changes: 26 additions & 21 deletions crates/wdk-build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,11 @@
#![cfg_attr(nightly_toolchain, feature(assert_matches))]

pub use bindgen::BuilderExt;
use metadata::TryFromCargoMetadataError;
use metadata::driver_install::DriverInstall;
use metadata::driver_settings::DriverConfig;
use metadata::{
driver_install::DriverInstall,
driver_settings::DriverConfig,
TryFromCargoMetadataError,
};

pub mod cargo_make;
pub mod metadata;
Expand All @@ -42,7 +44,7 @@ pub struct Config {
/// Build configuration of driver
pub driver_config: DriverConfig,
/// Driver installation settings
pub driver_install: Option<DriverInstall>
pub driver_install: Option<DriverInstall>,
}

/// The CPU architecture that's configured to be compiled for
Expand Down Expand Up @@ -127,8 +129,12 @@ rustflags = [\"-C\", \"target-feature=+crt-static\"]
#[error(transparent)]
SerdeError(#[from] metadata::Error),

/// Error returned when wdk build runs for [`metadata::driver_settings::DriverConfig::Package`]
#[error("Package driver model does not support building binaries. It should be used for Inf only drivers.")]
/// Error returned when wdk build runs for
/// [`metadata::driver_settings::DriverConfig::Package`]
#[error(
"Package driver model does not support building binaries. It should be used for Inf only \
drivers."
)]
UnsupportedDriverConfig,
}

Expand Down Expand Up @@ -294,7 +300,7 @@ impl Config {
DriverConfig::Umdf(_) => "um",
DriverConfig::Package => {
return Err(ConfigError::UnsupportedDriverConfig);
},
}
});
if !km_or_um_include_path.is_dir() {
return Err(ConfigError::DirectoryNotFound {
Expand Down Expand Up @@ -353,10 +359,10 @@ impl Config {
.canonicalize()?
.strip_extended_length_path_prefix()?,
);
},
}
DriverConfig::Package => {
return Err(ConfigError::UnsupportedDriverConfig);
},
}
}

Ok(include_paths)
Expand Down Expand Up @@ -392,7 +398,7 @@ impl Config {
}
DriverConfig::Package => {
return Err(ConfigError::UnsupportedDriverConfig);
},
}
});
if !windows_sdk_library_path.is_dir() {
return Err(ConfigError::DirectoryNotFound {
Expand Down Expand Up @@ -443,10 +449,10 @@ impl Config {
.canonicalize()?
.strip_extended_length_path_prefix()?,
);
},
}
DriverConfig::Package => {
return Err(ConfigError::UnsupportedDriverConfig);
},
}
}

// Reverse order of library paths so that paths pushed later into the vec take
Expand Down Expand Up @@ -543,7 +549,7 @@ impl Config {

umdf_definitions
}
DriverConfig::Package => unreachable!()
DriverConfig::Package => unreachable!("Package driver should not be running binary build"),
}
.into_iter()
.map(|(key, value)| (key.to_string(), value.map(|v| v.to_string()))),
Expand Down Expand Up @@ -605,7 +611,7 @@ impl Config {
(config.umdf_version_major, config.target_umdf_version_minor)
}
DriverConfig::Wdm => return None,
DriverConfig::Package => unreachable!(),
DriverConfig::Package => unreachable!("Package driver should not be running binary build"),
};

Some(format!(
Expand Down Expand Up @@ -702,7 +708,7 @@ impl Config {
}
DriverConfig::Package => {
return Err(ConfigError::UnsupportedDriverConfig);
},
}
}

// Emit linker arguments common to all configs
Expand Down Expand Up @@ -907,6 +913,7 @@ mod tests {
#[cfg(nightly_toolchain)]
use std::assert_matches::assert_matches;
use std::{collections::HashMap, ffi::OsStr, sync::Mutex};

use metadata::driver_settings::{KmdfConfig, UmdfConfig};

use super::*;
Expand Down Expand Up @@ -1078,10 +1085,7 @@ mod tests {
});

#[cfg(nightly_toolchain)]
assert_matches!(
config.driver_config,
DriverConfig::Package
);
assert_matches!(config.driver_config, DriverConfig::Package);
assert_eq!(config.cpu_architecture, CpuArchitecture::Arm64);
}

Expand All @@ -1099,9 +1103,10 @@ mod tests {
}

mod compute_wdffunctions_symbol_name {
use super::*;
use metadata::driver_settings::{KmdfConfig, UmdfConfig};

use super::*;

#[test]
fn kmdf() {
let config = with_env(&[("CARGO_CFG_TARGET_ARCH", "x86_64")], || Config {
Expand Down Expand Up @@ -1147,7 +1152,7 @@ mod tests {
}

#[test]
#[should_panic]
#[should_panic = "Package driver should not be running binary build"]
fn package() {
let config = with_env(&[("CARGO_CFG_TARGET_ARCH", "x86_64")], || Config {
driver_config: DriverConfig::Package,
Expand Down
16 changes: 9 additions & 7 deletions crates/wdk-build/src/metadata/driver_settings.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// Copyright (c) Microsoft Corporation
// License: MIT OR Apache-2.0

//! Types for the `DriverConfig` section of the `metadata.wdk` section of the `Cargo.toml`
//!
//! This section is used to specify the driver type and its associated configuration parameters.
//! This corresponds with the settings in the `Driver Model` property pages
//! Types for the `DriverConfig` section of the `metadata.wdk` section of the
//! `Cargo.toml`
//!
//! This section is used to specify the driver type and its associated
//! configuration parameters. This corresponds with the settings in the `Driver
//! Model` property pages

use serde::{Deserialize, Serialize};

Expand All @@ -24,7 +26,7 @@ pub enum DriverConfig {
/// User Mode Driver Framework
Umdf(UmdfConfig),
/// INF only drivers e.g. null drivers and extension INFs
Package
Package,
}

/// Private enum identical to [`DriverConfig`] but with different tag name to
Expand All @@ -44,7 +46,7 @@ enum DeserializableDriverConfig {
Wdm,
Kmdf(KmdfConfig),
Umdf(UmdfConfig),
Package
Package,
}

/// The configuration parameters for KMDF drivers
Expand Down Expand Up @@ -126,4 +128,4 @@ impl UmdfConfig {
pub fn new() -> Self {
Self::default()
}
}
}
9 changes: 4 additions & 5 deletions crates/wdk-build/src/metadata/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ pub use error::{Error, Result};
pub use map::Map;
pub use ser::{to_map, to_map_with_prefix, Serializer};

pub(crate) mod ser;
pub mod driver_install;
pub mod driver_settings;
pub(crate) mod ser;

mod error;
mod map;
Expand All @@ -24,12 +24,11 @@ use std::collections::HashSet;

use camino::Utf8PathBuf;
use cargo_metadata::Metadata;
use driver_install::DriverInstall;
use driver_settings::DriverConfig;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use driver_settings::DriverConfig;
use driver_install::DriverInstall;

/// Metadata specified in the `metadata.wdk` section of the `Cargo.toml`
/// of a crate that depends on the WDK, or in a cargo workspace.
///
Expand All @@ -44,7 +43,7 @@ pub struct Wdk {
/// Metadata corresponding to the `Driver Model` property page in the WDK
pub driver_model: DriverConfig,
/// Metadata corresponding to the `Driver Install` property page in the WDK
pub driver_install: Option<DriverInstall>
pub driver_install: Option<DriverInstall>,
}

/// Errors that could result from trying to construct a
Expand Down
Loading

0 comments on commit 64935b5

Please sign in to comment.