1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use std::{
    fs::File,
    io::{self, Read, Write},
    path::{Path, PathBuf},
};

use parking_lot::Mutex;
use tracing::warn;

static LOCK: Mutex<()> = Mutex::new(());

pub fn file_to_string(file_name: &str) -> Result<String, io::Error> {
    if !PathBuf::from(file_name).exists() {
        warn!("file not exist:{}", file_name);
        return Ok("".to_string());
    }
    let file = File::open(file_name)?;
    file_to_string_impl(&file)
}

pub fn file_to_string_impl(file: &File) -> Result<String, io::Error> {
    let file_length = file.metadata()?.len() as usize;
    let mut data = vec![0; file_length];
    let result = file.take(file_length as u64).read_exact(&mut data);

    match result {
        Ok(_) => Ok(String::from_utf8_lossy(&data).to_string()),
        Err(_) => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "Failed to read file",
        )),
    }
}

pub fn string_to_file(str_content: &str, file_name: &str) -> io::Result<()> {
    let lock = LOCK.lock();

    let bak_file = format!("{}.bak", file_name);

    // Read previous content and create a backup
    if let Ok(prev_content) = file_to_string(file_name) {
        string_to_file_not_safe(&prev_content, &bak_file)?;
    }

    // Write new content to the file
    string_to_file_not_safe(str_content, file_name)?;
    drop(lock);
    Ok(())
}

fn string_to_file_not_safe(str_content: &str, file_name: &str) -> io::Result<()> {
    // Create parent directories if they don't exist
    if let Some(parent) = Path::new(file_name).parent() {
        std::fs::create_dir_all(parent)?;
    }
    let file = File::create(file_name)?;

    write_string_to_file(&file, str_content, "UTF-8")
}

fn write_string_to_file(file: &File, data: &str, _encoding: &str) -> io::Result<()> {
    let mut os = io::BufWriter::new(file);

    os.write_all(data.as_bytes())?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_file_to_string() {
        // Create a temporary file for testing
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let file_path = temp_file.path().to_str().unwrap();

        // Write some content to the file
        let content = "Hello, World!";
        std::fs::write(file_path, content).unwrap();

        // Call the file_to_string function
        let result = file_to_string(file_path);

        // Check if the result is Ok and contains the expected content
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), content);
    }

    #[test]
    fn test_string_to_file() {
        // Create a temporary file for testing
        let temp_file = tempfile::NamedTempFile::new().unwrap();
        let file_path = temp_file.path().to_str().unwrap();

        // Call the string_to_file function
        let content = "Hello, World!";
        let result = string_to_file(content, file_path);

        // Check if the result is Ok and the file was created with the expected content
        assert!(result.is_ok());
        assert_eq!(std::fs::read_to_string(file_path).unwrap(), content);
    }
}