Skip to content

Commit

Permalink
Avoid second fs write
Browse files Browse the repository at this point in the history
  • Loading branch information
jayvdb committed Jan 14, 2024
1 parent d3f393e commit e2e35e3
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 15 deletions.
8 changes: 0 additions & 8 deletions butane_core/src/migrations/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ pub trait Filesystem: Debug {
fn list_dir(&self, path: &Path) -> std::io::Result<Vec<PathBuf>>;
/// Opens a file for writing. Creates it if it does not exist. Truncates it otherwise.
fn write(&self, path: &Path) -> std::io::Result<Box<dyn Write>>;
/// Opens a file for writing in append mode. Fails if file does not exist.
fn append(&self, path: &Path) -> std::io::Result<Box<dyn Write>>;
/// Opens a file for reading.
fn read(&self, path: &Path) -> std::io::Result<Box<dyn Read>>;
}
Expand All @@ -34,12 +32,6 @@ impl Filesystem for OsFilesystem {
fn write(&self, path: &Path) -> std::io::Result<Box<dyn Write>> {
std::fs::File::create(path).map(|f| Box::new(f) as Box<dyn Write>)
}
fn append(&self, path: &Path) -> std::io::Result<Box<dyn Write>> {
std::fs::OpenOptions::new()
.append(true)
.open(path)
.map(|f| Box::new(f) as Box<dyn Write>)
}
fn read(&self, path: &Path) -> std::io::Result<Box<dyn Read>> {
std::fs::File::open(path).map(|f| Box::new(f) as Box<dyn Read>)
}
Expand Down
13 changes: 6 additions & 7 deletions butane_core/src/migrations/fsmigrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,15 @@ impl FsMigration {
fn write_contents(&self, fname: &str, contents: &[u8]) -> Result<()> {
self.ensure_dir()?;
let path = self.root.join(fname);
let mut contents: Vec<u8> = contents.into();
if contents[contents.len() - 1] != b'\n' {
contents.push(b'\n');
}
self.fs
.write(&path)?
.write_all(contents)
.write_all(&contents)
.map_err(<std::io::Error as Into<Error>>::into)?;
if contents[contents.len() - 1] != b'\n' {
self.fs
.append(&path)?
.write(b"\n")
.map_err(<std::io::Error as Into<Error>>::into)?;
}

Ok(())
}

Expand Down

0 comments on commit e2e35e3

Please sign in to comment.