Skip to content

Commit

Permalink
Add read_to_string(path) function (#2507)
Browse files Browse the repository at this point in the history
  • Loading branch information
begoon authored Dec 10, 2024
1 parent 37dc2e4 commit 464fdbc
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1842,6 +1842,8 @@ which will halt execution.
- `path_exists(path)` - Returns `true` if the path points at an existing entity
and `false` otherwise. Traverses symbolic links, and returns `false` if the
path is inaccessible or points to a broken symlink.
- `read_to_string(path)`<sup>master</sup> - Returns the content of file at
`path` as string.

##### Error Reporting

Expand Down
6 changes: 6 additions & 0 deletions src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ pub(crate) fn get(name: &str) -> Option<Function> {
"path_exists" => Unary(path_exists),
"prepend" => Binary(prepend),
"quote" => Unary(quote),
"read_to_string" => Unary(read_to_string),
"replace" => Ternary(replace),
"replace_regex" => Ternary(replace_regex),
"semver_matches" => Binary(semver_matches),
Expand Down Expand Up @@ -528,6 +529,11 @@ fn quote(_context: Context, s: &str) -> FunctionResult {
Ok(format!("'{}'", s.replace('\'', "'\\''")))
}

fn read_to_string(context: Context, filename: &str) -> FunctionResult {
fs::read_to_string(context.evaluator.context.working_directory().join(filename))
.map_err(|err| format!("I/O error reading `{filename}`: {err}"))
}

fn replace(_context: Context, s: &str, from: &str, to: &str) -> FunctionResult {
Ok(s.replace(from, to))
}
Expand Down
20 changes: 20 additions & 0 deletions tests/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1258,3 +1258,23 @@ fn style_unknown() {
.status(EXIT_FAILURE)
.run();
}

#[test]
fn read_to_string() {
Test::new()
.justfile("foo := read_to_string('bar')")
.write("bar", "baz")
.args(["--evaluate", "foo"])
.stdout("baz")
.run();
}

#[test]
fn read_to_string_not_found() {
Test::new()
.justfile("foo := read_to_string('bar')")
.args(["--evaluate", "foo"])
.stderr_regex(r"error: Call to function `read_to_string` failed: I/O error reading `bar`: .*")
.status(EXIT_FAILURE)
.run();
}

0 comments on commit 464fdbc

Please sign in to comment.