-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
1 parent
76df690
commit d3dd9c9
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters