blob: 6803e8b9f08a6f35522c965130ed76bad32acc74 [file] [log] [blame]
Brian Silvermancc09f182022-03-09 15:40:20 -08001//! A utility for writing scripts for use as test executables intended to match the
2//! subcommands of Bazel build actions so `rustdoc --test`, which builds and tests
3//! code in a single call, can be run as a test target in a hermetic manner.
4
5use std::cmp::Reverse;
6use std::collections::{BTreeMap, BTreeSet};
7use std::env;
8use std::fs;
9use std::path::{Path, PathBuf};
10
11#[derive(Debug)]
12struct Options {
13 /// A list of environment variable keys to parse from the build action env.
14 env_keys: BTreeSet<String>,
15
16 /// A list of substrings to strip from [Options::action_argv].
17 strip_substrings: Vec<String>,
18
19 /// The path where the script should be written.
20 output: PathBuf,
21
22 /// The `argv` of the configured rustdoc build action.
23 action_argv: Vec<String>,
24}
25
26/// Parse command line arguments
27fn parse_args() -> Options {
28 let args: Vec<String> = env::args().into_iter().collect();
29 let (writer_args, action_args) = {
30 let split = args
31 .iter()
32 .position(|arg| arg == "--")
33 .expect("Unable to find split identifier `--`");
34
35 // Converting each set into a vector makes them easier to parse in
36 // the absence of nightly features
37 let (writer, action) = args.split_at(split);
38 (writer.to_vec(), action.to_vec())
39 };
40
41 // Remove the leading `--` which is expected to be the first
42 // item in `action_args`
43 debug_assert_eq!(action_args[0], "--");
44 let action_argv = action_args[1..].to_vec();
45
46 let output = writer_args
47 .iter()
48 .find(|arg| arg.starts_with("--output="))
49 .and_then(|arg| arg.splitn(2, '=').last())
50 .map(PathBuf::from)
51 .expect("Missing `--output` argument");
52
53 let (strip_substring_args, writer_args): (Vec<String>, Vec<String>) = writer_args
54 .into_iter()
55 .partition(|arg| arg.starts_with("--strip_substring="));
56
57 let mut strip_substrings: Vec<String> = strip_substring_args
58 .into_iter()
59 .map(|arg| {
60 arg.splitn(2, '=')
61 .last()
62 .expect("--strip_substring arguments must have assignments using `=`")
63 .to_owned()
64 })
65 .collect();
66
67 // Strip substrings should always be in reverse order of the length of each
68 // string so when filtering we know that the longer strings are checked
69 // first in order to avoid cases where shorter strings might match longer ones.
70 strip_substrings.sort_by_key(|b| Reverse(b.len()));
71 strip_substrings.dedup();
72
73 let env_keys = writer_args
74 .into_iter()
75 .filter(|arg| arg.starts_with("--action_env="))
76 .map(|arg| {
77 arg.splitn(2, '=')
78 .last()
79 .expect("--env arguments must have assignments using `=`")
80 .to_owned()
81 })
82 .collect();
83
84 Options {
85 env_keys,
86 strip_substrings,
87 output,
88 action_argv,
89 }
90}
91
92/// Write a unix compatible test runner
93fn write_test_runner_unix(
94 path: &Path,
95 env: &BTreeMap<String, String>,
96 argv: &[String],
97 strip_substrings: &[String],
98) {
99 let mut content = vec![
100 "#!/usr/bin/env bash".to_owned(),
101 "".to_owned(),
102 "exec env - \\".to_owned(),
103 ];
104
105 content.extend(env.iter().map(|(key, val)| format!("{}='{}' \\", key, val)));
106
107 let argv_str = argv
108 .iter()
109 // Remove any substrings found in the argument
110 .map(|arg| {
111 let mut stripped_arg = arg.to_owned();
112 strip_substrings
113 .iter()
114 .for_each(|substring| stripped_arg = stripped_arg.replace(substring, ""));
115 stripped_arg
116 })
117 .map(|arg| format!("'{}'", arg))
118 .collect::<Vec<String>>()
119 .join(" ");
120
121 content.extend(vec![argv_str, "".to_owned()]);
122
123 fs::write(path, content.join("\n")).expect("Failed to write test runner");
124}
125
126/// Write a windows compatible test runner
127fn write_test_runner_windows(
128 path: &Path,
129 env: &BTreeMap<String, String>,
130 argv: &[String],
131 strip_substrings: &[String],
132) {
133 let env_str = env
134 .iter()
135 .map(|(key, val)| format!("$env:{}='{}'", key, val))
136 .collect::<Vec<String>>()
137 .join(" ; ");
138
139 let argv_str = argv
140 .iter()
141 // Remove any substrings found in the argument
142 .map(|arg| {
143 let mut stripped_arg = arg.to_owned();
144 strip_substrings
145 .iter()
146 .for_each(|substring| stripped_arg = stripped_arg.replace(substring, ""));
147 stripped_arg
148 })
149 .map(|arg| format!("'{}'", arg))
150 .collect::<Vec<String>>()
151 .join(" ");
152
153 let content = vec![
154 "@ECHO OFF".to_owned(),
155 "".to_owned(),
156 format!("powershell.exe -c \"{} ; & {}\"", env_str, argv_str),
157 "".to_owned(),
158 ];
159
160 fs::write(path, content.join("\n")).expect("Failed to write test runner");
161}
162
163#[cfg(target_family = "unix")]
164fn set_executable(path: &Path) {
165 use std::os::unix::prelude::PermissionsExt;
166
167 let mut perm = fs::metadata(path)
168 .expect("Failed to get test runner metadata")
169 .permissions();
170
171 perm.set_mode(0o755);
172 fs::set_permissions(path, perm).expect("Failed to set permissions on test runner");
173}
174
175#[cfg(target_family = "windows")]
176fn set_executable(_path: &Path) {
177 // Windows determines whether or not a file is executable via the PATHEXT
178 // environment variable. This function is a no-op for this platform.
179}
180
181fn write_test_runner(
182 path: &Path,
183 env: &BTreeMap<String, String>,
184 argv: &[String],
185 strip_substrings: &[String],
186) {
187 if cfg!(target_family = "unix") {
188 write_test_runner_unix(path, env, argv, strip_substrings);
189 } else if cfg!(target_family = "windows") {
190 write_test_runner_windows(path, env, argv, strip_substrings);
191 }
192
193 set_executable(path);
194}
195
196fn main() {
197 let opt = parse_args();
198
199 let env: BTreeMap<String, String> = env::vars()
200 .into_iter()
201 .filter(|(key, _)| opt.env_keys.iter().any(|k| k == key))
202 .collect();
203
204 write_test_runner(&opt.output, &env, &opt.action_argv, &opt.strip_substrings);
205}