Finish writing before handing the file URL to an asynchronous browser. The unique automatic file survives process exit and browser-launch failure.
(
html: &str,
output: Option<&std::path::Path>,
open_browser: impl FnOnce(&str) -> std::io::Result<()>,
)
| 5 | /// Finish writing before handing the file URL to an asynchronous browser. The |
| 6 | /// unique automatic file survives process exit and browser-launch failure. |
| 7 | pub(crate) fn write_and_open_html( |
| 8 | html: &str, |
| 9 | output: Option<&std::path::Path>, |
| 10 | open_browser: impl FnOnce(&str) -> std::io::Result<()>, |
| 11 | ) -> CliResult<std::path::PathBuf> { |
| 12 | use std::io::Write; |
| 13 | let path = match output { |
| 14 | Some(path) => { |
| 15 | std::fs::write(path, html)?; |
| 16 | path.to_path_buf() |
| 17 | } |
| 18 | None => { |
| 19 | let path = |
| 20 | std::env::temp_dir().join(format!("atomic-report-{}.html", uuid::Uuid::new_v4())); |
| 21 | let mut file = std::fs::OpenOptions::new() |
| 22 | .write(true) |
| 23 | .create_new(true) |
| 24 | .open(&path)?; |
| 25 | file.write_all(html.as_bytes())?; |
| 26 | path |
| 27 | } |
| 28 | }; |
| 29 | let path = std::fs::canonicalize(path)?; |
| 30 | let url = url::Url::from_file_path(&path).map_err(|_| CliError::InvalidArgument { |
| 31 | message: format!("cannot convert HTML path to a file URL: {}", path.display()), |
| 32 | })?; |
| 33 | println!("Wrote HTML report to {}", path.display()); |
| 34 | if let Err(error) = open_browser(url.as_str()) { |
| 35 | eprintln!("Could not open a browser: {error}. Open {url} manually."); |
| 36 | } |
| 37 | Ok(path) |
| 38 | } |