rocketmq_common/utils/
file_utils.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18use std::fs::File;
19use std::io::Read;
20use std::io::Write;
21use std::io::{self};
22use std::path::Path;
23use std::path::PathBuf;
24
25use parking_lot::Mutex;
26use tracing::warn;
27
28static LOCK: Mutex<()> = Mutex::new(());
29
30pub fn file_to_string(file_name: &str) -> Result<String, io::Error> {
31    if !PathBuf::from(file_name).exists() {
32        warn!("file not exist:{}", file_name);
33        return Ok("".to_string());
34    }
35    let file = File::open(file_name)?;
36    file_to_string_impl(&file)
37}
38
39pub fn file_to_string_impl(file: &File) -> Result<String, io::Error> {
40    let file_length = file.metadata()?.len() as usize;
41    let mut data = vec![0; file_length];
42    let result = file.take(file_length as u64).read_exact(&mut data);
43
44    match result {
45        Ok(_) => Ok(String::from_utf8_lossy(&data).to_string()),
46        Err(_) => Err(io::Error::new(
47            io::ErrorKind::InvalidData,
48            "Failed to read file",
49        )),
50    }
51}
52
53pub fn string_to_file(str_content: &str, file_name: &str) -> io::Result<()> {
54    let lock = LOCK.lock(); //todo enhancement: not use global lock
55
56    let bak_file = format!("{file_name}.bak");
57
58    // Read previous content and create a backup
59    if let Ok(prev_content) = file_to_string(file_name) {
60        string_to_file_not_safe(&prev_content, &bak_file)?;
61    }
62
63    // Write new content to the file
64    string_to_file_not_safe(str_content, file_name)?;
65    drop(lock);
66    Ok(())
67}
68
69fn string_to_file_not_safe(str_content: &str, file_name: &str) -> io::Result<()> {
70    // Create parent directories if they don't exist
71    if let Some(parent) = Path::new(file_name).parent() {
72        std::fs::create_dir_all(parent)?;
73    }
74    let file = File::create(file_name)?;
75
76    write_string_to_file(&file, str_content, "UTF-8")
77}
78
79fn write_string_to_file(file: &File, data: &str, _encoding: &str) -> io::Result<()> {
80    let mut os = io::BufWriter::new(file);
81
82    os.write_all(data.as_bytes())?;
83
84    Ok(())
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    #[test]
92    fn test_file_to_string() {
93        // Create a temporary file for testing
94        let temp_file = tempfile::NamedTempFile::new().unwrap();
95        let file_path = temp_file.path().to_str().unwrap();
96
97        // Write some content to the file
98        let content = "Hello, World!";
99        std::fs::write(file_path, content).unwrap();
100
101        // Call the file_to_string function
102        let result = file_to_string(file_path);
103
104        // Check if the result is Ok and contains the expected content
105        assert!(result.is_ok());
106        assert_eq!(result.unwrap(), content);
107    }
108
109    #[test]
110    fn test_string_to_file() {
111        // Create a temporary file for testing
112        let temp_file = tempfile::NamedTempFile::new().unwrap();
113        let file_path = temp_file.path().to_str().unwrap();
114
115        // Call the string_to_file function
116        let content = "Hello, World!";
117        let result = string_to_file(content, file_path);
118
119        // Check if the result is Ok and the file was created with the expected content
120        assert!(result.is_ok());
121        assert_eq!(std::fs::read_to_string(file_path).unwrap(), content);
122    }
123}