-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfile.rs
More file actions
138 lines (118 loc) · 3.97 KB
/
Copy pathfile.rs
File metadata and controls
138 lines (118 loc) · 3.97 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use std::any::Any;
use std::fmt;
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use once_cell::sync::{Lazy, OnceCell};
use crate::vm::{RuntimeBoolResult, RuntimeErr};
use super::gen;
use super::new;
use super::base::{ObjectRef, ObjectTrait, TypeRef, TypeTrait};
use super::class::TYPE_TYPE;
use super::ns::Namespace;
// File Type ------------------------------------------------------------
gen::type_and_impls!(FileType, File);
pub static FILE_TYPE: Lazy<gen::obj_ref_t!(FileType)> = Lazy::new(|| {
let type_ref = gen::obj_ref!(FileType::new());
let mut type_obj = type_ref.write().unwrap();
type_obj.add_attrs(&[
// Class Methods
gen::meth!("new", type_ref, &["file_name"], "", |_, args, _| {
let arg = gen::use_arg!(args, 0);
if let Some(file_name) = arg.get_str_val() {
let path = Path::new(file_name);
Ok(if path.is_file() {
new::file(file_name)
} else {
new::file_not_found_err(file_name, new::nil())
})
} else {
let message = format!("File.new(file_name) expected string; got {arg}");
Ok(new::arg_err(message, new::nil()))
}
}),
// Instance Attributes
gen::prop!("text", type_ref, "", |this, _, _| {
let this = this.read().unwrap();
let this = this.down_to_file().unwrap();
Ok(this.text())
}),
gen::prop!("lines", type_ref, "", |this, _, _| {
let this = this.read().unwrap();
let this = &mut this.down_to_file().unwrap();
Ok(this.lines())
}),
]);
type_ref.clone()
});
// File Object ----------------------------------------------------------
pub struct File {
ns: Namespace,
file_name: String,
path: PathBuf,
text: OnceCell<ObjectRef>,
lines: OnceCell<ObjectRef>,
}
gen::standard_object_impls!(File);
impl File {
pub fn new(file_name: String) -> Self {
let path = fs::canonicalize(&file_name);
let path = path.map_or_else(|_| Path::new(&file_name).to_path_buf(), |p| p);
let name_obj = new::str(file_name.as_str());
Self {
ns: Namespace::with_entries(&[("name", name_obj)]),
file_name,
path,
text: OnceCell::default(),
lines: OnceCell::default(),
}
}
fn text(&self) -> ObjectRef {
let result = self.text.get_or_try_init(|| {
fs::read_to_string(&self.file_name)
.map(new::str)
.map_err(|err| new::file_unreadable_err(err.to_string(), new::nil()))
});
match result {
Ok(text) => text.clone(),
Err(err) => err,
}
}
fn lines(&self) -> ObjectRef {
let result = self.lines.get_or_try_init(|| {
let file = fs::File::open(&self.file_name);
file.map(|file| {
let reader = BufReader::new(file);
let lines = reader
.lines()
// TODO: Handle lines that can't be read
.map(|line| new::str(line.unwrap()))
.collect();
new::tuple(lines)
})
.map_err(|err| new::file_unreadable_err(err.to_string(), new::nil()))
});
match result {
Ok(lines) => lines.clone(),
Err(err) => err,
}
}
}
impl ObjectTrait for File {
gen::object_trait_header!(FILE_TYPE);
fn bool_val(&self) -> RuntimeBoolResult {
Ok(false)
}
}
// Display -------------------------------------------------------------
impl fmt::Display for File {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "<file: {}>", &self.path.display())
}
}
impl fmt::Debug for File {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}