Skip to content

Commit

Permalink
Add artifact writer
Browse files Browse the repository at this point in the history
Summary: We write artifacts in several places through the TD. This unifies and dedupes them.

Reviewed By: ndmitchell

Differential Revision: D62555601

fbshipit-source-id: 613c36ba79ca771a90d2268cd6ef3f570c1aabd1
  • Loading branch information
Fedir Panasenko authored and facebook-github-bot committed Sep 12, 2024
1 parent 76df690 commit d3dd9c9
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
57 changes: 57 additions & 0 deletions td_util/src/file_writer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under both the MIT license found in the
* LICENSE-MIT file in the root directory of this source tree and the Apache
* License, Version 2.0 found in the LICENSE-APACHE file in the root directory
* of this source tree.
*/

use std::fs::OpenOptions;
use std::io::BufWriter;
use std::io::Write;
use std::path::PathBuf;

use anyhow::Context;

pub fn file_writer(file_path: &PathBuf) -> anyhow::Result<impl Write> {
let file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(file_path)
.with_context(|| format!("Unable to open file `{}` for writing", file_path.display()))?;
Ok(BufWriter::new(file))
}

#[cfg(test)]
mod tests {
use std::fs;
use std::io::Write;
use std::path::PathBuf;

use tempfile::TempDir;

use crate::file_writer::file_writer;

static DATA: &str = "Artifact data";

#[test]
pub fn test_write_success() {
let out_dir = TempDir::new().unwrap();
let out_path = out_dir.path().join("test_artifact.json");

file_writer(&out_path)
.unwrap()
.write_all(DATA.as_bytes())
.unwrap();

let written = fs::read_to_string(&out_path).unwrap();
assert_eq!(written, DATA);
}

#[test]
pub fn test_write_error() {
assert!(file_writer(&PathBuf::from("/invalid/file/path")).is_err());
}
}
1 change: 1 addition & 0 deletions td_util/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod cli;
pub mod command;
pub mod directives;
pub mod executor;
pub mod file_writer;
pub mod json;
pub mod knobs;
pub mod no_hash;
Expand Down

0 comments on commit d3dd9c9

Please sign in to comment.