risingwave_sqlsmith/
utils.rs

1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fs::File;
16use std::io::Write;
17use std::path::Path;
18
19use anyhow::{Result, anyhow};
20
21pub(crate) fn read_file_contents<P: AsRef<Path>>(filepath: P) -> Result<String> {
22    std::fs::read_to_string(filepath.as_ref()).map_err(|e| {
23        anyhow!(
24            "Failed to read contents from {} due to {e}",
25            filepath.as_ref().display()
26        )
27    })
28}
29
30pub(crate) fn create_file<P: AsRef<Path>>(filepath: P) -> Result<File> {
31    std::fs::File::create(filepath.as_ref()).map_err(|e| {
32        anyhow!(
33            "Failed to create file: {} due to {e}",
34            filepath.as_ref().display()
35        )
36    })
37}
38
39pub(crate) fn write_to_file<S: AsRef<str>>(file: &mut File, contents: S) -> Result<()> {
40    let s = contents.as_ref().as_bytes();
41    file.write_all(s)
42        .map_err(|e| anyhow!("Failed to write file due to {e}"))
43}