Skip to content

Commit 19f07e0

Browse files
committed
improve writing
1 parent 6f3c8a5 commit 19f07e0

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed

tmc-langs-framework/src/io/submission_processing.rs

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use lazy_static::lazy_static;
88
use log::{debug, info};
99
use regex::Regex;
1010
use std::fs::{self, File};
11-
use std::io::Write;
11+
use std::io::{BufWriter, Write};
1212
use std::path::{Path, PathBuf};
1313
use walkdir::{DirEntry, WalkDir};
1414

@@ -27,6 +27,7 @@ pub fn move_files(
2727
target: &Path,
2828
) -> Result<()> {
2929
let tmc_project_yml = student_file_policy.get_tmc_project_yml()?;
30+
// silently skips over errors
3031
for entry in WalkDir::new(source)
3132
.into_iter()
3233
.filter_map(|e| e.ok())
@@ -111,7 +112,9 @@ fn copy_file<F: Fn(&MetaString) -> bool>(
111112
.strip_prefix(source_root)
112113
.unwrap_or_else(|_| Path::new(""));
113114
let dest_path = dest_root.join(&relative_path);
114-
dest_path.parent().map_or(Ok(()), fs::create_dir_all)?;
115+
if let Some(parent) = dest_path.parent() {
116+
fs::create_dir_all(parent).map_err(|e| Error::CreateDir(parent.to_path_buf(), e))?;
117+
}
115118
let extension = entry.path().extension().and_then(|e| e.to_str());
116119
let is_binary = extension
117120
.map(|e| NON_TEXT_TYPES.is_match(e))
@@ -135,19 +138,28 @@ fn copy_file<F: Fn(&MetaString) -> bool>(
135138
let source_file =
136139
File::open(entry.path()).map_err(|e| Error::OpenFile(entry.path().to_path_buf(), e))?;
137140

138-
let mut target_file = File::create(dest_path)
141+
let mut target_file = File::create(&dest_path)
139142
.map_err(|e| Error::CreateFile(entry.path().to_path_buf(), e))?;
140143

141144
let parser = MetaSyntaxParser::new(source_file, extension.unwrap_or_default());
142-
for line in parser {
143-
let line = line?;
144-
if filter(&line) {
145-
debug!("write: {:?}", line);
146-
target_file.write_all(line.as_str().as_bytes())?;
147-
} else {
148-
debug!("skip: {:?}", line);
149-
}
150-
}
145+
146+
// todo: reduce collection?
147+
// filtered metastrings
148+
let filtered: Vec<MetaString> = parser
149+
.collect::<Result<Vec<_>>>()?
150+
.into_iter()
151+
.filter(filter)
152+
.collect();
153+
// collects the filtered lines into a byte vector
154+
let write_lines: Vec<u8> = filtered
155+
.iter()
156+
.flat_map(|l| l.as_str().as_bytes())
157+
.copied()
158+
.collect();
159+
// writes all lines
160+
target_file
161+
.write_all(&write_lines)
162+
.map_err(|e| Error::Write(dest_path, e))?;
151163
}
152164
Ok(())
153165
}

0 commit comments

Comments
 (0)