huskies: merge 516_story_update_story_description_should_create_the_description_section_if_it_doesn_t_exist_instead_of_erroring

This commit is contained in:
dave
2026-04-10 10:25:07 +00:00
parent f015fe5a1d
commit 61ae30873f
2 changed files with 104 additions and 8 deletions
+47
View File
@@ -517,6 +517,53 @@ pub(super) fn replace_section_content(content: &str, section_name: &str, new_tex
Ok(new_str)
}
/// Insert a new `## {section_name}` section into `content`.
///
/// The new section is placed immediately before the first occurrence of
/// `## {before_section}`. If `before_section` is `None` or not found in the
/// document, the section is appended at the end.
pub(super) fn create_section_content(
content: &str,
section_name: &str,
new_text: &str,
before_section: Option<&str>,
) -> String {
let lines: Vec<&str> = content.lines().collect();
let insert_at = before_section
.and_then(|before| {
let heading = format!("## {before}");
lines.iter().position(|l| l.trim() == heading)
})
.unwrap_or(lines.len());
let mut new_lines: Vec<String> = Vec::new();
for line in lines.iter().take(insert_at) {
new_lines.push(line.to_string());
}
// Ensure a blank line before the new heading.
if new_lines.last().map(|l| !l.is_empty()).unwrap_or(false) {
new_lines.push(String::new());
}
new_lines.push(format!("## {section_name}"));
new_lines.push(String::new());
new_lines.push(new_text.to_string());
new_lines.push(String::new());
for line in lines.iter().skip(insert_at) {
new_lines.push(line.to_string());
}
let mut new_str = new_lines.join("\n");
if content.ends_with('\n') {
new_str.push('\n');
}
new_str
}
/// Replace the `## Test Results` section in `contents` with `new_section`,
/// or append it if not present.
pub(super) fn replace_or_append_section(contents: &str, header: &str, new_section: &str) -> String {