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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
|
//! Markdown rendering primitives.
//!
//! This module renders project headers and normalized file paths into Markdown.
//! Rendering behavior is controlled by [`RenderOptions`].
use std::{
fs::File,
io::{Read, Write},
path::Path,
};
use crate::{
logger::Logger,
normalizer::NormalizedPath,
util::{
fence::generate_outer_backticks, language::detect_language, path_display::display_path,
},
};
/// Default maximum file size, in bytes. Larger files are not included in Markdown output.
pub const DEFAULT_MAX_FILE_SIZE: u64 = 1_000_000;
/// Renders files and project metadata as Markdown.
#[derive(Debug)]
pub struct Renderer<W: Write> {
output: W,
max_file_size: u64,
logger: Logger,
placeholder_for_binary_files: bool,
placeholder_for_large_files: bool,
}
impl<W: Write> Renderer<W> {
/// Creates a renderer with default [`RenderOptions`].
pub fn new_with_defaults(output: W) -> Self {
Self::new(output, RenderOptions::default())
}
/// Creates a renderer with explicit rendering options.
pub fn new(output: W, config: RenderOptions) -> Self {
Self {
output,
max_file_size: config.max_file_size,
logger: Logger::default(),
placeholder_for_binary_files: config.placeholder_for_binary_files,
placeholder_for_large_files: config.placeholder_for_large_files,
}
}
/// Sets the maximum file size, in bytes, that will be rendered.
pub fn with_max_file_size(mut self, max_file_size: u64) -> Self {
self.max_file_size = max_file_size;
self
}
/// Sets the logger used for warnings and informational messages.
pub fn with_logger(mut self, logger: Logger) -> Self {
self.logger = logger;
self
}
/// Controls whether skipped binary files are represented by placeholders.
pub fn with_binary_file_placeholder(mut self, placeholder_for_binary_files: bool) -> Self {
self.placeholder_for_binary_files = placeholder_for_binary_files;
self
}
/// Controls whether skipped large files are represented by placeholders.
pub fn with_large_file_placeholder(mut self, placeholder_for_large_files: bool) -> Self {
self.placeholder_for_large_files = placeholder_for_large_files;
self
}
/// Renders the top-level project heading.
pub fn render_header(&mut self, project_title: &str) -> std::io::Result<()> {
writeln!(self.output, "# {}", project_title)
}
/// Renders a normalized path.
///
/// Text files are rendered as fenced Markdown code blocks. Large files and binary files are
/// skipped unless their corresponding placeholder options are enabled.
pub fn render_path(&mut self, normalized_path: &NormalizedPath) -> std::io::Result<()> {
let metadata = std::fs::metadata(&normalized_path.absolute)?;
if metadata.len() > self.max_file_size {
self.warn_about_filesize(&normalized_path.root_relative, metadata.len());
self.render_large_file(&normalized_path.root_relative)
} else {
let file = File::open(&normalized_path.absolute)?;
self.render_file(&normalized_path.root_relative, file)
}
}
fn render_file<R: Read>(&mut self, filename: &Path, mut reader: R) -> std::io::Result<()> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes)?;
let contents = if let Ok(utf8string) = std::str::from_utf8(&bytes) {
utf8string
} else {
self.warn_about_binary_file(filename);
return self.render_binary_file(filename);
};
self.write_file(filename, contents)
}
fn write_file(&mut self, filename: &Path, contents: &str) -> std::io::Result<()> {
let name = display_path(filename);
let fence = generate_outer_backticks(contents);
let language = detect_language(filename, contents);
self.log_file_render(filename);
writeln!(self.output)?;
writeln!(self.output, "## File: {}", name)?;
writeln!(self.output, "{}{}", fence, language)?;
writeln!(self.output, "{}", contents)?;
writeln!(self.output, "{}", fence)
}
fn render_large_file(&mut self, filename: &Path) -> std::io::Result<()> {
if !self.placeholder_for_large_files {
return Ok(());
}
let name = display_path(filename);
writeln!(self.output)?;
writeln!(self.output, "## File: {}", name)?;
writeln!(self.output, "[FILE TOO LARGE]")
}
fn render_binary_file(&mut self, filename: &Path) -> std::io::Result<()> {
if !self.placeholder_for_binary_files {
return Ok(());
}
let name = display_path(filename);
writeln!(self.output)?;
writeln!(self.output, "## File: {}", name)?;
writeln!(self.output, "[BINARY FILE]")
}
fn warn_about_filesize(&self, filename: &Path, filesize: u64) {
self.logger.warn(format!(
"skipping large file: {} ({} > limit {})",
display_path(filename),
human_readable_size(filesize),
human_readable_size(self.max_file_size),
))
}
fn warn_about_binary_file(&self, filename: &Path) {
self.logger
.warn(format!("skipping binary file: {}", display_path(filename)))
}
fn log_file_render(&self, filename: &Path) {
self.logger
.info(format!("rendering file: {}", display_path(filename)));
}
}
/// Options controlling how files are rendered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RenderOptions {
/// Maximum file size, in bytes, to include in Markdown output.
pub max_file_size: u64,
/// Whether skipped binary files should be shown as `[BINARY FILE]`.
pub placeholder_for_binary_files: bool,
/// Whether skipped large files should be shown as `[FILE TOO LARGE]`.
pub placeholder_for_large_files: bool,
}
impl Default for RenderOptions {
fn default() -> Self {
RenderOptions {
max_file_size: DEFAULT_MAX_FILE_SIZE,
placeholder_for_binary_files: false,
placeholder_for_large_files: false,
}
}
}
fn human_readable_size(bytes: u64) -> String {
const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
let mut size = bytes as f64;
let mut unit = 0;
while size >= 1024.0 && unit < UNITS.len() - 1 {
size /= 1024.0;
unit += 1;
}
if unit == 0 {
format!("{} {}", bytes, UNITS[unit])
} else {
format!("{:.1} {}", size, UNITS[unit])
}
}
#[cfg(test)]
mod tests {
use std::{
ffi::OsStr,
io::Cursor,
os::unix::ffi::OsStrExt,
path::{Path, PathBuf},
};
use tempfile::tempdir;
use crate::normalizer::NormalizedPath;
use super::{Renderer, human_readable_size};
#[test]
fn renderer_writes_header() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
renderer.render_header("Project name").unwrap();
assert_eq!(String::from_utf8(output).unwrap(), "# Project name\n");
}
#[test]
fn renderer_renders_single_rust_file_with_language_fence() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new("fn main() {}");
renderer.render_file(Path::new("main.rs"), input).unwrap();
let expected = "\n## File: main.rs\n```rust\nfn main() {}\n```\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn binary_files_are_not_included_in_output_at_all_by_default() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new(&[0x00, 0x01, 0x02, 0xc3]);
renderer.render_file(Path::new("image.png"), input).unwrap();
let expected = "";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn renderer_can_place_a_placeholder_for_binary_files() {
let mut output = Vec::new();
let mut renderer =
Renderer::new_with_defaults(&mut output).with_binary_file_placeholder(true);
let input = Cursor::new(&[0x00, 0x01, 0x02, 0xc3]);
renderer.render_file(Path::new("image.png"), input).unwrap();
let expected = "\n## File: image.png\n[BINARY FILE]\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn filename_with_linebreaks_and_invalid_chars_handled_properly() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new("fn main() {}");
let filename = Path::new(OsStr::from_bytes(b"jap\xE3\x81\x82dir/some\nma\xc3in.rs"));
renderer.render_file(filename, input).unwrap();
let expected = "\n## File: japあdir/some\\nma\\xC3in.rs\n```rust\nfn main() {}\n```\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn file_with_backticks_is_handled_safely() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new("fn main() { println!(\"``` inside\"); }");
renderer
.render_file(Path::new("example.rs"), input)
.unwrap();
let expected = "\n## File: example.rs\n````rust\n\
fn main() { println!(\"``` inside\"); }\n````\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn unknown_filetype_has_no_language_fence() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new("hello world");
renderer.render_file(Path::new("readme"), input).unwrap();
let expected = "\n## File: readme\n```\nhello world\n```\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn txt_file_has_no_language_fence() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new("hello world");
renderer.render_file(Path::new("hello.txt"), input).unwrap();
let expected = "\n## File: hello.txt\n```\nhello world\n```\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn python_file_has_python_language_fence() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new("print('hello')");
renderer.render_file(Path::new("main.py"), input).unwrap();
let expected = "\n## File: main.py\n```python\nprint('hello')\n```\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn json_file_has_json_language_fence() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new("{\"key\":\"value\"}");
renderer.render_file(Path::new("main.json"), input).unwrap();
let expected = "\n## File: main.json\n```json\n{\"key\":\"value\"}\n```\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn uppercase_extension_is_still_detected() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new("fn main() {}");
renderer.render_file(Path::new("MAIN.RS"), input).unwrap();
let expected = "\n## File: MAIN.RS\n```rust\nfn main() {}\n```\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn bash_file_detected_from_shebang() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new("#! /bin/bash\necho hello");
renderer.render_file(Path::new("hello"), input).unwrap();
let expected = "\n## File: hello\n```bash\n#! /bin/bash\necho hello\n```\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn python_file_detected_from_shebang() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output);
let input = Cursor::new("#! /bin/python3\nprint('hello')");
renderer.render_file(Path::new("hello"), input).unwrap();
let expected = "\n## File: hello\n```python\n#! /bin/python3\nprint('hello')\n```\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn large_files_are_not_included_in_output_at_all_by_default() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output).with_max_file_size(5); // smaller than file
let temp_dir = tempdir().unwrap();
let file_path = temp_dir.path().join("big.txt");
let content = "A".repeat(10); // 10 bytes -> bigger than the limit
std::fs::write(&file_path, &content).unwrap();
let normalized_path = NormalizedPath {
root_relative: PathBuf::from("big.txt"),
absolute: file_path,
};
renderer.render_path(&normalized_path).unwrap();
let expected = "";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn renderer_can_place_a_placeholder_for_large_files() {
let mut output = Vec::new();
let mut renderer = Renderer::new_with_defaults(&mut output)
.with_large_file_placeholder(true)
.with_max_file_size(5); // smaller than file
let temp_dir = tempdir().unwrap();
let file_path = temp_dir.path().join("big.txt");
let content = "A".repeat(10); // 10 bytes -> bigger than the limit
std::fs::write(&file_path, &content).unwrap();
let normalized_path = NormalizedPath {
root_relative: PathBuf::from("big.txt"),
absolute: file_path,
};
renderer.render_path(&normalized_path).unwrap();
let expected = "\n## File: big.txt\n[FILE TOO LARGE]\n";
assert_eq!(String::from_utf8(output).unwrap(), expected);
}
#[test]
fn format_readable_filesizes() {
assert_eq!(human_readable_size(10), "10 B");
assert_eq!(human_readable_size(1500), "1.5 KiB");
assert_eq!(human_readable_size(1_048_576), "1.0 MiB");
assert_eq!(human_readable_size(5_242_880), "5.0 MiB");
}
}
|