update to use file: prefix

This commit is contained in:
Luke Boswell 2023-03-19 14:10:22 +11:00
parent c7f8ba6ded
commit 3832228a13
No known key found for this signature in database
GPG Key ID: F6DB3C9DB47377B0
2 changed files with 25 additions and 8 deletions

View File

@ -60,6 +60,6 @@ Herculei undae calcata inmeriti quercus ignes parabant iam.
``` ```
```roc ```roc
codeExample.roc file:codeExample.roc
``` ```

View File

@ -232,7 +232,7 @@ fn process_file(input_dir: &Path, output_dir: &Path, input_file: &Path) -> Resul
// path to a static file, if so replace the code with // path to a static file, if so replace the code with
// the contents of the file. // the contents of the file.
// ``` // ```
// myCodeFile.roc // file:myCodeFile.roc
// ``` // ```
Some(new_code_to_highlight) => { Some(new_code_to_highlight) => {
code_to_highlight = new_code_to_highlight; code_to_highlight = new_code_to_highlight;
@ -330,13 +330,30 @@ fn is_roc_code_block(cbk: &pulldown_cmark::CodeBlockKind) -> bool {
fn replace_code_with_static_file(code: &str, input_file: &Path) -> Option<String> { fn replace_code_with_static_file(code: &str, input_file: &Path) -> Option<String> {
let input_dir = input_file.parent()?; let input_dir = input_file.parent()?;
let trimmed_code = code.trim(); let trimmed_code = code.trim();
if trimmed_code.len() <= 255 && trimmed_code.contains(".") {
let file_path = input_dir.join(trimmed_code); // Confirm the code block starts with a `file:` tag
match trimmed_code.strip_prefix("file:") {
None => None,
Some(path) => {
let vec_u8 = fs::read(file_path).ok()?; // File must be located in input folder or sub-directory
if path.contains("../") {
panic!("ERROR File must be located within the input diretory!");
}
String::from_utf8(vec_u8).ok() let file_path = input_dir.join(path);
} else {
None // Check file exists before opening
match file_path.try_exists() {
Err(_) | Ok(false) => {
panic!("ERROR File does not exist: \"{}\"", file_path.to_str().unwrap());
}
Ok(true) => {
let vec_u8 = fs::read(file_path).ok()?;
String::from_utf8(vec_u8).ok()
}
}
}
} }
} }