1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use crate::{Environment, eval::apply::eval_apply, value::Value};
pub(crate) fn builtin(args: &[Value], env: &Environment) -> Option<(Value, Environment)> {
if let [path] = &args[..] {
match eval_apply(path, env) {
Some((Value::String(file_path), _)) => {
match std::fs::File::options()
.read(true)
.open(&file_path)
.and_then(|f| {
let mut buffer = String::new();
std::io::Read::read_to_string(
&mut std::io::BufReader::new(f),
&mut buffer,
)
.map(|_| buffer)
}) {
Ok(file_content) => Some((Value::String(file_content), Environment::new())),
Err(_) => {
eprintln!(
concat!(
"Error[ksl::builtin::read]: ",
"Unable to read contents of file at `{}`."
),
file_path
);
None
}
}
}
Some((e, _)) => {
eprintln!(
concat!(
"Error[ksl::builtin::read]: ",
"Expected a string, but got `{:?}`."
),
e
);
None
}
None => {
eprintln!(
concat!(
"Error[ksl::builtin::read]: ",
"Cannot evaluate expression {:?}."
),
path
);
None
}
}
} else {
eprintln!(
concat!(
"Error[ksl::builtin::read]: ",
"Only accepts 1 argument, but {} were passed."
),
args.len()
);
None
}
}