use crate::cargo::{PackageError, layout_of, read_board, workspace_root};
use crate::layout::{Layout, LayoutErrors, ParseError};
use crate::manifest::Manifest;
use crate::table::TableError;
use crate::table::linker::{MemoryRegion, memory_regions, memory_script, rust_constants};
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use std::path::{Path, PathBuf};
const CONSTANTS_FILE: &str = "nanoflash_layout.rs";
const LINKER_FILE: &str = "nanoflash_memory.x";
const MEMORY_FILE: &str = "memory.x";
const GUARD_FILE: &str = "nanoflash_memory_guard.x";
const MEMORY_MARKER: &str = "__nanoflash_memory_x";
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Generated {
pub constants: PathBuf,
pub linker_script: PathBuf,
pub memory_script: Option<PathBuf>,
pub memory_guard: Option<PathBuf>,
pub inputs: Vec<PathBuf>,
}
pub enum BuildError {
Io {
path: PathBuf,
error: std::io::Error,
},
Parse(ParseError),
Layout(LayoutErrors),
Table(TableError),
MissingOutputDirectory,
MissingPackageDirectory,
Package(PackageError),
NoBoard {
cargo_toml: PathBuf,
},
Manifest {
path: PathBuf,
message: String,
},
MemoryScriptShadowed {
path: PathBuf,
},
}
impl fmt::Display for BuildError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BuildError::Io { path, error } => {
write!(formatter, "cannot access {}: {error}", path.display())
}
BuildError::Parse(error) => write!(formatter, "cannot read the layout: {error}"),
BuildError::Layout(error) => write!(formatter, "{error}"),
BuildError::Table(error) => write!(formatter, "{error}"),
BuildError::MissingOutputDirectory => formatter.write_str(
"the OUT_DIR environment variable is not set, call this from a build script",
),
BuildError::MissingPackageDirectory => formatter.write_str(
"the CARGO_MANIFEST_DIR environment variable is not set, call this from a build script",
),
BuildError::Package(error) => write!(formatter, "{error}"),
BuildError::NoBoard { cargo_toml } => write!(
formatter,
"{} names no board: add [package.metadata.nanoflash] board = \"boards/board.toml\", or call Build::layout with the layout file",
cargo_toml.display()
),
BuildError::Manifest { path, message } => write!(
formatter,
"cannot use the board manifest {}: {message}",
path.display()
),
BuildError::MemoryScriptShadowed { path } => write!(
formatter,
"{} would be linked instead of the memory.x nanoflash writes, since the linker looks first in its working directory, which is the workspace root of the package, or its package directory without a workspace: remove it, or keep it with INCLUDE nanoflash_memory.x and do not call Build::memory",
path.display()
),
}
}
}
impl fmt::Debug for BuildError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, formatter)
}
}
impl std::error::Error for BuildError {}
#[derive(Debug, Clone)]
enum Source {
Layout(PathBuf),
Package,
}
#[derive(Debug, Clone)]
pub struct Build {
source: Source,
memory: Vec<MemoryRegion>,
}
impl Build {
pub fn layout(path: impl AsRef<Path>) -> Build {
Build {
source: Source::Layout(path.as_ref().to_path_buf()),
memory: Vec::new(),
}
}
pub fn package() -> Build {
Build {
source: Source::Package,
memory: Vec::new(),
}
}
pub fn memory(mut self, name: &str, origin: u64, length: u64) -> Build {
self.memory.push(MemoryRegion {
name: name.into(),
origin,
length,
});
self
}
pub fn generate(self) -> Result<Generated, BuildError> {
let output_directory =
std::env::var_os("OUT_DIR").ok_or(BuildError::MissingOutputDirectory)?;
let output_directory = PathBuf::from(output_directory);
let package_directory = match (std::env::var_os("CARGO_MANIFEST_DIR"), &self.source) {
(Some(directory), _) => PathBuf::from(directory),
(None, Source::Layout(_)) => PathBuf::new(),
(None, Source::Package) => return Err(BuildError::MissingPackageDirectory),
};
let generated = self.generate_into(&package_directory, &output_directory)?;
for input in &generated.inputs {
std::println!("cargo:rerun-if-changed={}", input.display());
}
std::println!("cargo:rustc-link-search={}", output_directory.display());
if let Some(guard) = &generated.memory_guard {
std::println!("cargo:rustc-link-arg-bins=-T{}", guard.display());
}
Ok(generated)
}
pub fn generate_into(
self,
package_directory: &Path,
output_directory: &Path,
) -> Result<Generated, BuildError> {
let (layout_path, mut inputs) = match &self.source {
Source::Layout(path) => (package_directory.join(path), Vec::new()),
Source::Package => board_layout(package_directory)?,
};
let text = std::fs::read_to_string(&layout_path).map_err(|error| BuildError::Io {
path: layout_path.clone(),
error,
})?;
inputs.push(layout_path);
let resolved = Layout::from_toml(&text)
.map_err(BuildError::Parse)?
.resolve()
.map_err(BuildError::Layout)?;
let constants: String = rust_constants(&resolved).map_err(BuildError::Table)?;
let regions: String = memory_regions(&resolved).map_err(BuildError::Table)?;
let memory = if self.memory.is_empty() {
None
} else {
let mut directories = alloc::vec![package_directory.to_path_buf()];
if let Some(root) = workspace_root(&package_directory.join("Cargo.toml"))
&& root != package_directory
{
directories.push(root);
}
for directory in directories {
let shadow = directory.join(MEMORY_FILE);
if shadow.exists() {
return Err(BuildError::MemoryScriptShadowed { path: shadow });
}
}
let mut script = memory_script(&resolved, &self.memory).map_err(BuildError::Table)?;
script.push_str(&alloc::format!("{MEMORY_MARKER} = 1;\n"));
Some(script)
};
let generated = Generated {
constants: output_directory.join(CONSTANTS_FILE),
linker_script: output_directory.join(LINKER_FILE),
memory_script: memory.as_ref().map(|_| output_directory.join(MEMORY_FILE)),
memory_guard: memory.as_ref().map(|_| output_directory.join(GUARD_FILE)),
inputs,
};
let mut files = alloc::vec![
(&generated.constants, constants),
(&generated.linker_script, regions),
];
let guard = guard_script();
if let (Some(path), Some(contents)) = (&generated.memory_script, memory) {
files.push((path, contents));
}
if let Some(path) = &generated.memory_guard {
files.push((path, guard));
}
for (path, contents) in files {
std::fs::write(path, contents).map_err(|error| BuildError::Io {
path: path.clone(),
error,
})?;
}
if generated.memory_script.is_none() {
for name in [MEMORY_FILE, GUARD_FILE] {
let stale = output_directory.join(name);
match std::fs::remove_file(&stale) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(BuildError::Io { path: stale, error }),
}
}
}
Ok(generated)
}
}
fn guard_script() -> String {
alloc::format!(
"/* Generated by nanoflash. Do not edit.\n\
\x20 The memory.x that nanoflash writes defines the symbol {MEMORY_MARKER}. If the linker\n\
\x20 reports that this symbol is not found, it linked another memory.x: the one in the\n\
\x20 package directory or in the workspace root. Remove it. */\n\
ASSERT({MEMORY_MARKER} == 1, \"the memory.x that nanoflash writes was not linked, since another memory.x was found first: remove the memory.x in the package directory or in the workspace root, or keep it with INCLUDE nanoflash_memory.x and do not call Build::memory\");\n"
)
}
fn board_layout(package_directory: &Path) -> Result<(PathBuf, Vec<PathBuf>), BuildError> {
let cargo_toml = package_directory.join("Cargo.toml");
let board = read_board(&cargo_toml)
.map_err(BuildError::Package)?
.ok_or_else(|| BuildError::NoBoard {
cargo_toml: cargo_toml.clone(),
})?;
let manifest_error = |message: String| BuildError::Manifest {
path: board.board.clone(),
message,
};
let text = std::fs::read_to_string(&board.board).map_err(|error| BuildError::Io {
path: board.board.clone(),
error,
})?;
let manifest =
Manifest::parse(&text).map_err(|error| manifest_error(alloc::format!("{error}")))?;
let layout = layout_of(&manifest, board.board_identifier.as_deref()).map_err(manifest_error)?;
let directory = board.board.parent().unwrap_or_else(|| Path::new(""));
Ok((
directory.join(layout),
alloc::vec![cargo_toml, board.board.clone()],
))
}
pub fn generate(layout_path: impl AsRef<Path>) -> Result<Generated, BuildError> {
Build::layout(layout_path).generate()
}
pub fn generate_into(layout_path: &Path, output_directory: &Path) -> Result<Generated, BuildError> {
Build::layout(layout_path).generate_into(Path::new(""), output_directory)
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
use std::fs;
fn scratch(name: &str) -> PathBuf {
let directory = Path::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../target/test-scratch"
))
.join(std::format!("nanoflash-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&directory);
fs::create_dir_all(&directory).unwrap();
directory
}
fn fixture(name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/layouts")
.join(name)
}
#[test]
fn generate_into_writes_both_files() {
let directory = scratch("both");
let generated = generate_into(&fixture("nrf52840-arduino.toml"), &directory).unwrap();
let resolved =
Layout::from_toml(&fs::read_to_string(fixture("nrf52840-arduino.toml")).unwrap())
.unwrap()
.resolve()
.unwrap();
assert_eq!(
fs::read_to_string(&generated.constants).unwrap(),
rust_constants(&resolved).unwrap()
);
assert_eq!(
fs::read_to_string(&generated.linker_script).unwrap(),
memory_regions(&resolved).unwrap()
);
fs::remove_dir_all(&directory).unwrap();
}
#[test]
fn generate_into_writes_minimum_sizes() {
let directory = scratch("minimum");
let generated = generate_into(&fixture("growing.toml"), &directory).unwrap();
let constants = fs::read_to_string(&generated.constants).unwrap();
assert!(constants.contains("MINIMUM_SIZE"), "{constants}");
assert!(constants.contains("FLASH_MINIMUM_SIZE"), "{constants}");
assert!(!constants.contains("FLASH_SIZE: "), "{constants}");
fs::remove_dir_all(&directory).unwrap();
}
#[test]
fn generate_reports_layout_errors() {
let directory = scratch("overlap");
let layout = directory.join("layout.toml");
fs::write(
&layout,
"[flash]\nsize = \"1 MiB\"\nbase-address = 0x0\n\n\
[[partition]]\nname = \"a\"\nrole = \"firmware\"\noffset = 0x0\nsize = 0x20000\n\n\
[[partition]]\nname = \"b\"\nrole = \"storage\"\noffset = 0x10000\nsize = 0x10000\n",
)
.unwrap();
let error = generate_into(&layout, &directory).unwrap_err();
assert!(matches!(error, BuildError::Layout(_)));
assert!(error.to_string().contains("overlap"), "{error}");
let debug = std::format!("{error:?}");
assert!(debug.contains("overlap") && debug.contains("0x"), "{debug}");
assert_eq!(debug, error.to_string());
fs::remove_dir_all(&directory).unwrap();
}
fn package(name: &str, metadata: &str, boards: &[(&str, &str)]) -> PathBuf {
let directory = scratch(name);
fs::create_dir_all(directory.join("boards")).unwrap();
fs::create_dir_all(directory.join("layouts")).unwrap();
fs::write(
directory.join("Cargo.toml"),
std::format!("[package]\nname = \"firmware\"\n\n{metadata}"),
)
.unwrap();
let mut manifest = String::new();
for (identifier, layout) in boards {
manifest.push_str(&std::format!(
"[[board]]\nidentifier = \"{identifier}\"\nprotocol = \"espressif\"\nchip = \"esp32\"\nlayout = \"../layouts/{layout}\"\n"
));
}
fs::write(directory.join("boards/b.toml"), manifest).unwrap();
for (target, source) in [
("a.toml", "nrf52840-arduino.toml"),
("b.toml", "growing.toml"),
] {
fs::copy(fixture(source), directory.join("layouts").join(target)).unwrap();
}
directory
}
const BOARD: &str = "[package.metadata.nanoflash]\nboard = \"boards/b.toml\"\n";
fn nrf52840_regions() -> String {
memory_regions(
&Layout::from_toml(&fs::read_to_string(fixture("nrf52840-arduino.toml")).unwrap())
.unwrap()
.resolve()
.unwrap(),
)
.unwrap()
}
#[test]
fn package_layout_is_used() {
let directory = package("package", BOARD, &[("b", "a.toml")]);
let output = scratch("package-output");
let generated = Build::package().generate_into(&directory, &output).unwrap();
let resolved =
Layout::from_toml(&fs::read_to_string(fixture("nrf52840-arduino.toml")).unwrap())
.unwrap()
.resolve()
.unwrap();
assert_eq!(
fs::read_to_string(&generated.constants).unwrap(),
rust_constants(&resolved).unwrap()
);
assert_eq!(generated.memory_script, None);
assert_eq!(
generated.inputs,
[
directory.join("Cargo.toml"),
directory.join("boards/b.toml"),
directory.join("boards/../layouts/a.toml")
]
);
fs::remove_dir_all(&directory).unwrap();
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn layout_inputs_are_the_layout() {
let output = scratch("layout-inputs");
let generated = Build::layout(fixture("nrf52840-arduino.toml"))
.generate_into(Path::new("unused"), &output)
.unwrap();
assert_eq!(generated.inputs, [fixture("nrf52840-arduino.toml")]);
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn memory_writes_memory_x() {
let output = scratch("memory");
let generated = Build::layout(fixture("nrf52840-arduino.toml"))
.memory("RAM", 0x2000_0000, 0x40000)
.generate_into(Path::new(""), &output)
.unwrap();
let path = output.join("memory.x");
assert_eq!(generated.memory_script, Some(path.clone()));
let mut expected = nrf52840_regions();
expected.truncate(expected.len() - 2);
expected.push_str("\x20 RAM : ORIGIN = 0x20000000, LENGTH = 0x00040000\n}\n");
expected.push_str(&std::format!("{MEMORY_MARKER} = 1;\n"));
assert_eq!(fs::read_to_string(path).unwrap(), expected);
assert_eq!(
fs::read_to_string(&generated.linker_script).unwrap(),
nrf52840_regions()
);
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn memory_writes_a_guard_that_needs_the_marker() {
let output = scratch("guard");
let generated = Build::layout(fixture("nrf52840-arduino.toml"))
.memory("RAM", 0x2000_0000, 0x40000)
.generate_into(Path::new(""), &output)
.unwrap();
let path = output.join("nanoflash_memory_guard.x");
assert_eq!(generated.memory_guard, Some(path.clone()));
let guard = fs::read_to_string(path).unwrap();
assert!(
guard.contains(&std::format!("ASSERT({MEMORY_MARKER} == 1, \"")),
"{guard}"
);
assert!(guard.contains("not found"), "{guard}");
for name in ["memory.x", "package directory", "workspace root"] {
assert!(guard.contains(name), "{name}: {guard}");
}
assert_eq!(guard.matches('"').count(), 2, "{guard}");
assert!(!guard.contains("DEFINED"), "{guard}");
let memory = fs::read_to_string(output.join("memory.x")).unwrap();
assert!(
memory.contains(&std::format!("{MEMORY_MARKER} = 1;")),
"{memory}"
);
let regions = fs::read_to_string(&generated.linker_script).unwrap();
assert!(!regions.contains(MEMORY_MARKER), "{regions}");
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn no_guard_without_memory_and_a_stale_guard_is_removed() {
let output = scratch("guard-stale");
Build::layout(fixture("nrf52840-arduino.toml"))
.memory("RAM", 0x2000_0000, 0x40000)
.generate_into(Path::new(""), &output)
.unwrap();
assert!(output.join("nanoflash_memory_guard.x").exists());
let generated = Build::layout(fixture("nrf52840-arduino.toml"))
.generate_into(Path::new(""), &output)
.unwrap();
assert_eq!(generated.memory_guard, None);
assert!(!output.join("nanoflash_memory_guard.x").exists());
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn memory_naming_a_region_of_the_layout_is_refused() {
let output = scratch("memory-duplicate");
let error = Build::layout(fixture("nrf52840-arduino.toml"))
.memory("FLASH", 0x2000_0000, 0x40000)
.generate_into(Path::new(""), &output)
.unwrap_err();
assert!(matches!(
error,
BuildError::Table(TableError::DuplicateRegion { .. })
));
assert!(error.to_string().contains("FLASH"), "{error}");
assert!(!output.join("memory.x").exists());
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn memory_x_in_the_package_is_refused() {
let directory = package("shadow", BOARD, &[("b", "a.toml")]);
let shadow = directory.join("memory.x");
fs::write(&shadow, "INCLUDE nanoflash_memory.x\n").unwrap();
let output = scratch("shadow-output");
let error = Build::package()
.memory("RAM", 0x2000_0000, 0x40000)
.generate_into(&directory, &output)
.unwrap_err();
assert!(matches!(&error, BuildError::MemoryScriptShadowed { path } if *path == shadow));
assert_eq!(
error.to_string(),
std::format!(
"{} would be linked instead of the memory.x nanoflash writes, since the linker looks first in its working directory, which is the workspace root of the package, or its package directory without a workspace: remove it, or keep it with INCLUDE nanoflash_memory.x and do not call Build::memory",
shadow.display()
)
);
assert!(!output.join("memory.x").exists());
let generated = Build::package().generate_into(&directory, &output).unwrap();
assert_eq!(generated.memory_script, None);
fs::remove_dir_all(&directory).unwrap();
fs::remove_dir_all(&output).unwrap();
}
fn workspace(name: &str) -> (PathBuf, PathBuf) {
let root = scratch(name);
fs::write(
root.join("Cargo.toml"),
"[workspace]\nmembers = [\"firmware\"]\n",
)
.unwrap();
let member = root.join("firmware");
fs::create_dir_all(member.join("boards")).unwrap();
fs::create_dir_all(member.join("layouts")).unwrap();
fs::write(
member.join("Cargo.toml"),
std::format!("[package]\nname = \"firmware\"\n\n{BOARD}"),
)
.unwrap();
fs::write(
member.join("boards/b.toml"),
"[[board]]\nidentifier = \"b\"\nprotocol = \"espressif\"\nchip = \"esp32\"\nlayout = \"../layouts/a.toml\"\n",
)
.unwrap();
fs::copy(
fixture("nrf52840-arduino.toml"),
member.join("layouts/a.toml"),
)
.unwrap();
(root, member)
}
#[test]
fn memory_x_in_the_workspace_root_is_refused() {
let (root, member) = workspace("workspace-shadow");
let shadow = root.join("memory.x");
fs::write(&shadow, "MEMORY { FLASH : ORIGIN = 0, LENGTH = 1 }\n").unwrap();
let output = scratch("workspace-shadow-output");
let error = Build::package()
.memory("RAM", 0x2000_0000, 0x40000)
.generate_into(&member, &output)
.unwrap_err();
assert!(matches!(&error, BuildError::MemoryScriptShadowed { path } if *path == shadow));
assert!(!output.join("memory.x").exists());
Build::package().generate_into(&member, &output).unwrap();
fs::remove_file(&shadow).unwrap();
let member_shadow = member.join("memory.x");
fs::write(&member_shadow, "INCLUDE nanoflash_memory.x\n").unwrap();
let error = Build::package()
.memory("RAM", 0x2000_0000, 0x40000)
.generate_into(&member, &output)
.unwrap_err();
assert!(
matches!(&error, BuildError::MemoryScriptShadowed { path } if *path == member_shadow)
);
fs::remove_file(&member_shadow).unwrap();
Build::package()
.memory("RAM", 0x2000_0000, 0x40000)
.generate_into(&member, &output)
.unwrap();
assert!(output.join("memory.x").exists());
fs::remove_dir_all(&root).unwrap();
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn a_stale_memory_x_is_removed_when_memory_is_not_called() {
let output = scratch("stale");
Build::layout(fixture("nrf52840-arduino.toml"))
.memory("RAM", 0x2000_0000, 0x40000)
.generate_into(Path::new(""), &output)
.unwrap();
assert!(output.join("memory.x").exists());
let generated = Build::layout(fixture("nrf52840-arduino.toml"))
.generate_into(Path::new(""), &output)
.unwrap();
assert_eq!(generated.memory_script, None);
assert!(!output.join("memory.x").exists());
Build::layout(fixture("nrf52840-arduino.toml"))
.generate_into(Path::new(""), &output)
.unwrap();
Build::layout(fixture("nrf52840-arduino.toml"))
.memory("RAM", 0x2000_0000, 0x40000)
.generate_into(Path::new(""), &output)
.unwrap();
let error = Build::layout(fixture("nrf52840-arduino.toml"))
.memory("FLASH", 0x2000_0000, 0x40000)
.generate_into(Path::new(""), &output)
.unwrap_err();
assert!(matches!(error, BuildError::Table(_)), "{error}");
assert!(output.join("memory.x").exists());
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn the_format_of_the_board_manifest_is_read_from_its_content() {
let json = "{\"board\": [{\"identifier\": \"b\", \"protocol\": \"espressif\", \"chip\": \"esp32\", \"layout\": \"../layouts/a.toml\"}]}";
for name in ["b.JSON", "b.json", "b.manifest"] {
let directory = package(
"manifest-format",
&std::format!("[package.metadata.nanoflash]\nboard = \"boards/{name}\"\n"),
&[("b", "a.toml")],
);
fs::write(directory.join("boards").join(name), json).unwrap();
let output = scratch("manifest-format-output");
let generated = Build::package().generate_into(&directory, &output);
assert!(generated.is_ok(), "{name}: {generated:?}");
fs::remove_dir_all(&directory).unwrap();
fs::remove_dir_all(&output).unwrap();
}
}
#[test]
fn package_without_a_board() {
let directory = package("no-board", "", &[("b", "a.toml")]);
let output = scratch("no-board-output");
let error = Build::package()
.generate_into(&directory, &output)
.unwrap_err();
let cargo_toml = directory.join("Cargo.toml");
assert!(matches!(&error, BuildError::NoBoard { cargo_toml: path } if *path == cargo_toml));
assert_eq!(
error.to_string(),
std::format!(
"{} names no board: add [package.metadata.nanoflash] board = \"boards/board.toml\", or call Build::layout with the layout file",
cargo_toml.display()
)
);
fs::remove_dir_all(&directory).unwrap();
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn package_with_bad_metadata_or_a_missing_manifest() {
let directory = package(
"bad-metadata",
"[package.metadata.nanoflash]\nport = \"x\"\n",
&[("b", "a.toml")],
);
let output = scratch("bad-metadata-output");
let error = Build::package()
.generate_into(&directory, &output)
.unwrap_err();
assert!(matches!(error, BuildError::Package(_)), "{error}");
assert!(error.to_string().contains("unknown key"), "{error}");
fs::remove_file(directory.join("boards/b.toml")).unwrap();
fs::write(
directory.join("Cargo.toml"),
std::format!("[package]\nname = \"firmware\"\n\n{BOARD}"),
)
.unwrap();
let error = Build::package()
.generate_into(&directory, &output)
.unwrap_err();
assert!(matches!(error, BuildError::Io { .. }), "{error}");
fs::write(directory.join("boards/b.toml"), "not toml = [").unwrap();
let error = Build::package()
.generate_into(&directory, &output)
.unwrap_err();
assert!(matches!(error, BuildError::Manifest { .. }), "{error}");
assert!(
error.to_string().starts_with(&std::format!(
"cannot use the board manifest {}: ",
directory.join("boards/b.toml").display()
)),
"{error}"
);
fs::remove_dir_all(&directory).unwrap();
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn several_layouts_need_an_identifier() {
let directory = package("several", BOARD, &[("one", "a.toml"), ("two", "b.toml")]);
let output = scratch("several-output");
let error = Build::package()
.generate_into(&directory, &output)
.unwrap_err();
assert!(matches!(&error, BuildError::Manifest { .. }), "{error}");
let message = error.to_string();
assert!(
message.contains("\"one\"") && message.contains("\"two\""),
"{message}"
);
assert!(message.contains("board-identifier"), "{message}");
fs::write(
directory.join("Cargo.toml"),
"[package]\nname = \"firmware\"\n\n[package.metadata.nanoflash]\nboard = \"boards/b.toml\"\nboard-identifier = \"two\"\n",
)
.unwrap();
let generated = Build::package().generate_into(&directory, &output).unwrap();
assert!(
fs::read_to_string(&generated.constants)
.unwrap()
.contains("FLASH_MINIMUM_SIZE")
);
fs::remove_dir_all(&directory).unwrap();
fs::remove_dir_all(&output).unwrap();
}
#[test]
fn growing_layouts_keep_their_rules() {
let directory = package("growing", BOARD, &[("b", "b.toml")]);
let output = scratch("growing-output");
let generated = Build::package()
.memory("RAM", 0x2000_0000, 0x40000)
.generate_into(&directory, &output)
.unwrap();
let text = fs::read_to_string(generated.memory_script.unwrap()).unwrap();
assert!(
text.contains(
"\x20 /* STORAGE grows with the flash of the device: LENGTH is its size on the minimum flash. */\n\x20 STORAGE : ORIGIN = 0x00050000, LENGTH = 0x0002F000\n"
),
"{text}"
);
assert!(
text.contains("/* LOG moves with the flash of the device: no region. */"),
"{text}"
);
assert!(!text.contains("LOG :"), "{text}");
assert!(
text.ends_with(&std::format!(
"\x20 RAM : ORIGIN = 0x20000000, LENGTH = 0x00040000\n}}\n{MEMORY_MARKER} = 1;\n"
)),
"{text}"
);
fs::remove_dir_all(&directory).unwrap();
fs::remove_dir_all(&output).unwrap();
}
}