switchboard_common/
utils.rs

1use crate::SbError;
2
3use std::{fs, sync::Arc};
4
5/// Return the unix timestamp in seconds.
6pub fn unix_timestamp() -> i64 {
7    std::time::SystemTime::now()
8        .duration_since(std::time::UNIX_EPOCH)
9        .unwrap_or_default()
10        .as_secs()
11        .try_into()
12        .unwrap_or(0)
13}
14
15/// Read a file to a string and trim any leading or trailing whitespace.
16pub fn read_and_trim_file(file_path: &str) -> Result<String, SbError> {
17    // Check if the file exists
18    if !std::path::Path::new(file_path).exists() {
19        return Err(SbError::CustomError {
20            message: "File not found".to_string(),
21            source: Arc::new(std::io::Error::new(
22                std::io::ErrorKind::NotFound,
23                format!("File not found: {}", file_path),
24            )),
25        });
26    }
27
28    // Read the file to a String
29    let content = fs::read_to_string(file_path).map_err(|e| SbError::CustomError {
30        message: "Failed to read file".to_string(),
31        source: Arc::new(e),
32    })?;
33
34    // Trim the content and return it
35    Ok(content.trim().to_string())
36}