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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#![deny(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unstable_features,
unsafe_code,
unused_import_braces,
unused_qualifications
)]
use std::{
env,
error::Error,
ffi::{OsStr, OsString},
fs,
io::BufReader,
ops::Drop,
path::{Path, PathBuf},
process::Command,
sync::atomic::{AtomicUsize, Ordering},
time::{SystemTime, UNIX_EPOCH},
};
trait ScrawlState {}
const SCRAWL_TEMP_DIR: &str = "xvrqt_scrawl";
const DEFAULT_EXT: &str = ".txt";
static TEMP_FILE_COUNT: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug)]
pub struct Editor<S: EditorState> {
extension: String,
state: S,
}
pub fn new() -> Editor<DefaultState> {
Editor {
extension: String::from(DEFAULT_EXT),
state: DefaultState {},
}
}
pub trait EditorState {}
impl<S: EditorState> Editor<S> {
fn create_buffer_file(&mut self, contents: Contents) -> Result<PathBuf, Box<dyn Error>> {
let mut temp_dir = env::temp_dir();
temp_dir.push(SCRAWL_TEMP_DIR);
if fs::metadata(&temp_dir).is_err() {
fs::create_dir(&temp_dir)?
};
let i = TEMP_FILE_COUNT.fetch_add(1, Ordering::SeqCst);
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or_else(|_| 0, |v| v.as_secs());
let ext = &self.extension;
let process_id = std::process::id();
let temp_file = format!("{ts}_{process_id}_{i}{ext}");
temp_dir.push(&temp_file);
let temp_file_path = temp_dir;
fs::File::create(&temp_file_path)?;
match contents {
Contents::FromFile(source) => fs::copy(source, &temp_file_path).map(|_| ())?,
Contents::FromString(s) => fs::write(&temp_file_path, s)?,
_ => (),
}
Ok(temp_file_path)
}
fn get_editor_programs(&self) -> Vec<OsString> {
let mut programs = Vec::with_capacity(3);
if let Ok(p) = env::var("VISUAL") {
programs.push(OsString::from(p))
};
if let Ok(p) = env::var("EDITOR") {
programs.push(OsString::from(p))
};
if cfg!(windows) {
programs.push("notepad.exe".into());
} else {
let p: Vec<OsString> = vec![
"vim".into(),
"neovim".into(),
"nvim".into(),
"nano".into(),
"emacs".into(),
"mcedit".into(),
"tilde".into(),
"micro".into(),
"helix".into(),
"ne".into(),
"vi".into(),
];
programs.extend_from_slice(&p);
}
programs
}
}
#[derive(Debug, Clone, Copy)]
pub struct DefaultState {}
impl EditorState for DefaultState {}
impl Editor<DefaultState> {
pub fn ext<S: AsRef<str>>(&mut self, ext: S) -> &mut Self {
self.extension = ext.as_ref().into();
self
}
pub fn editor<S: AsRef<OsStr>>(self, editor: S) -> Editor<SpecificEditorState> {
Editor {
extension: self.extension,
state: SpecificEditorState {
editor: OsString::from(editor.as_ref()),
args: None,
},
}
}
pub fn open(&mut self, contents: Contents) -> Result<Reader, Box<dyn Error>> {
let path = self.create_buffer_file(contents)?;
self.get_editor_programs()
.iter()
.find(|e| Command::new(e).arg(&path).status().is_ok())
.ok_or("Could not find a text editing program")?;
Ok(Reader { path })
}
pub fn edit<P: AsRef<Path>>(&mut self, path: P) -> Result<Reader, Box<dyn Error>> {
self.get_editor_programs()
.iter()
.find(|e| Command::new(e).arg(path.as_ref()).status().is_ok())
.ok_or("Could not find a text editing program")?;
Ok(Reader {
path: path.as_ref().into(),
})
}
}
#[derive(Debug)]
pub struct SpecificEditorState {
args: Option<Vec<OsString>>,
editor: OsString,
}
impl EditorState for SpecificEditorState {}
impl Editor<SpecificEditorState> {
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
self.state
.args
.get_or_insert(vec![])
.push(OsString::from(arg.as_ref()));
self
}
pub fn ext<S: AsRef<str>>(&mut self, ext: S) -> &mut Self {
self.extension = ext.as_ref().into();
self
}
pub fn open(&mut self, contents: Contents) -> Result<Reader, Box<dyn Error>> {
let path = self.create_buffer_file(contents)?;
Command::new(&self.state.editor)
.arg(&path)
.args(self.state.args.as_ref().unwrap_or(&vec![]))
.status()?;
Ok(Reader { path })
}
pub fn edit<P: AsRef<Path>>(&mut self, path: P) -> Result<Reader, Box<dyn Error>> {
Command::new(&self.state.editor)
.arg(path.as_ref())
.args(self.state.args.as_ref().unwrap_or(&vec![]))
.status()?;
Ok(Reader {
path: path.as_ref().into(),
})
}
}
#[allow(missing_debug_implementations)]
pub enum Contents<'a> {
Empty,
FromString(&'a dyn AsRef<[u8]>),
FromFile(&'a dyn AsRef<Path>),
}
#[derive(Debug)]
pub struct Reader {
path: PathBuf,
}
impl Reader {
pub fn read(&self) -> Result<Vec<u8>, Box<dyn Error>> {
Ok(fs::read(&self.path)?)
}
pub fn to_string(&self) -> Result<String, Box<dyn Error>> {
Ok(fs::read_to_string(&self.path)?)
}
pub fn to_bufreader(&self) -> Result<BufReader<fs::File>, Box<dyn Error>> {
Ok(BufReader::new(fs::File::open(&self.path)?))
}
pub fn to_file<P: AsRef<Path>>(&self, path: &P) -> Result<u64, Box<dyn Error>> {
Ok(fs::copy(&self.path, path.as_ref())?)
}
}
impl Drop for Reader {
fn drop(&mut self) {
let mut temp_dir_path = env::temp_dir();
temp_dir_path.push(SCRAWL_TEMP_DIR);
if self.path.starts_with(temp_dir_path) {
let _ = fs::remove_file(&self.path);
}
}
}