Skip to content

Commit

Permalink
Improve filesystem functions and error messages (#251)
Browse files Browse the repository at this point in the history
  • Loading branch information
ia0 authored Oct 13, 2023
1 parent ed65105 commit d45d307
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 16 deletions.
74 changes: 74 additions & 0 deletions crates/xtask/src/fs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Wrappers around `std::fs` with descriptive errors.
use std::fs::Metadata;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};

pub fn canonicalize(path: impl AsRef<Path>) -> Result<PathBuf> {
let name = path.as_ref().display();
std::fs::canonicalize(path.as_ref()).with_context(|| format!("canonicalizing {name}"))
}

pub fn copy(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<u64> {
let src = from.as_ref().display();
let dst = to.as_ref().display();
create_parent(to.as_ref())?;
std::fs::copy(from.as_ref(), to.as_ref()).with_context(|| format!("copying {src} to {dst}"))
}

fn create_dir_all(path: impl AsRef<Path>) -> Result<()> {
let name = path.as_ref().display();
std::fs::create_dir_all(path.as_ref()).with_context(|| format!("creating {name}"))
}

fn create_parent(path: impl AsRef<Path>) -> Result<()> {
if let Some(parent) = path.as_ref().parent() {
create_dir_all(parent)?;
}
Ok(())
}

pub fn metadata(path: impl AsRef<Path>) -> Result<Metadata> {
let name = path.as_ref().display();
std::fs::metadata(path.as_ref()).with_context(|| format!("reading {name} metadata"))
}

pub fn read(path: impl AsRef<Path>) -> Result<Vec<u8>> {
let name = path.as_ref().display();
std::fs::read(path.as_ref()).with_context(|| format!("reading {name}"))
}

pub fn remove_file(path: impl AsRef<Path>) -> Result<()> {
let name = path.as_ref().display();
std::fs::remove_file(path.as_ref()).with_context(|| format!("removing {name}"))
}

pub fn touch(path: impl AsRef<Path>) -> Result<()> {
if path.as_ref().exists() {
return Ok(());
}
write(path, "")
}

pub fn write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<()> {
let name = path.as_ref().display();
let contents = contents.as_ref();
create_parent(path.as_ref())?;
std::fs::write(path.as_ref(), contents).with_context(|| format!("writing {name}"))?;
Ok(())
}
31 changes: 15 additions & 16 deletions crates/xtask/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ use rustc_demangle::demangle;
use sha2::{Digest, Sha256};
use strum::{Display, EnumString};

mod fs;

#[derive(Parser)]
struct Flags {
#[clap(flatten)]
Expand Down Expand Up @@ -329,15 +331,15 @@ impl AppletOptions {
fn execute_wasm(&self, main: &MainOptions) -> Result<()> {
let wasm = "target/wasefire/applet.wasm";
if main.size {
println!("Initial applet size: {}", std::fs::metadata(wasm)?.len());
println!("Initial applet size: {}", fs::metadata(wasm)?.len());
}
if self.strip.get() {
let mut strip = wrap_command()?;
strip.arg("wasm-strip");
strip.arg(wasm);
execute_command(&mut strip)?;
if main.size {
println!("Stripped applet size: {}", std::fs::metadata(wasm)?.len());
println!("Stripped applet size: {}", fs::metadata(wasm)?.len());
}
}
if self.opt.get() {
Expand All @@ -354,7 +356,7 @@ impl AppletOptions {
opt.args([wasm, "-o", wasm]);
execute_command(&mut opt)?;
if main.size {
println!("Optimized applet size: {}", std::fs::metadata(wasm)?.len());
println!("Optimized applet size: {}", fs::metadata(wasm)?.len());
}
}
Ok(())
Expand Down Expand Up @@ -447,14 +449,11 @@ impl RunnerOptions {
}
cargo.env("RUSTFLAGS", rustflags.join(" "));
cargo.current_dir(format!("crates/runner-{}", self.name));
if !Path::new("target/wasefire/applet.wasm").exists() {
std::fs::create_dir_all("target/wasefire")?;
std::fs::write("target/wasefire/applet.wasm", "")?;
}
fs::touch("target/wasefire/applet.wasm")?;
if run && self.name == "host" {
let path = Path::new("target/wasefire/storage.bin");
if self.erase_flash && path.exists() {
std::fs::remove_file(path)?;
fs::remove_file(path)?;
}
replace_command(cargo);
} else {
Expand Down Expand Up @@ -491,7 +490,7 @@ impl RunnerOptions {
execute_command(&mut size)?;
}
if let Some(stack_sizes) = self.stack_sizes {
let elf = std::fs::read(&elf)?;
let elf = fs::read(&elf)?;
let symbols = stack_sizes::analyze_executable(&elf)?;
assert!(symbols.have_32_bit_addresses);
assert!(symbols.undefined.is_empty());
Expand Down Expand Up @@ -612,21 +611,21 @@ fn ensure_command(cmd: &[&str]) -> Result<()> {
}

fn wrap_command() -> Result<Command> {
Ok(Command::new(std::fs::canonicalize("./scripts/wrapper.sh")?))
Ok(Command::new(fs::canonicalize("./scripts/wrapper.sh")?))
}

/// Copies a file if its destination .hash changed.
///
/// Returns whether the copy took place.
fn copy_if_changed(src: &str, dst: &str) -> Result<bool> {
let dst_file = format!("{dst}.hash");
let src_hash = Sha256::digest(std::fs::read(src)?);
let changed = !Path::new(dst).exists()
|| !Path::new(&dst_file).exists()
|| std::fs::read(&dst_file)? != *src_hash;
let src_hash = Sha256::digest(fs::read(src)?);
let dst_path = Path::new(dst);
let changed =
!dst_path.exists() || !Path::new(&dst_file).exists() || fs::read(&dst_file)? != *src_hash;
if changed {
std::fs::copy(src, dst)?;
std::fs::write(&dst_file, src_hash)?;
fs::copy(src, dst)?;
fs::write(&dst_file, src_hash)?;
}
Ok(changed)
}
Expand Down

0 comments on commit d45d307

Please sign in to comment.