-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathcargo_make.rs
1135 lines (1022 loc) · 40.8 KB
/
cargo_make.rs
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
// Copyright (c) Microsoft Corporation
// License: MIT OR Apache-2.0
//! Utilities for `cargo-make` tasks used to package binaries dependent on the
//! `WDK`.
//!
//! This module provides functions used in the rust scripts in
//! `rust-driver-makefile.toml`. This includes argument parsing functionality
//! used by `rust-driver-makefile.toml` to validate and forward arguments common
//! to cargo commands. It uses a combination of `clap` and `clap_cargo` to
//! provide a CLI very close to cargo's own, but only exposes the arguments
//! supported by `rust-driver-makefile.toml`.
use core::{fmt, ops::RangeFrom};
use std::{
env,
panic::UnwindSafe,
path::{Path, PathBuf},
};
use anyhow::Context;
use cargo_metadata::{camino::Utf8Path, Metadata, MetadataCommand};
use clap::{Args, Parser};
use tracing::{instrument, trace};
use crate::{
metadata,
utils::{
detect_wdk_content_root,
get_latest_windows_sdk_version,
get_wdk_version_number,
PathExt,
},
ConfigError,
CpuArchitecture,
};
/// The filename of the main makefile for Rust Windows drivers.
pub const RUST_DRIVER_MAKEFILE_NAME: &str = "rust-driver-makefile.toml";
/// The filename of the samples makefile for Rust Windows drivers.
pub const RUST_DRIVER_SAMPLE_MAKEFILE_NAME: &str = "rust-driver-sample-makefile.toml";
const PATH_ENV_VAR: &str = "Path";
/// The environment variable that [`setup_wdk_version`] stores the WDK version
/// in.
pub const WDK_VERSION_ENV_VAR: &str = "WDK_BUILD_DETECTED_VERSION";
/// The first WDK version with the new `InfVerif` behavior.
const MINIMUM_SAMPLES_FLAG_WDK_VERSION: i32 = 25798;
const WDK_INF_ADDITIONAL_FLAGS_ENV_VAR: &str = "WDK_BUILD_ADDITIONAL_INFVERIF_FLAGS";
const WDK_BUILD_OUTPUT_DIRECTORY_ENV_VAR: &str = "WDK_BUILD_OUTPUT_DIRECTORY";
/// The name of the environment variable that cargo-make uses during `cargo
/// build` and `cargo test` commands
const CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR: &str = "CARGO_MAKE_CARGO_BUILD_TEST_FLAGS";
const CARGO_MAKE_PROFILE_ENV_VAR: &str = "CARGO_MAKE_PROFILE";
const CARGO_MAKE_CARGO_PROFILE_ENV_VAR: &str = "CARGO_MAKE_CARGO_PROFILE";
const CARGO_MAKE_CRATE_TARGET_TRIPLE_ENV_VAR: &str = "CARGO_MAKE_CRATE_TARGET_TRIPLE";
const CARGO_MAKE_CRATE_CUSTOM_TRIPLE_TARGET_DIRECTORY_ENV_VAR: &str =
"CARGO_MAKE_CRATE_CUSTOM_TRIPLE_TARGET_DIRECTORY";
const CARGO_MAKE_RUST_DEFAULT_TOOLCHAIN_ENV_VAR: &str = "CARGO_MAKE_RUST_DEFAULT_TOOLCHAIN";
const CARGO_MAKE_CRATE_NAME_ENV_VAR: &str = "CARGO_MAKE_CRATE_NAME";
const CARGO_MAKE_CRATE_FS_NAME_ENV_VAR: &str = "CARGO_MAKE_CRATE_FS_NAME";
const CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY_ENV_VAR: &str =
"CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY";
const CARGO_MAKE_CURRENT_TASK_NAME_ENV_VAR: &str = "CARGO_MAKE_CURRENT_TASK_NAME";
/// `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;
// This range is inclusive of 25798. FIXME: update with range end after /sample
// flag is added to InfVerif CLI
const MISSING_SAMPLE_FLAG_WDK_BUILD_NUMBER_RANGE: RangeFrom<u32> = 25798..;
trait ParseCargoArgs {
fn parse_cargo_args(&self);
}
#[derive(Parser, Debug)]
struct CommandLineInterface {
#[command(flatten)]
base: BaseOptions,
#[command(flatten)]
#[command(next_help_heading = "Package Selection")]
workspace: clap_cargo::Workspace,
#[command(flatten)]
#[command(next_help_heading = "Feature Selection")]
features: clap_cargo::Features,
#[command(flatten)]
compilation_options: CompilationOptions,
#[command(flatten)]
manifest_options: ManifestOptions,
}
#[derive(Args, Debug)]
struct BaseOptions {
#[arg(long, help = "Do not print cargo log messages")]
quiet: bool,
#[arg(short, long, action = clap::ArgAction::Count, help = "Use verbose output (-vv very verbose/build.rs output)")]
verbose: u8,
}
#[derive(Args, Debug)]
#[command(next_help_heading = "Compilation Options")]
struct CompilationOptions {
#[arg(
short,
long,
help = "Build artifacts in release mode, with optimizations"
)]
release: bool,
#[arg(
long,
value_name = "PROFILE-NAME",
help = "Build artifacts with the specified profile"
)]
profile: Option<String>,
#[arg(
short,
long,
value_name = "N",
allow_negative_numbers = true,
help = "Number of parallel jobs, defaults to # of CPUs."
)]
jobs: Option<String>,
// FIXME: support building multiple targets at once
#[arg(long, value_name = "TRIPLE", help = "Build for a target triple")]
target: Option<String>,
#[allow(clippy::option_option)] // This is how clap_derive expects "optional value for optional argument" args
#[arg(
long,
value_name = "FMTS",
require_equals = true,
help = "Timing output formats (unstable) (comma separated): html, json"
)]
timings: Option<Option<String>>,
}
#[derive(Args, Debug)]
#[command(next_help_heading = "Manifest Options")]
struct ManifestOptions {
#[arg(long, help = "Require Cargo.lock and cache are up to date")]
frozen: bool,
#[arg(long, help = "Require Cargo.lock is up to date")]
locked: bool,
#[arg(long, help = "Run without accessing the network")]
offline: bool,
}
impl ParseCargoArgs for CommandLineInterface {
fn parse_cargo_args(&self) {
let Self {
base,
workspace,
features,
compilation_options,
manifest_options,
} = self;
base.parse_cargo_args();
workspace.parse_cargo_args();
features.parse_cargo_args();
compilation_options.parse_cargo_args();
manifest_options.parse_cargo_args();
}
}
impl ParseCargoArgs for BaseOptions {
fn parse_cargo_args(&self) {
let Self { quiet, verbose } = self;
if *quiet && *verbose > 0 {
eprintln!("Cannot specify both --quiet and --verbose");
std::process::exit(CLAP_USAGE_EXIT_CODE);
}
if *quiet {
append_to_space_delimited_env_var(CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR, "--quiet");
}
if *verbose > 0 {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
format!("-{}", "v".repeat((*verbose).into())).as_str(),
);
}
}
}
impl ParseCargoArgs for clap_cargo::Workspace {
fn parse_cargo_args(&self) {
let Self {
package,
workspace,
all,
exclude,
..
} = self;
if !package.is_empty() {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
package
.iter()
.fold(
String::with_capacity({
const MINIMUM_PACKAGE_SPEC_LENGTH: usize = 1;
const MINIMUM_PACKAGE_ARG_LENGTH: usize =
"--package ".len() + MINIMUM_PACKAGE_SPEC_LENGTH + " ".len();
package.len() * MINIMUM_PACKAGE_ARG_LENGTH
}),
|mut package_args, package_spec| {
package_args.push_str("--package ");
package_args.push_str(package_spec);
package_args.push(' ');
package_args
},
)
.trim_end(),
);
}
if *workspace {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
"--workspace",
);
}
if !exclude.is_empty() {
if !*workspace {
eprintln!("--exclude can only be used together with --workspace");
std::process::exit(CLAP_USAGE_EXIT_CODE);
}
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
exclude
.iter()
.fold(
String::with_capacity({
const MINIMUM_PACKAGE_SPEC_LENGTH: usize = 1;
const MINIMUM_EXCLUDE_ARG_LENGTH: usize =
"--exclude ".len() + MINIMUM_PACKAGE_SPEC_LENGTH + " ".len();
package.len() * MINIMUM_EXCLUDE_ARG_LENGTH
}),
|mut exclude_args, package_spec| {
exclude_args.push_str("--exclude ");
exclude_args.push_str(package_spec);
exclude_args.push(' ');
exclude_args
},
)
.trim_end(),
);
}
if *all {
append_to_space_delimited_env_var(CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR, "--all");
}
}
}
impl ParseCargoArgs for clap_cargo::Features {
fn parse_cargo_args(&self) {
let Self {
all_features,
no_default_features,
features,
..
} = self;
if *all_features {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
"--all-features",
);
}
if *no_default_features {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
"--no-default-features",
);
}
if !features.is_empty() {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
features
.iter()
.fold(
String::with_capacity({
const MINIMUM_FEATURE_NAME_LENGTH: usize = 1;
const MINIMUM_FEATURE_ARG_LENGTH: usize =
"--features ".len() + MINIMUM_FEATURE_NAME_LENGTH + " ".len();
features.len() * MINIMUM_FEATURE_ARG_LENGTH
}),
|mut feature_args: String, feature| {
feature_args.push_str("--features ");
feature_args.push_str(feature);
feature_args.push(' ');
feature_args
},
)
.trim_end(),
);
}
}
}
impl ParseCargoArgs for CompilationOptions {
fn parse_cargo_args(&self) {
let Self {
release,
profile,
jobs,
target,
timings,
} = self;
if *release && profile.is_some() {
eprintln!("the `--release` flag should not be specified with the `--profile` flag");
std::process::exit(CLAP_USAGE_EXIT_CODE);
}
let cargo_make_cargo_profile = match env::var(CARGO_MAKE_PROFILE_ENV_VAR)
.unwrap_or_else(|_| panic!("{CARGO_MAKE_PROFILE_ENV_VAR} should be set by cargo-make"))
.as_str()
{
"release" => {
// cargo-make release profile sets the `--profile release` flag
if let Some(profile) = &profile {
if profile != "release" {
eprintln!(
"Specifying `--profile release` for cargo-make conflicts with the \
setting `--profile {profile}` to forward to tasks"
);
std::process::exit(CLAP_USAGE_EXIT_CODE);
}
}
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
"--profile release",
);
"release".to_string()
}
_ => {
// All other cargo-make profiles do not set a specific cargo profile. Cargo
// profiles set by --release, --profile <PROFILE>, or -p <PROFILE> (after
// the cargo-make task name) are forwarded to cargo
// commands
if *release {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
"--release",
);
"release".to_string()
} else if let Some(profile) = &profile {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
format!("--profile {profile}").as_str(),
);
profile.into()
} else {
env::var(CARGO_MAKE_CARGO_PROFILE_ENV_VAR).unwrap_or_else(|_| {
panic!("{CARGO_MAKE_CARGO_PROFILE_ENV_VAR} should be set by cargo-make")
})
}
}
};
env::set_var(CARGO_MAKE_CARGO_PROFILE_ENV_VAR, &cargo_make_cargo_profile);
if let Some(jobs) = &jobs {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
format!("--jobs {jobs}").as_str(),
);
}
if let Some(target) = &target {
env::set_var(CARGO_MAKE_CRATE_TARGET_TRIPLE_ENV_VAR, target);
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
format!("--target {target}").as_str(),
);
}
configure_wdf_build_output_dir(target.as_ref(), &cargo_make_cargo_profile);
if let Some(timings_option) = &timings {
timings_option.as_ref().map_or_else(
|| {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
"--timings",
);
},
|timings_value| {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
format!("--timings {timings_value}").as_str(),
);
},
);
}
}
}
impl ParseCargoArgs for ManifestOptions {
fn parse_cargo_args(&self) {
let Self {
frozen,
locked,
offline,
} = self;
if *frozen {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
"--frozen",
);
}
if *locked {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
"--locked",
);
}
if *offline {
append_to_space_delimited_env_var(
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
"--offline",
);
}
}
}
/// Parses the command line arguments, validates that they are supported by
/// `rust-driver-makefile.toml`, and then returns a list of environment variable
/// names that were updated.
///
/// These environment variable names should be passed to
/// [`forward_printed_env_vars`] to forward values to cargo-make.
///
/// # Panics
///
/// This function will panic if there's an internal error (i.e. bug) in its
/// argument processing.
#[must_use]
pub fn validate_command_line_args() -> impl IntoIterator<Item = String> {
const TOOLCHAIN_ARG_POSITION: usize = 1;
let mut env_args = env::args_os().collect::<Vec<_>>();
// +<toolchain> is a special argument that can't currently be handled by clap parsing: https://github.com/clap-rs/clap/issues/2468
let toolchain_arg = if env_args
.get(TOOLCHAIN_ARG_POSITION)
.is_some_and(|arg| arg.to_string_lossy().starts_with('+'))
{
Some(
env_args
.remove(TOOLCHAIN_ARG_POSITION)
.to_string_lossy()
.strip_prefix('+')
.expect("Toolchain arg should have a + prefix")
.to_string(),
)
} else {
None
};
if let Some(toolchain) = toolchain_arg {
env::set_var(CARGO_MAKE_RUST_DEFAULT_TOOLCHAIN_ENV_VAR, toolchain);
}
CommandLineInterface::parse_from(env_args.iter()).parse_cargo_args();
[
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS_ENV_VAR,
CARGO_MAKE_CARGO_PROFILE_ENV_VAR,
CARGO_MAKE_CRATE_TARGET_TRIPLE_ENV_VAR,
CARGO_MAKE_RUST_DEFAULT_TOOLCHAIN_ENV_VAR,
WDK_BUILD_OUTPUT_DIRECTORY_ENV_VAR,
]
.into_iter()
.filter(|env_var_name| env::var_os(env_var_name).is_some())
.map(std::string::ToString::to_string)
}
/// Prepends the path variable with the necessary paths to access WDK tools
///
/// # Errors
///
/// This function returns a [`ConfigError::WdkContentRootDetectionError`] if the
/// WDK content root directory could not be found.
///
/// # Panics
///
/// This function will panic if the CPU architecture cannot be determined from
/// [`env::consts::ARCH`] or if the PATH variable contains non-UTF8
/// characters.
pub fn setup_path() -> Result<impl IntoIterator<Item = String>, ConfigError> {
let Some(wdk_content_root) = detect_wdk_content_root() else {
return Err(ConfigError::WdkContentRootDetectionError);
};
let version = get_latest_windows_sdk_version(&wdk_content_root.join("Lib"))?;
let host_arch = CpuArchitecture::try_from_cargo_str(env::consts::ARCH)
.expect("The rust standard library should always set env::consts::ARCH");
let wdk_bin_root = wdk_content_root
.join(format!("bin/{version}"))
.canonicalize()?
.strip_extended_length_path_prefix()?;
let host_windows_sdk_ver_bin_path = match host_arch {
CpuArchitecture::Amd64 => wdk_bin_root
.join(host_arch.as_windows_str())
.canonicalize()?
.strip_extended_length_path_prefix()?
.to_str()
.expect("x64 host_windows_sdk_ver_bin_path should only contain valid UTF8")
.to_string(),
CpuArchitecture::Arm64 => wdk_bin_root
.join(host_arch.as_windows_str())
.canonicalize()?
.strip_extended_length_path_prefix()?
.to_str()
.expect("ARM64 host_windows_sdk_ver_bin_path should only contain valid UTF8")
.to_string(),
};
// Some tools (ex. inf2cat) are only available in the x86 folder
let x86_windows_sdk_ver_bin_path = wdk_bin_root
.join("x86")
.canonicalize()?
.strip_extended_length_path_prefix()?
.to_str()
.expect("x86_windows_sdk_ver_bin_path should only contain valid UTF8")
.to_string();
prepend_to_semicolon_delimited_env_var(
PATH_ENV_VAR,
// By putting host path first, host versions of tools are prioritized over
// x86 versions
format!("{host_windows_sdk_ver_bin_path};{x86_windows_sdk_ver_bin_path}",),
);
let wdk_tool_root = wdk_content_root
.join(format!("Tools/{version}"))
.canonicalize()?
.strip_extended_length_path_prefix()?;
let arch_specific_wdk_tool_root = wdk_tool_root
.join(host_arch.as_windows_str())
.canonicalize()?
.strip_extended_length_path_prefix()?;
prepend_to_semicolon_delimited_env_var(
PATH_ENV_VAR,
arch_specific_wdk_tool_root
.to_str()
.expect("arch_specific_wdk_tool_root should only contain valid UTF8"),
);
Ok([PATH_ENV_VAR].map(std::string::ToString::to_string))
}
/// Forwards the specified environment variables in this process to the parent
/// cargo-make. This is facilitated by printing to `stdout`, and having the
/// `rust-env-update` plugin parse the printed output.
///
/// # Panics
///
/// Panics if any of the `env_vars` do not exist or contain a non-UTF8 value.
pub fn forward_printed_env_vars(env_vars: impl IntoIterator<Item = impl AsRef<str>>) {
// This print signifies the start of the forwarding and signals to the
// `rust-env-update` plugin that it should forward args
println!("FORWARDING ARGS TO CARGO-MAKE:");
for env_var_name in env_vars {
let env_var_name = env_var_name.as_ref();
// Since this executes in a child process to cargo-make, we need to forward the
// values we want to change to duckscript, in order to get it to modify the
// parent process (ie. cargo-make)
println!(
"{env_var_name}={}",
env::var(env_var_name).unwrap_or_else(|_| panic!(
"{env_var_name} should be the name of an environment variable that is set and \
contains a valid UTF-8 value"
))
);
}
// This print signifies the end of the forwarding and signals to the
// `rust-env-update` plugin that it should stop forwarding args
println!("END OF FORWARDING ARGS TO CARGO-MAKE");
}
/// Adds the WDK version to the environment in the full string form of
/// 10.xxx.yyy.zzz, where x, y, and z are numerical values.
///
/// # Errors
///
/// This function returns a [`ConfigError::WdkContentRootDetectionError`] if the
/// WDK content root directory could not be found, or if the WDK version is
/// ill-formed.
pub fn setup_wdk_version() -> Result<impl IntoIterator<Item = String>, ConfigError> {
let Some(wdk_content_root) = detect_wdk_content_root() else {
return Err(ConfigError::WdkContentRootDetectionError);
};
let detected_sdk_version = get_latest_windows_sdk_version(&wdk_content_root.join("Lib"))?;
if let Ok(existing_version) = std::env::var(WDK_VERSION_ENV_VAR) {
if detected_sdk_version == existing_version {
// Skip updating. This can happen in certain recursive
// cargo-make cases.
return Ok([WDK_VERSION_ENV_VAR].map(std::string::ToString::to_string));
}
// We have a bad version string set somehow. Return an error.
return Err(ConfigError::WdkContentRootDetectionError);
}
if !crate::utils::validate_wdk_version_format(&detected_sdk_version) {
return Err(ConfigError::WdkVersionStringFormatError {
version: detected_sdk_version,
});
}
env::set_var(WDK_VERSION_ENV_VAR, detected_sdk_version);
Ok([WDK_VERSION_ENV_VAR].map(std::string::ToString::to_string))
}
/// Sets the `WDK_INFVERIF_SAMPLE_FLAG` environment variable to contain the
/// appropriate flag for building samples.
///
/// # Errors
///
/// This function returns a [`ConfigError::WdkContentRootDetectionError`] if
/// an invalid WDK version is provided.
///
/// # Panics
///
/// This function will panic if the function for validating a WDK version string
/// is ever changed to no longer validate that each part of the version string
/// is an i32.
pub fn setup_infverif_for_samples<S: AsRef<str> + ToString + ?Sized>(
version: &S,
) -> Result<impl IntoIterator<Item = String>, ConfigError> {
let validated_version_string = crate::utils::get_wdk_version_number(version)?;
// Safe to unwrap as we called .parse::<i32>().is_ok() in our call to
// validate_wdk_version_format above.
let version = validated_version_string
.parse::<i32>()
.expect("Unable to parse the build number of the WDK version string as an int!");
let sample_flag = if version > MINIMUM_SAMPLES_FLAG_WDK_VERSION {
"/samples" // Note: Not currently implemented, so in samples TOML we
// currently skip infverif
} else {
"/msft"
};
append_to_space_delimited_env_var(WDK_INF_ADDITIONAL_FLAGS_ENV_VAR, sample_flag);
Ok([WDK_INF_ADDITIONAL_FLAGS_ENV_VAR].map(std::string::ToString::to_string))
}
/// Returns the path to the WDK build output directory for the current
/// cargo-make flow
///
/// # Panics
///
/// This function will panic if the `WDK_BUILD_OUTPUT_DIRECTORY` environment
/// variable is not set
#[must_use]
pub fn get_wdk_build_output_directory() -> PathBuf {
PathBuf::from(
env::var("WDK_BUILD_OUTPUT_DIRECTORY")
.expect("WDK_BUILD_OUTPUT_DIRECTORY should have been set by the wdk-build-init task"),
)
}
/// Returns the name of the current cargo package cargo-make is processing
///
/// # Panics
///
/// This function will panic if the `CARGO_MAKE_CRATE_FS_NAME` environment
/// variable is not set
#[must_use]
pub fn get_current_package_name() -> String {
env::var(CARGO_MAKE_CRATE_FS_NAME_ENV_VAR).unwrap_or_else(|_| {
panic!(
"{} should be set by cargo-make",
&CARGO_MAKE_CRATE_FS_NAME_ENV_VAR
)
})
}
/// Copies the file or directory at `path_to_copy` to the Driver Package folder
///
/// # Errors
///
/// This function returns a [`ConfigError::IoError`] if the it encouters IO
/// errors while copying the file or creating the directory
///
/// # Panics
///
/// This function will panic if `path_to_copy` does end with a valid file or
/// directory name
pub fn copy_to_driver_package_folder<P: AsRef<Path>>(path_to_copy: P) -> Result<(), ConfigError> {
let path_to_copy = path_to_copy.as_ref();
let package_folder_path: PathBuf =
get_wdk_build_output_directory().join(format!("{}_package", get_current_package_name()));
if !package_folder_path.exists() {
std::fs::create_dir(&package_folder_path)?;
}
let destination_path = package_folder_path.join(
path_to_copy
.file_name()
.expect("path_to_copy should always end with a valid file or directory name"),
);
std::fs::copy(path_to_copy, destination_path)?;
Ok(())
}
/// Symlinks `rust-driver-makefile.toml` to the `target` folder where it can be
/// extended from a `Makefile.toml`.
///
/// This is necessary so that paths in the `rust-driver-makefile.toml` can to be
/// relative to `CARGO_MAKE_CURRENT_TASK_INITIAL_MAKEFILE_DIRECTORY`
///
/// # Errors
///
/// This function returns:
/// - [`ConfigError::CargoMetadataError`] if there is an error executing or
/// parsing `cargo_metadata`
/// - [`ConfigError::MultipleWdkBuildCratesDetected`] if there are multiple
/// versions of the WDK build crate detected
/// - [`ConfigError::IoError`] if there is an error creating or updating the
/// symlink to `rust-driver-makefile.toml`
///
/// # Panics
///
/// This function will panic if the `CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY`
/// environment variable is not set
pub fn load_rust_driver_makefile() -> Result<(), ConfigError> {
load_wdk_build_makefile(RUST_DRIVER_MAKEFILE_NAME)
}
/// Symlinks `rust-driver-sample-makefile.toml` to the `target` folder where it
/// can be extended from a `Makefile.toml`.
///
/// This is necessary so that paths in the `rust-driver-sample-makefile.toml`
/// can to be relative to `CARGO_MAKE_CURRENT_TASK_INITIAL_MAKEFILE_DIRECTORY`
///
/// # Errors
///
/// This function returns:
/// - [`ConfigError::CargoMetadataError`] if there is an error executing or
/// parsing `cargo_metadata`
/// - [`ConfigError::MultipleWdkBuildCratesDetected`] if there are multiple
/// versions of the WDK build crate detected
/// - [`ConfigError::IoError`] if there is an error creating or updating the
/// symlink to `rust-driver-sample-makefile.toml`
///
/// # Panics
///
/// This function will panic if the `CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY`
/// environment variable is not set
pub fn load_rust_driver_sample_makefile() -> Result<(), ConfigError> {
load_wdk_build_makefile(RUST_DRIVER_SAMPLE_MAKEFILE_NAME)
}
/// Symlinks a [`wdk_build`] `cargo-make` makefile to the `target` folder where
/// it can be extended from a downstream `Makefile.toml`.
///
/// This is necessary so that paths in the [`wdk_build`] makefile can be
/// relative to `CARGO_MAKE_CURRENT_TASK_INITIAL_MAKEFILE_DIRECTORY`. The
/// version of `wdk-build` from which the file being symlinked to comes from is
/// determined by the workding directory of the process that invokes this
/// function. For example, if this function is ultimately executing in a
/// `cargo_make` `load_script`, the files will be symlinked from the `wdk-build`
/// version that is in the `.Cargo.lock` file, and not the `wdk-build` version
/// specified in the `load_script`.
///
/// # Errors
///
/// This function returns:
/// - [`ConfigError::CargoMetadataError`] if there is an error executing or
/// parsing `cargo_metadata`
/// - [`ConfigError::MultipleWdkBuildCratesDetected`] if there are multiple
/// versions of the WDK build crate detected
/// - [`ConfigError::IoError`] if there is an error creating or updating the
/// symlink to the makefile.
///
/// # Panics
///
/// This function will panic if the `CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY`
/// environment variable is not set
#[instrument(level = "trace")]
fn load_wdk_build_makefile<S: AsRef<str> + AsRef<Utf8Path> + AsRef<Path> + fmt::Debug>(
makefile_name: S,
) -> Result<(), ConfigError> {
let cargo_metadata = MetadataCommand::new().exec()?;
trace!(cargo_metadata_output = ?cargo_metadata);
let wdk_build_package_matches = cargo_metadata
.packages
.into_iter()
.filter(|package| package.name == "wdk-build")
.collect::<Vec<_>>();
if wdk_build_package_matches.len() != 1 {
return Err(ConfigError::MultipleWdkBuildCratesDetected {
package_ids: wdk_build_package_matches
.iter()
.map(|package_info| package_info.id.clone())
.collect(),
});
}
let rust_driver_makefile_toml_path = wdk_build_package_matches[0]
.manifest_path
.parent()
.expect("The parsed manifest_path should have a valid parent directory")
.join(&makefile_name);
let cargo_make_workspace_working_directory =
env::var(CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY_ENV_VAR).unwrap_or_else(|_| {
panic!("{CARGO_MAKE_WORKSPACE_WORKING_DIRECTORY_ENV_VAR} should be set by cargo-make")
});
let destination_path = Path::new(&cargo_make_workspace_working_directory)
.join("target")
.join(&makefile_name);
// Only create a new symlink if the existing one is not already pointing to the
// correct file
if !destination_path.exists() {
return Ok(std::os::windows::fs::symlink_file(
rust_driver_makefile_toml_path,
destination_path,
)?);
} else if !destination_path.is_symlink()
|| std::fs::read_link(&destination_path)? != rust_driver_makefile_toml_path
{
std::fs::remove_file(&destination_path)?;
return Ok(std::os::windows::fs::symlink_file(
rust_driver_makefile_toml_path,
destination_path,
)?);
}
// Symlink is already up to date
Ok(())
}
/// Get [`cargo_metadata::Metadata`] based off of manifest in
/// `CARGO_MAKE_WORKING_DIRECTORY`
///
/// # Errors
///
/// This function will return a [`cargo_metadata::Error`] if `cargo_metadata`
/// fails
///
/// # Panics
///
/// This function will panic if executed outside of a `cargo-make` task
pub fn get_cargo_metadata() -> cargo_metadata::Result<Metadata> {
let manifest_path = {
let mut p: PathBuf = std::path::PathBuf::from(
std::env::var("CARGO_MAKE_WORKING_DIRECTORY")
.expect("CARGO_MAKE_WORKING_DIRECTORY should be set by cargo-make"),
);
p.push("Cargo.toml");
p
};
cargo_metadata::MetadataCommand::new()
.manifest_path(manifest_path)
.exec()
}
/// Execute a `FnOnce` closure, and handle its contents in a way compatible with
/// `cargo-make`'s `condition_script`:
/// 1. If the closure panics, the panic is caught and it returns an `Ok(())`.
/// This ensures that panics encountered in `condition_script_closure` will
/// not default to skipping the task.
/// 2. If the closure executes without panicking, forward the result to
/// `cargo-make`. `Ok` types will result in the task being run, and `Err`
/// types will print the `Err` contents and then skip the task.
///
/// If you want your task to be skipped, return an `Err` from
/// `condition_script_closure`. If you want the task to execute, return an
/// `Ok(())` from `condition_script_closure`
///
/// # Errors
///
/// This function returns an error whenever `condition_script_closure` returns
/// an error
///
/// # Panics
///
/// Panics if `CARGO_MAKE_CURRENT_TASK_NAME` is not set in the environment
pub fn condition_script<F, E>(condition_script_closure: F) -> anyhow::Result<(), E>
where
F: FnOnce() -> anyhow::Result<(), E> + UnwindSafe,
{
std::panic::catch_unwind(condition_script_closure).unwrap_or_else(|_| {
// Note: Any panic messages has already been printed by this point
let cargo_make_task_name = env::var(CARGO_MAKE_CURRENT_TASK_NAME_ENV_VAR)
.expect("CARGO_MAKE_CURRENT_TASK_NAME should be set by cargo-make");
eprintln!(
r#"`condition_script` for "{cargo_make_task_name}" task panicked while executing. \
Defaulting to running "{cargo_make_task_name}" task."#
);
Ok(())
})
}
/// `cargo-make` condition script for `package-driver-flow` task in
/// [`rust-driver-makefile.toml`](../rust-driver-makefile.toml)
///
/// # Errors
///
/// This function returns an error whenever it determines that the
/// `package-driver-flow` `cargo-make` task should be skipped (i.e. when the
/// current package isn't a cdylib depending on the WDK, or when no valid WDK
/// configurations are detected)
///
/// # Panics
///
/// Panics if `CARGO_MAKE_CRATE_NAME` is not set in the environment
pub fn package_driver_flow_condition_script() -> anyhow::Result<()> {
condition_script(|| {
// Get the current package name via `CARGO_MAKE_CRATE_NAME_ENV_VAR` instead of
// `CARGO_MAKE_CRATE_FS_NAME_ENV_VAR`, since `cargo_metadata` output uses the
// non-preprocessed name (ie. - instead of _)
let current_package_name = env::var(CARGO_MAKE_CRATE_NAME_ENV_VAR).unwrap_or_else(|_| {
panic!(
"{} should be set by cargo-make",
&CARGO_MAKE_CRATE_NAME_ENV_VAR
)
});
let cargo_metadata = get_cargo_metadata()?;
// Skip task if the current crate is not a driver (i.e. a cdylib with a
// `package.metadata.wdk` section)
let current_package = cargo_metadata
.packages
.iter()
.find(|package| package.name == current_package_name)
.expect("The current package should be present in the cargo metadata output");
if current_package.metadata["wdk"].is_null() {
return Err::<(), anyhow::Error>(
metadata::TryFromCargoMetadataError::NoWdkConfigurationsDetected.into(),
)
.with_context(|| {
"Skipping package-driver-flow cargo-make task because the current crate does not \
have a package.metadata.wdk section"
});
}
if !current_package
.targets
.iter()
.any(|target| target.kind.iter().any(|kind| kind == "cdylib"))
{
return Err::<(), anyhow::Error>(
metadata::TryFromCargoMetadataError::NoWdkConfigurationsDetected.into(),
)
.with_context(|| {
"Skipping package-driver-flow cargo-make task because the current crate does not \
contain a cdylib target"
});
}
match metadata::Wdk::try_from(&cargo_metadata) {
Err(e @ metadata::TryFromCargoMetadataError::NoWdkConfigurationsDetected) => {
// Skip task only if no WDK configurations are detected
Err::<(), anyhow::Error>(e.into()).with_context(|| {
"Skipping package-driver-flow cargo-make task because the current crate is not \
a driver"
})
}
Ok(_) => Ok(()),