Skip to content

Commit

Permalink
prevent panic when writing a block
Browse files Browse the repository at this point in the history
  • Loading branch information
miller-time committed Jun 21, 2024
1 parent 9d94012 commit 8ca916f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/bin/hq.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{
error::Error,
io::{self, Read, Write},
fs,
io::{self, Read, Write},
};

use clap::{Parser, Subcommand};
Expand Down Expand Up @@ -75,7 +75,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let expr: Expression = value.parse()?;
if let Some(filter) = args.filter {
let fields = parse_filter(&filter)?;
write(fields, &mut body, &expr);
write(fields, &mut body, &expr)?;
print!("{body}");
io::stdout().flush()?;
} else {
Expand Down
22 changes: 21 additions & 1 deletion src/write.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::error::Error;

use hcl_edit::{expr::Expression, structure::Body, visit_mut::VisitMut};

use crate::parser::Field;
Expand All @@ -6,6 +8,7 @@ struct HclEditor<'a> {
fields: Vec<Field>,
next: Option<Field>,
value: &'a Expression,
error: Option<Box<dyn Error>>,
}

impl<'a> HclEditor<'a> {
Expand All @@ -14,6 +17,7 @@ impl<'a> HclEditor<'a> {
fields,
next: None,
value,
error: None,
}
}

Expand Down Expand Up @@ -43,6 +47,10 @@ impl<'a> VisitMut for HclEditor<'a> {
if let Some(next) = next {
if node.ident.as_str() == next.name {
if next.labels.is_empty() {
if self.fields.is_empty() {
self.error = Some("unable to write expr as block body".into());
return;
}
// the block is a match if its name matches and there are no labels
// traverse to the next field
self.next = Some(self.fields.remove(0));
Expand All @@ -52,6 +60,10 @@ impl<'a> VisitMut for HclEditor<'a> {
for filter_label in &next.labels {
for block_label in &node.labels {
if block_label.as_str() == filter_label {
if self.fields.is_empty() {
self.error = Some("unable to write expr as block body".into());
return;
}
// the block name and this label match the filters
// traverse to the next field
self.next = Some(self.fields.remove(0));
Expand All @@ -66,7 +78,15 @@ impl<'a> VisitMut for HclEditor<'a> {
}
}

pub fn write(fields: Vec<Field>, body: &mut Body, value: &Expression) {
pub fn write(
fields: Vec<Field>,
body: &mut Body,
value: &Expression,
) -> Result<(), Box<dyn Error>> {
let mut visitor = HclEditor::new(fields, value);
visitor.visit_body_mut(body);
if let Some(err) = visitor.error {
return Err(err);
}
Ok(())
}

0 comments on commit 8ca916f

Please sign in to comment.