# IronShell I/O Utilities
# File operations and data serialization
# ===== JSON File Operations =====
# Read JSON from file and parse
pub let read_json = fn(path) => json_parse(cat(path))
# ===== Text File Operations =====
# Read file as array of lines
pub let read_lines = fn(path) => split(cat(path), "\n")
# Read file and trim whitespace
pub let read_trimmed = fn(path) => trim(cat(path))
# ===== File Path Utilities =====
# The path with backslashes as slashes and trailing slashes removed
let path_clean = fn(path) => regex_replace(replace(path, "\\", "/"), "/+$", "")
# Get filename from path (works with both / and \; a trailing slash is ignored)
pub let file_name = fn(path) => last(split(path_clean(path), "/"))
# Get file extension of the last path component, without its dot. "" when there
# is none: a leading dot does not start one (".bashrc" has no extension).
pub let file_ext = fn(path) => match {
_ if regex_match(regex_replace(file_name(path), "^\\.+", ""), "\\.") => last(split(file_name(path), ".")),
_ => ""
}
# Get directory from path: "/" for a file directly under the root, "" for a
# bare name with no directory part
pub let file_dir = fn(path) => match {
_ if !regex_match(path_clean(path), "/") => "",
_ if regex_match(path_clean(path), "^/[^/]*$") => "/",
_ => regex_replace(path_clean(path), "/[^/]*$", "")
}
# Join path components with one slash at each joint: "a/" + "/b" is "a/b"
pub let path_join = fn(parts) => regex_replace(join(parts, "/"), "/{2,}", "/")
# ===== Data Serialization =====
# Convert to pretty-printed JSON (two spaces per level)
pub let to_json_pretty = fn(data) => to_json(data, 2)
# Parse YAML content
pub let parse_yaml = fn(content) => from_yaml(content)
# Parse CSV content with header
pub let parse_csv = fn(content) => from_csv(content)
# Export all public items
export {
read_json,
read_lines, read_trimmed,
file_ext, file_name, file_dir, path_join,
to_json_pretty, parse_yaml, parse_csv
}