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.
13///
14/// This function reads the contents of a file and creates a `SourceText`.
15///
16/// # Arguments
17///
18/// * `path` - The file system path to read from
19///
20/// # Returns
21///
22/// A `Result` containing the `SourceText` if successful, or an `OakError` if reading fails
23///
24/// # Examples
25///
26/// ```ignore
27/// let path = std::path::Path::new("source.rs");
28/// let source = source_from_path(path)?;
29/// ```
30pub fn source_from_path(path: &std::path::Path) -> Result<SourceText, OakError> {
31 match std::fs::read_to_string(path) {
32 Ok(o) => Ok(SourceText::new(o)),
33 Err(e) => Err(OakError::custom_error(format!("failed to read file {}: {}", path.display(), e))),
34 }
35}
36
37/// Opens a file and returns a file handle.
38///
39/// # Arguments
40///
41/// * `path` - The file system path to open
42///
43/// # Returns
44///
45/// A `Result` containing the file handle if successful, or an `OakError` if opening fails
46///
47/// # Examples
48///
49/// ```ignore
50/// let path = std::path::Path::new("source.rs");
51/// let file = open_file(path)?;
52/// ```
53pub fn open_file(path: &std::path::Path) -> Result<File, OakError> {
54 match File::open(path) {
55 Ok(o) => Ok(o),
56 Err(e) => Err(OakError::custom_error(format!("failed to open file {}: {}", path.display(), e))),
57 }
58}
59
60/// Creates a file and its parent directories.
61pub fn create_file(path: &std::path::Path) -> Result<std::fs::File, OakError> {
62 if let Some(parent) = path.parent() {
63 std::fs::create_dir_all(parent).map_err(|e| OakError::custom_error(e.to_string()))?;
64 }
65 std::fs::File::create(path).map_err(|e| OakError::custom_error(e.to_string()))
66}