Skip to main content

oak_core/helpers/
mod.rs

1//! Helper utilities for common operations in the Oak Core parsing framework.
2//!
3//! This module provides utility functions for file system operations
4//! and other common tasks that are useful when working with the parsing framework.
5
6use crate::errors::OakError;
7
8use crate::source::SourceText;
9
10use std::fs::File;
11
12/// Reads source text from a file path.
13pub fn source_from_path(path: &std::path::Path) -> Result<SourceText, OakError> {
14    match std::fs::read_to_string(path) {
15        Ok(o) => Ok(SourceText::new(o)),
16        Err(e) => Err(OakError::custom_error(format!("failed to read file {}: {}", path.display(), e))),
17    }
18}
19
20/// Opens a file and returns a file handle.
21pub fn open_file(path: &std::path::Path) -> Result<File, OakError> {
22    match File::open(path) {
23        Ok(o) => Ok(o),
24        Err(e) => Err(OakError::custom_error(format!("failed to open file {}: {}", path.display(), e))),
25    }
26}
27
28/// Creates a file and its parent directories.
29pub fn create_file(path: &std::path::Path) -> Result<std::fs::File, OakError> {
30    if let Some(parent) = path.parent() {
31        std::fs::create_dir_all(parent).map_err(|e| OakError::custom_error(e.to_string()))?
32    }
33    std::fs::File::create(path).map_err(|e| OakError::custom_error(e.to_string()))
34}