diff --git a/xtask/src/app_manifest.rs b/xtask/src/app_manifest.rs index 6284d182c..dfcc5024f 100644 --- a/xtask/src/app_manifest.rs +++ b/xtask/src/app_manifest.rs @@ -1,6 +1,5 @@ // This module supports generating the app menus from the JSON manifest in the apps/ directory. -use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, HashMap}; use std::{ fmt::Write as StdWrite, @@ -9,6 +8,8 @@ use std::{ string::String, }; +use serde::{Deserialize, Serialize}; + #[derive(Deserialize, Serialize, Debug)] struct AppManifest { context_name: String, @@ -24,15 +25,13 @@ pub(crate) fn generate_app_menus(apps: &Vec) { let file = File::open("apps/manifest.json").expect("Failed to open the manifest file"); let mut reader = std::io::BufReader::new(file); let mut content = String::new(); - reader - .read_to_string(&mut content) - .expect("Failed to read the file"); + reader.read_to_string(&mut content).expect("Failed to read the file"); let manifest: HashMap = serde_json::from_str(&content).expect("Cannot parse manifest file"); // localization file - // inject all the localization strings into the i18n file, which in theory reduces the churn on other crates that depend - // on the global i18n file between build variants + // inject all the localization strings into the i18n file, which in theory reduces the churn on other + // crates that depend on the global i18n file between build variants let mut l = BTreeMap::>::new(); for (_app, manifest) in manifest.iter() { for (name, translations) in &manifest.menu_name { @@ -58,11 +57,7 @@ pub(crate) fn generate_app_menus(apps: &Vec) { // construct the gam_tokens let mut gam_tokens = String::new(); - writeln!( - gam_tokens, - "// This file is auto-generated by xtask/main.rs generate_app_menus()" - ) - .unwrap(); + writeln!(gam_tokens, "// This file is auto-generated by xtask/main.rs generate_app_menus()").unwrap(); for (app_name, manifest) in working_set.iter() { writeln!( gam_tokens, @@ -85,27 +80,13 @@ pub(crate) fn generate_app_menus(apps: &Vec) { } } } - writeln!( - gam_tokens, - "\npub const EXPECTED_APP_CONTEXTS: &[&'static str] = &[" - ) - .unwrap(); + writeln!(gam_tokens, "\npub const EXPECTED_APP_CONTEXTS: &[&'static str] = &[").unwrap(); for (app_name, manifest) in working_set.iter() { - writeln!( - gam_tokens, - " APP_NAME_{},", - app_name.to_uppercase().replace("-", "_"), - ) - .unwrap(); + writeln!(gam_tokens, " APP_NAME_{},", app_name.to_uppercase().replace("-", "_"),).unwrap(); if let Some(menu_count) = manifest.submenu { for i in 0..menu_count { - writeln!( - gam_tokens, - " APP_MENU_{}_{},", - i, - app_name.to_uppercase().replace("-", "_"), - ) - .unwrap(); + writeln!(gam_tokens, " APP_MENU_{}_{},", i, app_name.to_uppercase().replace("-", "_"),) + .unwrap(); } } } @@ -114,18 +95,16 @@ pub(crate) fn generate_app_menus(apps: &Vec) { // construct the app menu let mut menu = String::new(); - writeln!( - menu, - "// This file is auto-generated by xtask/main.rs generate_app_menus()" - ) - .unwrap(); + writeln!(menu, "// This file is auto-generated by xtask/main.rs generate_app_menus()").unwrap(); if apps.len() == 0 { writeln!(menu, "// NO APPS SELECTED: suppressing warning messages!").unwrap(); writeln!(menu, "#![allow(dead_code)]").unwrap(); writeln!(menu, "#![allow(unused_imports)]").unwrap(); writeln!(menu, "#![allow(unused_variables)]").unwrap(); } - writeln!(menu, r####"use crate::StatusOpcode; + writeln!( + menu, + r####"use crate::StatusOpcode; use gam::{{MenuItem, MenuPayload}}; use locales::t; use num_traits::*; @@ -147,7 +126,9 @@ impl fmt::Display for AppDispatchError {{ }} pub(crate) fn app_dispatch(gam: &gam::Gam, token: [u32; 4], index: usize) -> Result<(), AppDispatchError> {{ - match index {{"####).unwrap(); + match index {{"#### + ) + .unwrap(); for (index, (app_name, _manifest)) in working_set.iter().enumerate() { writeln!( menu, @@ -172,12 +153,7 @@ pub(crate) fn app_index_to_name(index: usize) -> Result<&'static str, AppDispatc .unwrap(); for (index, (_, _manifest)) in working_set.iter().enumerate() { for name in _manifest.menu_name.keys() { - writeln!( - menu, - " {} => Ok(t!(\"{}\", locales::LANG)),", - index, name, - ) - .unwrap(); + writeln!(menu, " {} => Ok(t!(\"{}\", locales::LANG)),", index, name,).unwrap(); } } writeln!( @@ -192,30 +168,14 @@ pub(crate) fn app_menu_items(menu_items: &mut Vec::, status_conn: u32) .unwrap(); for (index, (_app_name, manifest)) in working_set.iter().enumerate() { writeln!(menu, " menu_items.push(MenuItem {{",).unwrap(); - assert!( - manifest.menu_name.len() == 1, - "Improper menu name record entry" - ); + assert!(manifest.menu_name.len() == 1, "Improper menu name record entry"); for name in manifest.menu_name.keys() { - writeln!( - menu, - " name: xous_ipc::String::from_str(t!(\"{}\", locales::LANG)),", - name - ) - .unwrap(); + writeln!(menu, " name: xous_ipc::String::from_str(t!(\"{}\", locales::LANG)),", name) + .unwrap(); } writeln!(menu, " action_conn: Some(status_conn),",).unwrap(); - writeln!( - menu, - " action_opcode: StatusOpcode::SwitchToApp.to_u32().unwrap(),", - ) - .unwrap(); - writeln!( - menu, - " action_payload: MenuPayload::Scalar([{}, 0, 0, 0]),", - index - ) - .unwrap(); + writeln!(menu, " action_opcode: StatusOpcode::SwitchToApp.to_u32().unwrap(),",).unwrap(); + writeln!(menu, " action_payload: MenuPayload::Scalar([{}, 0, 0, 0]),", index).unwrap(); writeln!(menu, " close_on_select: true,",).unwrap(); writeln!(menu, " }});\n",).unwrap(); } @@ -227,9 +187,7 @@ fn overwrite_if_changed(new_string: &String, old_file: &str) { let original = match OpenOptions::new().read(true).open(old_file) { Ok(mut ref_file) => { let mut buf = String::new(); - ref_file - .read_to_string(&mut buf) - .expect("UTF-8 error in previous localization file"); + ref_file.read_to_string(&mut buf).expect("UTF-8 error in previous localization file"); buf } _ => String::new(), diff --git a/xtask/src/builder.rs b/xtask/src/builder.rs index c54291173..66f238bde 100644 --- a/xtask/src/builder.rs +++ b/xtask/src/builder.rs @@ -5,13 +5,14 @@ use std::{ path::{Path, PathBuf}, process::Command, }; -use crate::{DynError, app_manifest::generate_app_menus}; + +use crate::{app_manifest::generate_app_menus, DynError}; #[allow(dead_code)] #[derive(Copy, Clone, Debug)] pub(crate) enum BuildStream { Debug, - Release + Release, } impl BuildStream { pub fn to_str(&self) -> &str { @@ -42,19 +43,23 @@ impl CrateSpec { CrateSpec::CratesIo(_n, _v, xip) => *xip, CrateSpec::Prebuilt(_n, _u, xip) => *xip, CrateSpec::BinaryFile(_n, _path, xip) => *xip, - _ => false + _ => false, } } + pub fn set_xip(&mut self, xip: bool) { *self = match self { //TODO: why do these to_strings need to be here? CrateSpec::Local(s, _xip) => CrateSpec::Local(s.to_string(), xip), CrateSpec::CratesIo(n, v, _xip) => CrateSpec::CratesIo(n.to_string(), v.to_string(), xip), CrateSpec::Prebuilt(n, u, _xip) => CrateSpec::Prebuilt(n.to_string(), u.to_string(), xip), - CrateSpec::BinaryFile(n, path, _xip) => CrateSpec::BinaryFile(n.as_ref().or(None).cloned(), path.to_string(), xip), + CrateSpec::BinaryFile(n, path, _xip) => { + CrateSpec::BinaryFile(n.as_ref().or(None).cloned(), path.to_string(), xip) + } CrateSpec::None => CrateSpec::None, } } + pub fn name(&self) -> Option { match self { CrateSpec::Local(s, _xip) => Some(s.to_string()), @@ -63,11 +68,10 @@ impl CrateSpec { CrateSpec::BinaryFile(n, path, _xip) => { if let Some(name) = n { Some(name.to_string()) - } - else { + } else { Some(path.to_string()) } - }, + } _ => None, } } @@ -77,29 +81,22 @@ impl From<&str> for CrateSpec { // remote crates are specified as "name@version", i.e. "xous-names@0.9.9" if spec.contains('@') { let (name, version) = spec.split_once('@').expect("couldn't parse crate specifier"); - CrateSpec::CratesIo( - name.to_string(), - version.to_string(), - false - ) + CrateSpec::CratesIo(name.to_string(), version.to_string(), false) // prebuilt crates are specified as "name#url" // i.e. "espeak-embedded#https://ci.betrusted.io/job/espeak-embedded/lastSuccessfulBuild/artifact/target/riscv32imac-unknown-xous-elf/release/" } else if spec.contains('#') { let (name, url) = spec.split_once('#').expect("couldn't parse crate specifier"); - CrateSpec::Prebuilt( - name.to_string(), - url.to_string(), - false - ) + CrateSpec::Prebuilt(name.to_string(), url.to_string(), false) // local files are specified as paths, which, at a minimum include one directory separator "/" or "\" // i.e. "./local_file" // Note that this is after a test for the '#' character, so that disambiguates URL slashes - // It does mean that files with a '#' character in them are mistaken for URL coded paths, and '@' as remote crates. + // It does mean that files with a '#' character in them are mistaken for URL coded paths, and '@' as + // remote crates. } else if spec.contains('/') || spec.contains('\\') { //optionally a BinaryFile can have a name associated with it as "name:path" if spec.find(':').is_some() { - let (name,path) = spec.split_once(':').unwrap(); - CrateSpec::BinaryFile(Some(name.to_string()), path.to_string(), false) + let (name, path) = spec.split_once(':').unwrap(); + CrateSpec::BinaryFile(Some(name.to_string()), path.to_string(), false) } else { CrateSpec::BinaryFile(None, spec.to_string(), false) } @@ -111,19 +108,20 @@ impl From<&str> for CrateSpec { pub(crate) struct Builder { loader: CrateSpec, - loader_features: Vec::, + loader_features: Vec, loader_disable_defaults: bool, loader_key: String, kernel: CrateSpec, - kernel_features: Vec::, + kernel_features: Vec, kernel_disable_defaults: bool, kernel_key: String, /// crates that are installed in the xous.img, each one running in its own separate process space - services: Vec::, - /// Apps are different from services in that context menus are auto-generated for apps; furthermore, the apps must - /// exist in the app manifest JSON file. Aside from that, the Xous kernel treats apps and services identically. - apps: Vec::, - features: Vec::, + services: Vec, + /// Apps are different from services in that context menus are auto-generated for apps; furthermore, the + /// apps must exist in the app manifest JSON file. Aside from that, the Xous kernel treats apps and + /// services identically. + apps: Vec, + features: Vec, stream: BuildStream, min_ver: String, target: Option, @@ -159,9 +157,10 @@ impl Builder { locale_override: None, locale_stash: String::new(), dry_run: false, - no_image: false, + no_image: false, } } + /// Specify an alternate loader key, as a String that can encode a file name /// in the local directory, or a path + filename. #[allow(dead_code)] @@ -169,6 +168,7 @@ impl Builder { self.loader_key = filename; self } + /// Specify an alternate loader key, as a String that can encode a file name /// in the local directory, or a path + filename. #[allow(dead_code)] @@ -176,24 +176,28 @@ impl Builder { self.kernel_key = filename; self } + /// Set the build stream (debug or release) #[allow(dead_code)] pub fn stream<'a>(&'a mut self, stream: BuildStream) -> &'a mut Builder { self.stream = stream; self } + /// Disable default features on the loader #[allow(dead_code)] pub fn loader_disable_defaults<'a>(&'a mut self) -> &'a mut Builder { self.loader_disable_defaults = true; self } + /// Disable default features on the loader #[allow(dead_code)] pub fn kernel_disable_defaults<'a>(&'a mut self) -> &'a mut Builder { self.kernel_disable_defaults = true; self } + /// Set a minimum xous version. This is the minimum Xous version necessary to read /// the PDDB that is generated by this build. The purpose of this is so that we can /// trim migration code out of the PDDB: when we have a breaking change to the PDDB, @@ -221,6 +225,7 @@ impl Builder { self.run_svd2repl = false; self } + /// Configure for renode targets pub fn target_renode<'a>(&'a mut self) -> &'a mut Builder { self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); @@ -231,6 +236,7 @@ impl Builder { self.kernel = CrateSpec::Local("xous-kernel".to_string(), false); self } + /// Configure for precursor targets. This is the default, but it's good practice /// to call it anyways just in case the defaults change. The `soc_version` should /// be just the gitrev of the soc version, not the entire feature name. @@ -243,12 +249,13 @@ impl Builder { self.kernel = CrateSpec::Local("xous-kernel".to_string(), false); self } + pub fn target_precursor_no_image<'a>(&'a mut self, soc_version: &str) -> &'a mut Builder { self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); self.stream = BuildStream::Release; self.utra_target = format!("precursor-{}", soc_version).to_string(); self.run_svd2repl = false; - self.no_image = true; + self.no_image = true; self } @@ -273,6 +280,7 @@ impl Builder { self.kernel = CrateSpec::Local("xous-kernel".to_string(), false); self } + pub fn target_cramium_soc<'a>(&'a mut self) -> &'a mut Builder { self.target = Some(crate::TARGET_TRIPLE_RISCV32.to_string()); self.stream = BuildStream::Release; @@ -283,12 +291,14 @@ impl Builder { self } - /// Override the default kernel. For example, to use the kernel from crates.io, specify as "xous-kernel@0.9.9" + /// Override the default kernel. For example, to use the kernel from crates.io, specify as + /// "xous-kernel@0.9.9" #[allow(dead_code)] pub fn use_kernel<'a>(&'a mut self, spec: &str) -> &'a mut Builder { self.kernel = spec.into(); self } + /// Override the default loader #[allow(dead_code)] pub fn use_loader<'a>(&'a mut self, spec: &str) -> &'a mut Builder { @@ -303,8 +313,9 @@ impl Builder { self.services.push(spec); self } + /// Add a list of services - pub fn add_services<'a>(&'a mut self, service_list: &Vec::) -> &'a mut Builder { + pub fn add_services<'a>(&'a mut self, service_list: &Vec) -> &'a mut Builder { for service in service_list { self.services.push(service.as_str().into()); } @@ -319,39 +330,44 @@ impl Builder { self.apps.push(spec); self } + /// Add a list of apps - pub fn add_apps<'a>(&'a mut self, app_list: &Vec::) -> &'a mut Builder { + pub fn add_apps<'a>(&'a mut self, app_list: &Vec) -> &'a mut Builder { for app in app_list { self.apps.push(app.as_str().into()); } self } + /// add a feature to be passed on to services pub fn add_feature<'a>(&'a mut self, feature: &str) -> &'a mut Builder { self.features.push(feature.into()); self } + /// remove a feature previously added by a previous call #[allow(dead_code)] pub fn remove_feature<'a>(&'a mut self, feature: &str) -> &'a mut Builder { self.features.retain(|x| x != feature); self } + /// test if a feature is present - pub fn has_feature(&self, feature: &str) -> bool { - self.features.contains(&feature.to_string()) - } + pub fn has_feature(&self, feature: &str) -> bool { self.features.contains(&feature.to_string()) } + /// add a feature to be passed on to just the loader pub fn add_loader_feature<'a>(&'a mut self, feature: &str) -> &'a mut Builder { self.loader_features.push(feature.into()); self } + /// add a feature to be passed on to just the loader #[allow(dead_code)] pub fn add_kernel_feature<'a>(&'a mut self, feature: &str) -> &'a mut Builder { self.kernel_features.push(feature.into()); self } + /// only build a hosted target. don't run it. Used exclusively to confirm that hosted mode builds in CI. pub fn hosted_build_only<'a>(&'a mut self) -> &'a mut Builder { self.dry_run = true; @@ -363,14 +379,14 @@ impl Builder { /// method, and it gets called repeatedly to build the kernel, loader, and services. fn builder( &self, - packages: &Vec::, - features: &Vec::, + packages: &Vec, + features: &Vec, target: &Option<&str>, // the stream is specified separately here because the loader is special-case always release stream: BuildStream, - extra_args: &Vec::, + extra_args: &Vec, no_default_features: bool, - ) -> Result, DynError> { + ) -> Result, DynError> { // list of build artifacts, as full paths specific to the host OS let mut artifacts = Vec::::new(); // set up the list of arguments to cargo @@ -380,7 +396,8 @@ impl Builder { let mut local_args = vec!["build"]; let mut remote_args = vec!["install", "--target-dir", "target"]; remote_args.push("--root"); - let output_root = format!("{}/target/{}{}/", + let output_root = format!( + "{}/target/{}{}/", project_root().into_os_string().into_string().unwrap(), match target { Some(t) => format!("{}/", t), @@ -422,7 +439,7 @@ impl Builder { match pkg { CrateSpec::Local(name, _xip) => local_pkgs.push(&name), CrateSpec::CratesIo(name, version, _xip) => remote_pkgs.push((&name, &version)), - _ => {}, + _ => {} } } @@ -449,10 +466,7 @@ impl Builder { } println!(); // build - let status = Command::new(cargo()) - .current_dir(project_root()) - .args(&local_args) - .status()?; + let status = Command::new(cargo()).current_dir(project_root()).args(&local_args).status()?; if !status.success() { return Err("Local build failed".into()); } @@ -478,9 +492,9 @@ impl Builder { println!(" {} {}", name, version); // build let status = Command::new(cargo()) - .current_dir(project_root()) - .args([&remote_args[..], &[name, "--version", version].to_vec()[..]].concat()) - .status()?; + .current_dir(project_root()) + .args([&remote_args[..], &[name, "--version", version].to_vec()[..]].concat()) + .status()?; if !status.success() { return Err("Remote build failed".into()); } @@ -498,8 +512,9 @@ impl Builder { let mut found = false; for app in self.apps.iter() { if let Some(n) = &app.name() { - if Path::new(service).file_name().unwrap_or_default().to_str().unwrap_or_default() == - Path::new(n).file_name().unwrap_or_default().to_str().unwrap_or_default() { + if Path::new(service).file_name().unwrap_or_default().to_str().unwrap_or_default() + == Path::new(n).file_name().unwrap_or_default().to_str().unwrap_or_default() + { if app.is_xip() { inif.push(service.to_string()); } else { @@ -515,8 +530,9 @@ impl Builder { } for serv in self.services.iter() { if let Some(n) = &serv.name() { - if Path::new(service).file_name().unwrap_or_default().to_str().unwrap_or_default() == - Path::new(n).file_name().unwrap_or_default().to_str().unwrap_or_default() { + if Path::new(service).file_name().unwrap_or_default().to_str().unwrap_or_default() + == Path::new(n).file_name().unwrap_or_default().to_str().unwrap_or_default() + { if serv.is_xip() { inif.push(service.to_string()); } else { @@ -537,12 +553,12 @@ impl Builder { (inie, inif) } - /// Consume the builder and execute the configured build task. This handles dispatching all configurations, - /// including renode, hosted, and hardware targets. + /// Consume the builder and execute the configured build task. This handles dispatching all + /// configurations, including renode, hosted, and hardware targets. pub fn build(mut self) -> Result<(), DynError> { if self.apps.len() == 0 && self.services.len() == 0 { // no services were specified - don't build anything - return Ok(()) + return Ok(()); } // ------ configure target generation feature flags ------ @@ -601,8 +617,9 @@ impl Builder { // if binary file has a name, ensure it ends up in the app menu if let Some(n) = name { app_names.push(n.to_string()) - } else {} - }, + } else { + } + } _ => {} } } @@ -613,21 +630,24 @@ impl Builder { &target, self.stream, &vec![], - false + false, )?; // ------ either stop here, create an image, or launch hosted mode ------ if self.no_image { - println!("The following apps/services were compiled:"); - for path in services_path { - println!("{}", path); - } - } else if self.target.is_none() { // hosted mode doesn't specify a cross-compilation target! + println!("The following apps/services were compiled:"); + for path in services_path { + println!("{}", path); + } + } else if self.target.is_none() { + // hosted mode doesn't specify a cross-compilation target! // throw a warning if prebuilts are specified for hosted mode for item in [&self.services[..], &self.apps[..]].concat() { match item { - CrateSpec::Prebuilt(name, _, _xip) => println!("Warning! Pre-built binaries not supported for hosted mode ({})", name), - _ => {}, + CrateSpec::Prebuilt(name, _, _xip) => { + println!("Warning! Pre-built binaries not supported for hosted mode ({})", name) + } + _ => {} } } // fixup windows paths @@ -659,10 +679,7 @@ impl Builder { print!(" {}", arg); } println!(); - let status = Command::new(cargo()) - .current_dir(dir) - .args(&hosted_args) - .status()?; + let status = Command::new(cargo()).current_dir(dir).args(&hosted_args).status()?; if !status.success() { return Err("cargo run failed to launch hosted mode".into()); } @@ -696,12 +713,9 @@ impl Builder { // ------ build the loader ------ // stash any LTO settings applied to the kernel; proper layout of the loader // block depends on the loader being compact and highly optimized. - let existing_lto = std::env::var("CARGO_PROFILE_RELEASE_LTO") - .map(|v| Some(v)) - .unwrap_or(None); - let existing_codegen_units = std::env::var("CARGO_PROFILE_RELEASE_CODEGEN_UNITS") - .map(|v| Some(v)) - .unwrap_or(None); + let existing_lto = std::env::var("CARGO_PROFILE_RELEASE_LTO").map(|v| Some(v)).unwrap_or(None); + let existing_codegen_units = + std::env::var("CARGO_PROFILE_RELEASE_CODEGEN_UNITS").map(|v| Some(v)).unwrap_or(None); // these settings will generate the most compact code (but also the hardest to debug) std::env::set_var("CARGO_PROFILE_RELEASE_LTO", "true"); std::env::set_var("CARGO_PROFILE_RELEASE_CODEGEN_UNITS", "1"); @@ -741,10 +755,12 @@ impl Builder { } // ---------- extract SVD file path, as computed by utralib ---------- - let svd_spec_path = format!("target/{}/{}/build/SVD_PATH", self.target.as_ref().expect("target"), self.stream.to_str()); - let mut svd_spec_file = OpenOptions::new() - .read(true) - .open(&svd_spec_path)?; + let svd_spec_path = format!( + "target/{}/{}/build/SVD_PATH", + self.target.as_ref().expect("target"), + self.stream.to_str() + ); + let mut svd_spec_file = OpenOptions::new().read(true).open(&svd_spec_path)?; let mut svd_path_str = String::new(); svd_spec_file.read_to_string(&mut svd_path_str)?; let mut svd_paths = Vec::new(); @@ -758,17 +774,9 @@ impl Builder { // --------- package up and sign a binary image ---------- let (inie, inif) = self.split_xip(services_path.clone()); - let output_bundle = self.create_image( - &kernel_path[0], - &inie, - &inif, - svd_paths, - )?; + let output_bundle = self.create_image(&kernel_path[0], &inie, &inif, svd_paths)?; println!(); - println!( - "Kernel+Init bundle is available at {}", - output_bundle.display() - ); + println!("Kernel+Init bundle is available at {}", output_bundle.display()); let mut loader_bin = output_bundle.parent().unwrap().to_owned(); loader_bin.push("loader.bin"); @@ -855,7 +863,7 @@ impl Builder { kernel: &String, init: &[String], inif: &[String], - memory_spec: Vec::, + memory_spec: Vec, ) -> Result { let stream = self.stream.to_str(); let mut args = vec!["run", "--package", "tools", "--bin", "create-image", "--"]; @@ -892,10 +900,7 @@ impl Builder { } } - let status = Command::new(cargo()) - .current_dir(project_root()) - .args(&args) - .status()?; + let status = Command::new(cargo()).current_dir(project_root()).args(&args).status()?; if !status.success() { return Err("cargo build failed".into()); @@ -903,12 +908,17 @@ impl Builder { Ok(project_root().join(output_file)) } - fn fetch_prebuilds(&self) -> Result, DynError> { + fn fetch_prebuilds(&self) -> Result, DynError> { let mut paths = Vec::::new(); for item in [&self.services[..], &self.apps[..]].concat() { match item { CrateSpec::Prebuilt(name, url, _xip) => { - let exec_name = format!("target/{}/{}/{}", self.target.as_ref().expect("target"), self.stream.to_str(), name); + let exec_name = format!( + "target/{}/{}/{}", + self.target.as_ref().expect("target"), + self.stream.to_str(), + name + ); println!("Fetching {} executable from build server...", name); let mut exec_file = OpenOptions::new() .read(true) @@ -917,15 +927,9 @@ impl Builder { .truncate(true) .open(&exec_name) .expect("Can't open our version file for writing"); - let mut freader = ureq::get(&url) - .call()? - .into_reader(); + let mut freader = ureq::get(&url).call()?.into_reader(); std::io::copy(&mut freader, &mut exec_file)?; - println!( - "{} pre-built exec is {} bytes", - name, - exec_file.metadata().unwrap().len() - ); + println!("{} pre-built exec is {} bytes", name, exec_file.metadata().unwrap().len()); paths.push(exec_name); } _ => {} @@ -934,7 +938,7 @@ impl Builder { Ok(paths) } - fn enumerate_binary_files(&self) -> Result, DynError> { + fn enumerate_binary_files(&self) -> Result, DynError> { let mut paths = Vec::::new(); for item in [&self.services[..], &self.apps[..]].concat() { match item { @@ -949,7 +953,8 @@ impl Builder { fn locale_override(&mut self) { if let Some(locale) = &self.locale_override { - { // stash the existing locale + { + // stash the existing locale let mut locale_file = OpenOptions::new() .read(true) .open("locales/src/locale.rs") @@ -964,11 +969,7 @@ impl Builder { .truncate(true) .open("locales/src/locale.rs") .expect("Can't open locale for modification"); - write!( - locale_override, - "pub const LANG: &str = \"{}\";\n", - locale - ).unwrap(); + write!(locale_override, "pub const LANG: &str = \"{}\";\n", locale).unwrap(); } } @@ -981,23 +982,13 @@ impl Builder { .truncate(true) .open("locales/src/locale.rs") .expect("Can't open locale for modification"); - write!( - locale_restore, - "{}", - self.locale_stash - ).unwrap(); + write!(locale_restore, "{}", self.locale_stash).unwrap(); } } } -pub fn cargo() -> String { - env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()) -} +pub fn cargo() -> String { env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()) } pub fn project_root() -> PathBuf { - Path::new(&env!("CARGO_MANIFEST_DIR")) - .ancestors() - .nth(1) - .unwrap() - .to_path_buf() + Path::new(&env!("CARGO_MANIFEST_DIR")).ancestors().nth(1).unwrap().to_path_buf() } diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 180cb5f9a..0f85b498b 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -6,10 +6,10 @@ use utils::*; mod builder; use builder::*; mod verifier; -use verifier::*; - use std::env; +use verifier::*; + /// specifies the hardware target variant for the SoC const PRECURSOR_SOC_VERSION: &str = "pvt"; @@ -63,7 +63,7 @@ fn main() -> Result<(), Box> { "xous-ticktimer", // "well known" service: thread scheduling "xous-log", // "well known" service: debug logging "xous-names", // "well known" service: manage inter-server connection lookup - "xous-susres", // ticktimer registers with susres to coordinate time continuity across sleeps + "xous-susres", // ticktimer registers with susres to coordinate time continuity across sleeps ] .to_vec(); // minimal set of packages to do bare-iron graphical I/O @@ -160,11 +160,7 @@ fn main() -> Result<(), Box> { match task.as_deref() { Some("install-toolkit") | Some("install-toolchain") => { let arg = env::args().nth(2); - ensure_compiler( - &Some(TARGET_TRIPLE_RISCV32), - true, - arg.map(|x| x == "--force").unwrap_or(false), - )? + ensure_compiler(&Some(TARGET_TRIPLE_RISCV32), true, arg.map(|x| x == "--force").unwrap_or(false))? } // ----- renode configs -------- Some("renode-image") => { @@ -198,9 +194,7 @@ fn main() -> Result<(), Box> { .target_renode() .add_services(&base_pkgs.into_iter().map(String::from).collect()) .add_services(&get_cratespecs()); - builder - .add_loader_feature("renode-bypass") - .add_loader_feature("renode-minimal"); + builder.add_loader_feature("renode-bypass").add_loader_feature("renode-minimal"); builder .add_service("net", false) .add_service("com", false) @@ -290,8 +284,7 @@ fn main() -> Result<(), Box> { //.add_services(&user_pkgs.into_iter().map(String::from).collect()) .add_feature("mass-storage"); // add this in by default to help with testing for service in user_pkgs { - if (service != "shellchat") && (service != "ime-plugin-shell" && (service != "net")) - { + if (service != "shellchat") && (service != "ime-plugin-shell" && (service != "net")) { builder.add_service(service, false); } else { builder.add_service(service, true); @@ -307,13 +300,15 @@ fn main() -> Result<(), Box> { // select `shellchat` as the performance manager by default. builder.add_feature("shellperf"); } - // note: to use this image, you need to load a version of the SOC that has the performance counters built in. - // this can be generated using the command `python3 .\betrusted_soc.py -e .\dummy.nky --perfcounter` in the betrusted-soc repo. + // note: to use this image, you need to load a version of the SOC that has the performance + // counters built in. this can be generated using the command `python3 + // .\betrusted_soc.py -e .\dummy.nky --perfcounter` in the betrusted-soc repo. // // to read out performance monitoring data, use the `usb_update.py` script as follows: // ` python3 .\..\usb_update.py --dump v2p.txt --dump-file .\ring_aes_8.bin` - // where the `v2p.txt` file contains a virtual to physical mapping that is generated by the `perflib` framework and - // formatted in a fashion that can be automatically extracted by the usb_update script. + // where the `v2p.txt` file contains a virtual to physical mapping that is generated by the + // `perflib` framework and formatted in a fashion that can be automatically extracted + // by the usb_update script. builder .target_precursor("c809403-perflib") .add_services(&user_pkgs.into_iter().map(String::from).collect()) @@ -322,9 +317,10 @@ fn main() -> Result<(), Box> { .add_kernel_feature("v2p"); } Some("dvt-image") => { - // this image targets a mostly deprecated DVT hardware generation. The purpose of it is to re-use some - // of the now-defunct hardware for eFuse code testing, especially since FPGAs have gotten very scarce. - // Once the eFuse path is validated, we could remove this target. + // this image targets a mostly deprecated DVT hardware generation. The purpose of it is to re-use + // some of the now-defunct hardware for eFuse code testing, especially since FPGAs + // have gotten very scarce. Once the eFuse path is validated, we could remove this + // target. let mut services: Vec = user_pkgs.into_iter().map(String::from).collect(); services.retain(|x| x != "codec"); // codec is not compatible with DVT boards @@ -396,8 +392,7 @@ fn main() -> Result<(), Box> { // ------ Cramium hardware image configs ------ Some("cramium-fpga") | Some("cramium-soc") => { - let cramium_pkgs = - ["xous-log", "xous-names", "xous-ticktimer", "cram-console"].to_vec(); + let cramium_pkgs = ["xous-log", "xous-names", "xous-ticktimer", "cram-console"].to_vec(); match task.as_deref() { Some("cramium-fpga") => builder.target_cramium_fpga(), Some("cramium-soc") => builder.target_cramium_soc(), @@ -451,8 +446,12 @@ fn main() -> Result<(), Box> { Ok(()) => Ok(()), Err(e) => { // Explain to developers why this step is important. - println!("Local source changes have not been published. If you meant to modify core components,"); - println!("activate patches in top-level Cargo.toml to redirect crates.io to the local source tree."); + println!( + "Local source changes have not been published. If you meant to modify core components," + ); + println!( + "activate patches in top-level Cargo.toml to redirect crates.io to the local source tree." + ); println!("Otherwise, your local changes are IGNORED."); println!("Use the `--no-verify` argument to suppress this warning."); Err(e) @@ -571,10 +570,7 @@ fn get_flag(flag: &str) -> Result, DynError> { } if flag_found { if arg.starts_with('-') { - eprintln!( - "Malformed arguments. Expected argument after flag {}, but found {}", - flag, arg - ); + eprintln!("Malformed arguments. Expected argument after flag {}, but found {}", flag, arg); return Err("Bad arguments".into()); } list.push(arg); diff --git a/xtask/src/utils.rs b/xtask/src/utils.rs index 2a6cc4928..06fdc81af 100644 --- a/xtask/src/utils.rs +++ b/xtask/src/utils.rs @@ -1,4 +1,3 @@ -use lazy_static::lazy_static; use std::collections::HashMap; use std::{ fs::{File, OpenOptions}, @@ -7,32 +6,25 @@ use std::{ process::Command, }; +use lazy_static::lazy_static; + use crate::{cargo, project_root}; use crate::{TARGET_TRIPLE_ARM, TARGET_TRIPLE_RISCV32}; -const TOOLCHAIN_RELEASE_URL_RISCV32: &str = - "https://api.github.com/repos/betrusted-io/rust/releases"; -const TOOLCHAIN_RELEASE_URL_ARM: &str = - "https://api.github.com/repos/Foundation-Devices/rust/releases"; +const TOOLCHAIN_RELEASE_URL_RISCV32: &str = "https://api.github.com/repos/betrusted-io/rust/releases"; +const TOOLCHAIN_RELEASE_URL_ARM: &str = "https://api.github.com/repos/Foundation-Devices/rust/releases"; lazy_static! { static ref TOOLCHAIN_RELEASE_URLS: HashMap = HashMap::from([ - ( - TARGET_TRIPLE_RISCV32.to_owned(), - TOOLCHAIN_RELEASE_URL_RISCV32.to_owned() - ), - ( - TARGET_TRIPLE_ARM.to_owned(), - TOOLCHAIN_RELEASE_URL_ARM.to_owned() - ), + (TARGET_TRIPLE_RISCV32.to_owned(), TOOLCHAIN_RELEASE_URL_RISCV32.to_owned()), + (TARGET_TRIPLE_ARM.to_owned(), TOOLCHAIN_RELEASE_URL_ARM.to_owned()), ]); } /// Since we use the same TARGET for all calls to `build()`, /// cache it inside an atomic boolean. If this is `true` then /// it means we can assume the check passed already. -static DONE_COMPILER_CHECK: std::sync::atomic::AtomicBool = - std::sync::atomic::AtomicBool::new(false); +static DONE_COMPILER_CHECK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Ensure we have a compatible compiler toolchain. We use a new Target, /// and we want to give the user a friendly way of installing the latest @@ -85,8 +77,13 @@ pub(crate) fn ensure_compiler( let rustc_version_str = format!("{}", rustc_version::version().unwrap()); if version_str.trim() != rustc_version_str.trim() { - println!("Version upgrade. Compiler is version {}, the installed toolchain is for {}", rustc_version_str.trim(), version_str.trim(), ); - // return Err(format!("Version upgrade. Compiler is version {}, the installed toolchain is for {}", version_str, rustc_version_str)); + println!( + "Version upgrade. Compiler is version {}, the installed toolchain is for {}", + rustc_version_str.trim(), + version_str.trim(), + ); + // return Err(format!("Version upgrade. Compiler is version {}, the installed toolchain is + // for {}", version_str, rustc_version_str)); return Ok(None); } } else { @@ -96,11 +93,7 @@ pub(crate) fn ensure_compiler( } } - if have_toolchain { - Ok(Some(toolchain_path)) - } else { - Ok(None) - } + if have_toolchain { Ok(Some(toolchain_path)) } else { Ok(None) } } // If the sysroot exists, then we're good. @@ -132,8 +125,7 @@ pub(crate) fn ensure_compiler( } // Since no sysroot exists, we must download a new one. - let toolchain_path = - get_sysroot(None)?.ok_or_else(|| "default toolchain not installed".to_owned())?; + let toolchain_path = get_sysroot(None)?.ok_or_else(|| "default toolchain not installed".to_owned())?; // If the terminal is a tty, or if toolchain installation is forced, // download the latest toolchain. if !atty::is(atty::Stream::Stdin) && !force_install { @@ -153,10 +145,7 @@ pub(crate) fn ensure_compiler( if force_install { println!("Downloading toolchain"); } else { - println!( - "Error: Toolchain for {} was not found on this system!", - target - ); + println!("Error: Toolchain for {} was not found on this system!", target); } loop { if force_install { @@ -180,12 +169,7 @@ pub(crate) fn ensure_compiler( println!(); } - fn get_toolchain_url( - target: &str, - major: u64, - minor: u64, - patch: u64, - ) -> Result { + fn get_toolchain_url(target: &str, major: u64, minor: u64, patch: u64) -> Result { let url = TOOLCHAIN_RELEASE_URLS .get(target) .ok_or_else(|| format!("Can't find toolchain URL for target {}", target))?; @@ -251,10 +235,7 @@ pub(crate) fn ensure_compiler( } let toolchain_url = get_toolchain_url(target, ver.major, ver.minor, ver.patch)?; - println!( - "Attempting to install toolchain for {} into {}", - target, toolchain_path - ); + println!("Attempting to install toolchain for {} into {}", target, toolchain_path); println!("Downloading toolchain from {}...", toolchain_url); print!("Download in progress..."); @@ -265,14 +246,8 @@ pub(crate) fn ensure_compiler( // .middleware(CounterMiddleware(shared_state.clone())) .build(); - let mut freader = agent - .get(&toolchain_url) - .call() - .map_err(|e| format!("{}", e))? - .into_reader(); - freader - .read_to_end(&mut zip_data) - .map_err(|e| format!("{}", e))?; + let mut freader = agent.get(&toolchain_url).call().map_err(|e| format!("{}", e))?.into_reader(); + freader.read_to_end(&mut zip_data).map_err(|e| format!("{}", e))?; // |total_bytes, bytes_so_far, _total_uploaded, _uploaded_so_far| { // // If either number is infinite, don't print anything and just continue. // if total_bytes.is_infinite() || bytes_so_far.is_infinite() { @@ -291,10 +266,7 @@ pub(crate) fn ensure_compiler( // }, println!(); } - println!( - "Download successful. Total data size is {} bytes", - zip_data.len() - ); + println!("Download successful. Total data size is {} bytes", zip_data.len()); /// Extract the zipfile to the target directory, ensuring that all files /// contained within are created. @@ -302,12 +274,11 @@ pub(crate) fn ensure_compiler( archive_data: P, extract_to: P2, ) -> Result<(), String> { - let mut archive = zip::ZipArchive::new(archive_data) - .map_err(|e| format!("unable to extract zip: {}", e))?; + let mut archive = + zip::ZipArchive::new(archive_data).map_err(|e| format!("unable to extract zip: {}", e))?; for i in 0..archive.len() { - let mut entry_in_archive = archive - .by_index(i) - .map_err(|e| format!("unable to locate file index {}: {}", i, e))?; + let mut entry_in_archive = + archive.by_index(i).map_err(|e| format!("unable to locate file index {}: {}", i, e))?; // println!( // "Trying to extract file {}", // entry_in_archive.mangled_name().display() @@ -315,35 +286,21 @@ pub(crate) fn ensure_compiler( let output_path = extract_to.as_ref().join(entry_in_archive.mangled_name()); if entry_in_archive.is_dir() { - std::fs::create_dir_all(&output_path).map_err(|e| { - format!( - "unable to create directory {}: {}", - output_path.display(), - e - ) - })?; + std::fs::create_dir_all(&output_path) + .map_err(|e| format!("unable to create directory {}: {}", output_path.display(), e))?; } else { // Create the parent directory if necessary if let Some(parent) = output_path.parent() { if !parent.exists() { std::fs::create_dir_all(&parent).map_err(|e| { - format!( - "unable to create directory {}: {}", - output_path.display(), - e - ) + format!("unable to create directory {}: {}", output_path.display(), e) })?; } } - let mut outfile = std::fs::File::create(&output_path).map_err(|e| { - format!("unable to create file {}: {}", output_path.display(), e) - })?; + let mut outfile = std::fs::File::create(&output_path) + .map_err(|e| format!("unable to create file {}: {}", output_path.display(), e))?; std::io::copy(&mut entry_in_archive, &mut outfile).map_err(|e| { - format!( - "unable to write extracted file {}: {}", - output_path.display(), - e - ) + format!("unable to write extracted file {}: {}", output_path.display(), e) })?; } } @@ -364,15 +321,9 @@ pub(crate) fn generate_locales() -> Result<(), std::io::Error> { filetime::set_file_mtime("locales/src/lib.rs", ts)?; let mut path = project_root(); path.push("locales"); - let status = Command::new(cargo()) - .current_dir(path) - .args(&["build", "--package", "locales"]) - .status()?; + let status = Command::new(cargo()).current_dir(path).args(&["build", "--package", "locales"]).status()?; if !status.success() { - return Err(std::io::Error::new( - std::io::ErrorKind::Other, - "Couldn't generate the locales", - )); + return Err(std::io::Error::new(std::io::ErrorKind::Other, "Couldn't generate the locales")); } return Ok(()); } @@ -383,14 +334,7 @@ pub(crate) fn whycheproof_import() -> Result<(), crate::DynError> { let output_file = "services/shellchat/src/cmds/x25519_test.bin"; let status = Command::new(cargo()) .current_dir(project_root()) - .args(&[ - "run", - "--package", - "wycheproof-import", - "--", - input_file, - output_file, - ]) + .args(&["run", "--package", "wycheproof-import", "--", input_file, output_file]) .status()?; if !status.success() { return Err("wycheproof-import failed. If any, the output will not be usable.".into()); @@ -409,22 +353,13 @@ pub(crate) fn track_language_changes(last_lang: &str) -> Result<(), crate::DynEr let changed = match OpenOptions::new().read(true).open(&last_config) { Ok(mut file) => { file.read_to_string(&mut contents).unwrap(); - if contents != last_lang { - true - } else { - false - } + if contents != last_lang { true } else { false } } _ => true, }; if changed { println!("Locale language changed to {}", last_lang); - let mut file = OpenOptions::new() - .create(true) - .write(true) - .truncate(true) - .open(&last_config) - .unwrap(); + let mut file = OpenOptions::new().create(true).write(true).truncate(true).open(&last_config).unwrap(); write!(file, "{}", last_lang).unwrap(); generate_locales()? } else { diff --git a/xtask/src/verifier.rs b/xtask/src/verifier.rs index 13d12963e..670ac710f 100644 --- a/xtask/src/verifier.rs +++ b/xtask/src/verifier.rs @@ -1,10 +1,10 @@ -use crate::builder::CrateSpec; use std::env; use std::fs; use std::fs::File; use std::io::{BufReader, Read}; use std::path::Path; +use crate::builder::CrateSpec; use crate::DynError; pub fn check_project_consistency() -> Result<(), DynError> { @@ -48,7 +48,8 @@ pub fn verify(spec: CrateSpec, hard_failure: bool) -> Result<(), DynError> { // this should *really* exist if the build system is stable, so just unwrap all the things let regdir = path.file_name().unwrap().to_str().unwrap().to_string(); if regdir.contains("crates.io") { - // crates.io sticks sources in something with git yadda yadda...docs don't really say what/why/how... + // crates.io sticks sources in something with git yadda yadda...docs don't really say + // what/why/how... cache_leaf.push_str(®dir); } } @@ -68,11 +69,7 @@ pub fn verify(spec: CrateSpec, hard_failure: bool) -> Result<(), DynError> { } // form the local source path - let subdir = if name.contains("-api-") { - "api" - } else { - "services" - }; + let subdir = if name.contains("-api-") { "api" } else { "services" }; let subdir = format!("./{}/{}/", subdir, name); // handle special cases of xous kernel and ipc crates let src_path = if name != "xous" @@ -94,9 +91,7 @@ pub fn verify(spec: CrateSpec, hard_failure: bool) -> Result<(), DynError> { } else if name == "svd2utra" { Path::new("./svd2utra") } else { - panic!( - "Consistency error: special case handling did not find either xous or xous-ipc" - ); + panic!("Consistency error: special case handling did not find either xous or xous-ipc"); } }; @@ -112,7 +107,9 @@ pub fn verify(spec: CrateSpec, hard_failure: bool) -> Result<(), DynError> { if hard_failure { Err("Crates.io downloaded data does not match local source".into()) } else { - println!("**WARNING**: Local package does not match the published source. Third parties downloading from crates.io will be inconsistent with this build."); + println!( + "**WARNING**: Local package does not match the published source. Third parties downloading from crates.io will be inconsistent with this build." + ); Ok(()) } } @@ -146,7 +143,8 @@ fn compare_dirs(src: &Path, other: &Path) -> Result { other_file.push("Cargo.toml.orig"); let mut src_file = src.to_path_buf(); src_file.push(&fname); - // println!("comparing {} <-> {}", src_file.as_os_str().to_str().unwrap(), other_file.as_os_str().to_str().unwrap()); + // println!("comparing {} <-> {}", src_file.as_os_str().to_str().unwrap(), + // other_file.as_os_str().to_str().unwrap()); match compare_files(&src_file, &other_file) { Ok(true) => {} Ok(false) => { @@ -221,18 +219,16 @@ fn compare_dirs(src: &Path, other: &Path) -> Result { other_file.push(&fname); let mut src_file = src.to_path_buf(); src_file.push(&fname); - // println!("comparing {} <-> {}", src_file.as_os_str().to_str().unwrap(), other_file.as_os_str().to_str().unwrap()); + // println!("comparing {} <-> {}", src_file.as_os_str().to_str().unwrap(), + // other_file.as_os_str().to_str().unwrap()); if (src_file.as_os_str().to_str().unwrap().contains("ticktimer") && fname.as_os_str().to_str().unwrap() == "version.rs") - || src_file - .as_os_str() - .to_str() - .unwrap() - .contains("Cargo.lock") + || src_file.as_os_str().to_str().unwrap().contains("Cargo.lock") { // don't compare the version.rs, as it's supposed to be different due to the timestamp // don't compare Cargo.lock files that happen to be checked into packages - // println!("skipping ticktimer version.rs or Cargo.lock file"); // this line is helpful to ensure our skip exception isn't too broad. + // println!("skipping ticktimer version.rs or Cargo.lock file"); // this line is helpful + // to ensure our skip exception isn't too broad. } else { match compare_files(&src_file, &other_file) { Ok(true) => {} @@ -244,9 +240,7 @@ fn compare_dirs(src: &Path, other: &Path) -> Result { ); return Ok(false); } - Err(_) => { - return Err("Access error comparing remote and local crates".into()) - } + Err(_) => return Err("Access error comparing remote and local crates".into()), } } } @@ -260,7 +254,8 @@ fn compare_dirs(src: &Path, other: &Path) -> Result { other_dir.push(&dname); let mut src_dir = src.to_path_buf(); src_dir.push(&dname); - // println!("comparing {}/ <-> {}/", src_dir.as_os_str().to_str().unwrap(), &other_dir.as_os_str().to_str().unwrap()); + // println!("comparing {}/ <-> {}/", src_dir.as_os_str().to_str().unwrap(), + // &other_dir.as_os_str().to_str().unwrap()); match compare_dirs(&src_dir, &other_dir) { Ok(true) => {} Ok(false) => { @@ -295,11 +290,7 @@ fn compare_files(a: &Path, b: &Path) -> Result { // text do CRLF substitutions let f1 = s1?.replace("\r\n", "\n"); let f2 = s2?.replace("\r\n", "\n"); - if f1 == f2 { - Ok(true) - } else { - Ok(false) - } + if f1 == f2 { Ok(true) } else { Ok(false) } } else { // do a binary compare let f1 = BufReader::new(f1); diff --git a/xtask/src/versioning.rs b/xtask/src/versioning.rs index f141baaa7..3ab1943c7 100644 --- a/xtask/src/versioning.rs +++ b/xtask/src/versioning.rs @@ -2,11 +2,12 @@ // This generates the SEMVER data that is displayed when quering `xous ver` // It also generates timestamps, if demanded. -use chrono::Local; use std::fs::OpenOptions; use std::io::{Read, Write}; use std::process::Command; +use chrono::Local; + pub(crate) fn generate_version(add_timestamp: bool) { let output = if cfg!(target_os = "windows") { Command::new("cmd") @@ -42,19 +43,13 @@ pub(crate) fn generate_version(add_timestamp: bool) { ) .expect("couldn't add our timestamp"); } else { - write!( - new_data, - "#[allow(dead_code)]\npub const TIMESTAMP: &'static str = \"unavailable\";\n" - ) - .expect("couldn't add our timestamp"); + write!(new_data, "#[allow(dead_code)]\npub const TIMESTAMP: &'static str = \"unavailable\";\n") + .expect("couldn't add our timestamp"); } write!( new_data, "pub const SEMVER: &'static str = \"{}\";\n", - semver - .strip_suffix("\r\n") - .or(semver.strip_suffix("\n")) - .unwrap_or(&semver) + semver.strip_suffix("\r\n").or(semver.strip_suffix("\n")).unwrap_or(&semver) ) .expect("couldn't add our semver"); @@ -66,9 +61,7 @@ pub(crate) fn generate_version(add_timestamp: bool) { .truncate(true) .open(version_file) .expect("Can't open our version file for writing"); - vfile - .write_all(&mut new_data) - .expect("couldn't write new timestamp to version.rs"); + vfile.write_all(&mut new_data).expect("couldn't write new timestamp to version.rs"); } } @@ -87,6 +80,5 @@ pub(crate) fn get_version() -> crate::api::VersionString { v } "####; - out.write_all(s.as_bytes()) - .expect("couldn't write our version template header"); + out.write_all(s.as_bytes()).expect("couldn't write our version template header"); }