Debian Codegraph @

third_party/rust/uniffi_bindgen/src/bindings/swift/test.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use crate::bindings::RunScriptOptions;
6 use crate::cargo_metadata::CrateConfigSupplier;
7 use crate::library_mode::generate_bindings;
8
9 use anyhow::{bail, Context, Result};
10 use camino::{Utf8Path, Utf8PathBuf};
11 use cargo_metadata::Metadata;
12 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
13 use std::ffi::OsStr;
14 use std::fs::{read_to_string, File};
15 use std::io::Write;
16 use std::process::{Command, Stdio};
17 use uniffi_testing::UniFFITestHelper;
18
19 /// Run Swift tests for a UniFFI test fixture
20 pub fn run_test(tmp_dir: &str, package_name: &str, script_file: &str) -> Result<()> {
21 run_script(
22 tmp_dir,
23 package_name,
24 script_file,
25 vec![],
26 &RunScriptOptions::default(),
27 )
28 }
29
30 /// Run a Swift script
31 ///
32 /// This function will set things up so that the script can import the UniFFI bindings for a crate
33 pub fn run_script(
34 tmp_dir: &str,
35 package_name: &str,
36 script_file: &str,
37 args: Vec<String>,
38 options: &RunScriptOptions,
39 ) -> Result<()> {
40 let script_path = Utf8Path::new(script_file).canonicalize_utf8()?;
41 let test_helper = UniFFITestHelper::new(package_name)?;
42 let out_dir = test_helper.create_out_dir(tmp_dir, &script_path)?;
43 let cdylib_path = test_helper.copy_cdylib_to_out_dir(&out_dir)?;
44 let generated_sources = GeneratedSources::new(
45 test_helper.crate_name(),
46 &cdylib_path,
47 test_helper.cargo_metadata(),
48 &out_dir,
49 )?;
50
51 // We need something better than this env var, but it's a reasonable start.
52 let swift_version = std::env::var("UNIFFI_TEST_SWIFT_VERSION").unwrap_or("5".to_string());
53
54 // Compile the generated sources together to create a single swift module
55 compile_swift_module(
56 &out_dir,
57 &generated_sources.main_module,
58 &generated_sources.generated_swift_files,
59 &generated_sources.module_map,
60 &swift_version,
61 options,
62 )?;
63
64 // Run the test script against compiled bindings
65 let mut command = create_command("swift", options);
66 command
67 .current_dir(&out_dir)
68 .arg("-I")
69 .arg(&out_dir)
70 .arg("-L")
71 .arg(&out_dir)
72 .args(calc_library_args(&out_dir)?)
73 .arg("-swift-version")
74 .arg(swift_version)
75 .arg("-Xcc")
76 .arg(format!(
77 "-fmodule-map-file={}",
78 generated_sources.module_map
79 ))
80 .arg(&script_path)
81 .args(args);
82 let status = command
83 .spawn()
84 .context("Failed to spawn `swiftc` when running test script")?
85 .wait()
86 .context("Failed to wait for `swiftc` when running test script")?;
87 if !status.success() {
88 bail!("running `swift` to run test script failed ({:?})", command)
89 }
90 Ok(())
91 }
92
93 fn compile_swift_module<T: AsRef<OsStr>>(
94 out_dir: &Utf8Path,
95 module_name: &str,
96 sources: impl IntoIterator<Item = T>,
97 module_map: &Utf8Path,
98 swift_version: &str,
99 options: &RunScriptOptions,
100 ) -> Result<()> {
101 let output_filename = format!("{DLL_PREFIX}testmod_{module_name}{DLL_SUFFIX}");
102 let mut command = create_command("swiftc", options);
103 command
104 .current_dir(out_dir)
105 .arg("-emit-module")
106 // TODO(2279): Fix concurrency issues and uncomment this
107 //.arg("-strict-concurrency=complete")
108 .arg("-module-name")
109 .arg(module_name)
110 .arg("-o")
111 .arg(output_filename)
112 .arg("-emit-library")
113 .arg("-swift-version")
114 .arg(swift_version)
115 .arg("-Xcc")
116 .arg(format!("-fmodule-map-file={module_map}"))
117 .arg("-I")
118 .arg(out_dir)
119 .arg("-L")
120 .arg(out_dir)
121 .args(calc_library_args(out_dir)?)
122 .args(sources);
123 let status = command
124 .spawn()
125 .context("Failed to spawn `swiftc` when compiling bindings")?
126 .wait()
127 .context("Failed to wait for `swiftc` when compiling bindings")?;
128 if !status.success() {
129 bail!(
130 "running `swiftc` to compile bindings failed ({:?})",
131 command
132 )
133 };
134 Ok(())
135 }
136
137 // Stores sources generated by `uniffi-bindgen-swift`
138 struct GeneratedSources {
139 main_module: String,
140 generated_swift_files: Vec<Utf8PathBuf>,
141 module_map: Utf8PathBuf,
142 }
143
144 impl GeneratedSources {
145 fn new(
146 crate_name: &str,
147 cdylib_path: &Utf8Path,
148 cargo_metadata: Metadata,
149 out_dir: &Utf8Path,
150 ) -> Result<Self> {
151 let sources = generate_bindings(
152 cdylib_path,
153 None,
154 &super::SwiftBindingGenerator,
155 &CrateConfigSupplier::from(cargo_metadata),
156 None,
157 out_dir,
158 false,
159 )?;
160 let main_source = sources
161 .iter()
162 .find(|s| s.ci.crate_name() == crate_name)
163 .unwrap();
164 let main_module = main_source.config.module_name();
165 let modulemap_glob = glob(&out_dir.join("*.modulemap"))?;
166 let module_map = match modulemap_glob.len() {
167 0 => bail!("No modulemap files found in {out_dir}"),
168 // Normally we only generate 1 module map and can return it directly
169 1 => modulemap_glob.into_iter().next().unwrap(),
170 // When we use multiple UDL files in a test, for example the ext-types fixture,
171 // then we get multiple module maps and need to combine them
172 _ => {
173 let path = out_dir.join("combined.modulemap");
174 let mut f = File::create(&path)?;
175 write!(
176 f,
177 "{}",
178 modulemap_glob
179 .into_iter()
180 .map(|path| Ok(read_to_string(path)?))
181 .collect::<Result<Vec<String>>>()?
182 .join("\n")
183 )?;
184 path
185 }
186 };
187
188 Ok(GeneratedSources {
189 main_module,
190 generated_swift_files: glob(&out_dir.join("*.swift"))?,
191 module_map,
192 })
193 }
194 }
195
196 fn create_command(program: &str, options: &RunScriptOptions) -> Command {
197 let mut command = Command::new(program);
198 if !options.show_compiler_messages {
199 // This prevents most compiler messages, but not remarks
200 command.arg("-suppress-warnings");
201 // This gets the remarks. Note: swift will eventually get a `-suppress-remarks` argument,
202 // maybe we can eventually move to that
203 command.stderr(Stdio::null());
204 }
205 command
206 }
207
208 // Wraps glob to use Utf8Paths and flattens errors
209 fn glob(globspec: &Utf8Path) -> Result<Vec<Utf8PathBuf>> {
210 glob::glob(globspec.as_str())?
211 .map(|globresult| Ok(Utf8PathBuf::try_from(globresult?)?))
212 .collect()
213 }
214
215 fn calc_library_args(out_dir: &Utf8Path) -> Result<Vec<String>> {
216 let results = glob::glob(out_dir.join(format!("{DLL_PREFIX}*{DLL_SUFFIX}")).as_str())?;
217 results
218 .map(|globresult| {
219 let path = Utf8PathBuf::try_from(globresult.unwrap())?;
220 Ok(format!(
221 "-l{}",
222 path.file_name()
223 .unwrap()
224 .strip_prefix(DLL_PREFIX)
225 .unwrap()
226 .strip_suffix(DLL_SUFFIX)
227 .unwrap()
228 ))
229 })
230 .collect()
231 }