hcl_edit::structure

Struct Body

Source
pub struct Body { /* private fields */ }
Expand description

Represents an HCL config file body.

A Body consists of zero or more Attribute and Block HCL structures.

Implementations§

Source§

impl Body

Source

pub fn new() -> Self

Constructs a new, empty Body.

Source

pub fn with_capacity(capacity: usize) -> Self

Constructs a new, empty Body with at least the specified capacity.

Source

pub fn builder() -> BodyBuilder

Creates a new BodyBuilder to start building a new Body.

Source

pub fn is_empty(&self) -> bool

Returns true if the body contains no structures.

Source

pub fn len(&self) -> usize

Returns the number of structures in the body, also referred to as its ‘length’.

Source

pub fn clear(&mut self)

Clears the body, removing all structures.

Source

pub fn get(&self, index: usize) -> Option<&Structure>

Returns a reference to the structure at the given index, or None if the index is out of bounds.

Source

pub fn get_mut(&mut self, index: usize) -> Option<&mut Structure>

Returns a mutable reference to the structure at the given index, or None if the index is out of bounds.

Source

pub fn has_attribute(&self, key: &str) -> bool

Returns true if the body contains an attribute with given key.

§Example
use hcl_edit::structure::{Attribute, Body};
use hcl_edit::Ident;

let body = Body::from_iter([Attribute::new(Ident::new("foo"), "bar")]);
assert!(body.has_attribute("foo"));
assert!(!body.has_attribute("bar"));
Source

pub fn has_blocks(&self, ident: &str) -> bool

Returns true if the body contains blocks with given identifier.

§Example
use hcl_edit::structure::{Block, Body};
use hcl_edit::Ident;

let body = Body::from_iter([Block::new(Ident::new("foo"))]);
assert!(body.has_blocks("foo"));
assert!(!body.has_blocks("bar"));
Source

pub fn get_attribute(&self, key: &str) -> Option<&Attribute>

Returns a reference to the Attribute with given key if it exists, otherwise None.

§Example
use hcl_edit::structure::{Attribute, Body};
use hcl_edit::Ident;

let mut body = Body::new();

assert!(body.get_attribute("foo").is_none());

let foo = Attribute::new(Ident::new("foo"), "bar");

body.push(foo.clone());

assert_eq!(body.get_attribute("foo"), Some(&foo));
Source

pub fn get_attribute_mut(&mut self, key: &str) -> Option<AttributeMut<'_>>

Returns a mutable reference to the Attribute with given key if it exists, otherwise None.

§Example
use hcl_edit::expr::Expression;
use hcl_edit::structure::{Attribute, Body};
use hcl_edit::Ident;

let mut body = Body::new();

assert!(body.get_attribute("foo").is_none());

let foo = Attribute::new(Ident::new("foo"), "bar");

body.push(foo.clone());

if let Some(mut attr) = body.get_attribute_mut("foo") {
    *attr.value_mut() = Expression::from("baz");
}

assert_eq!(body.get_attribute("foo"), Some(&Attribute::new(Ident::new("foo"), "baz")));
Source

pub fn get_blocks<'a>(&'a self, ident: &'a str) -> Blocks<'a>

Returns an iterator visiting all Blocks with the given identifier. The iterator element type is &'a Block.

§Example
use hcl_edit::structure::Body;

let input = r#"
resource "aws_s3_bucket" "bucket" {}

variable "name" {}

resource "aws_instance" "instance" {}
"#;

let body: Body = input.parse()?;

let resources: Body = body.get_blocks("resource").cloned().collect();

let expected = r#"
resource "aws_s3_bucket" "bucket" {}

resource "aws_instance" "instance" {}
"#;

assert_eq!(resources.to_string(), expected);
Source

pub fn get_blocks_mut<'a>(&'a mut self, ident: &'a str) -> BlocksMut<'a>

Returns an iterator visiting all Blocks with the given identifier. The iterator element type is &'a mut Block.

§Example
use hcl_edit::expr::{Traversal, TraversalOperator};
use hcl_edit::structure::{Attribute, Body};
use hcl_edit::Ident;

let input = r#"
resource "aws_s3_bucket" "bucket" {}

variable "name" {}

resource "aws_db_instance" "db_instance" {}
"#;

let mut body: Body = input.parse()?;

for block in body.get_blocks_mut("resource") {
    let operators = vec![TraversalOperator::GetAttr(Ident::new("name").into()).into()];
    let value = Traversal::new(Ident::new("var"), operators);
    block.body.push(Attribute::new(Ident::new("name"), value));
}

let expected = r#"
resource "aws_s3_bucket" "bucket" { name = var.name }

variable "name" {}

resource "aws_db_instance" "db_instance" { name = var.name }
"#;

assert_eq!(body.to_string(), expected);
Source

pub fn insert(&mut self, index: usize, structure: impl Into<Structure>)

Inserts a structure at position index within the body, shifting all structures after it to the right.

If it is attempted to insert an Attribute which already exists in the body, it is ignored and not inserted. For a fallible variant of this function see Body::try_insert.

§Panics

Panics if index > len.

Source

pub fn try_insert( &mut self, index: usize, structure: impl Into<Structure>, ) -> Result<(), Attribute>

Inserts a structure at position index within the body, shifting all structures after it to the right.

§Errors

If it is attempted to insert an Attribute which already exists in the body, it is not inserted and returned as the Result’s Err variant instead.

§Panics

Panics if index > len.

§Example
use hcl_edit::structure::{Attribute, Body};
use hcl_edit::Ident;

let mut body = Body::new();

body.push(Attribute::new(Ident::new("foo"), "bar"));
assert!(body.try_insert(0, Attribute::new(Ident::new("bar"), "baz")).is_ok());
assert_eq!(body.len(), 2);

let duplicate_attr = Attribute::new(Ident::new("foo"), "baz");

assert_eq!(body.try_insert(0, duplicate_attr.clone()), Err(duplicate_attr));
Source

pub fn push(&mut self, structure: impl Into<Structure>)

Appends a structure to the back of the body.

If it is attempted to append an Attribute which already exists in the body, it is ignored and not appended. For a fallible variant of this function see Body::try_push.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

Source

pub fn try_push( &mut self, structure: impl Into<Structure>, ) -> Result<(), Attribute>

Appends a structure to the back of the body.

§Errors

If it is attempted to append an Attribute which already exists in the body, it is not appended and returned as the Result’s Err variant instead.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Example
use hcl_edit::structure::{Attribute, Body};
use hcl_edit::Ident;

let mut body = Body::new();

assert!(body.try_push(Attribute::new(Ident::new("foo"), "bar")).is_ok());
assert!(body.try_push(Attribute::new(Ident::new("bar"), "baz")).is_ok());
assert_eq!(body.len(), 2);

let duplicate_attr = Attribute::new(Ident::new("foo"), "baz");

assert_eq!(body.try_push(duplicate_attr.clone()), Err(duplicate_attr));
Source

pub fn pop(&mut self) -> Option<Structure>

Removes the last structure from the body and returns it, or None if it is empty.

Source

pub fn remove(&mut self, index: usize) -> Structure

Removes and returns the structure at position index within the body, shifting all elements after it to the left.

Like Vec::remove, the structure is removed by shifting all of the structures that follow it, preserving their relative order. This perturbs the index of all of those elements!

§Panics

Panics if index is out of bounds.

Source

pub fn remove_attribute(&mut self, key: &str) -> Option<Attribute>

Removes and returns the attribute with given key.

§Example
use hcl_edit::structure::{Attribute, Block, Body};
use hcl_edit::Ident;

let mut body = Body::new();
body.push(Block::new(Ident::new("block")));

assert!(body.remove_attribute("foo").is_none());

let foo = Attribute::new(Ident::new("foo"), "bar");

body.push(foo.clone());

assert_eq!(body.len(), 2);
assert_eq!(body.remove_attribute("foo"), Some(foo));
assert_eq!(body.len(), 1);
Source

pub fn remove_blocks(&mut self, ident: &str) -> Vec<Block>

Removes and returns all blocks with given ident.

§Example
use hcl_edit::structure::{Attribute, Block, Body};
use hcl_edit::Ident;

let mut body = Body::builder()
    .attribute(Attribute::new(Ident::new("foo"), "bar"))
    .block(
        Block::builder(Ident::new("resource"))
            .labels(["aws_s3_bucket", "bucket"])
    )
    .block(Block::builder(Ident::new("variable")).label("name"))
    .block(
        Block::builder(Ident::new("resource"))
            .labels(["aws_db_instance", "db_instance"])
    )
    .build();

let resources = body.remove_blocks("resource");

assert_eq!(
    resources,
    vec![
        Block::builder(Ident::new("resource"))
            .labels(["aws_s3_bucket", "bucket"])
            .build(),
        Block::builder(Ident::new("resource"))
            .labels(["aws_db_instance", "db_instance"])
            .build()
    ]
);

assert_eq!(
    body,
    Body::builder()
        .attribute(Attribute::new(Ident::new("foo"), "bar"))
        .block(Block::builder(Ident::new("variable")).label("name"))
        .build()
);
Source

pub fn iter(&self) -> Iter<'_>

An iterator visiting all body structures in insertion order. The iterator element type is &'a Structure.

Source

pub fn iter_mut(&mut self) -> IterMut<'_>

An iterator visiting all body structures in insertion order, with mutable references to the values. The iterator element type is StructureMut<'a>.

Source

pub fn into_attributes(self) -> IntoAttributes

An owning iterator visiting all Attributes within the body in insertion order. The iterator element type is Attribute.

Source

pub fn attributes(&self) -> Attributes<'_>

An iterator visiting all Attributes within the body in insertion order. The iterator element type is &'a Attribute.

Source

pub fn attributes_mut(&mut self) -> AttributesMut<'_>

An iterator visiting all Attributes within the body in insertion order, with mutable references to the values. The iterator element type is AttributeMut<'a>.

Source

pub fn into_blocks(self) -> IntoBlocks

An owning iterator visiting all Blocks within the body in insertion order. The iterator element type is Block.

Source

pub fn blocks(&self) -> Blocks<'_>

An iterator visiting all Blocks within the body in insertion order. The iterator element type is &'a Block.

Source

pub fn blocks_mut(&mut self) -> BlocksMut<'_>

An iterator visiting all Blocks within the body in insertion order, with mutable references to the values. The iterator element type is &'a mut Block.

Source

pub fn set_prefer_oneline(&mut self, yes: bool)

Configures whether the body should be displayed on a single line.

This is only a hint which will be applied if the Body is part of a Block (that is: not the document root) and only if either of these conditions meet:

  • The body is empty. In this case, the opening ({) and closing (}) braces will be places on the same line.
  • The body only consist of a single Attribute, which will be placed on the same line as the opening and closing braces.

In all other cases this hint is ignored.

Source

pub fn prefer_oneline(&self) -> bool

Returns true if the body should be displayed on a single line.

See the documentation of Body::set_prefer_oneline for more.

Source

pub fn set_prefer_omit_trailing_newline(&mut self, yes: bool)

Configures whether the trailing newline after the last structure in the body should be omitted.

This is only a hint which will be applied if this is the top-level Body of a HCL document and is ignored if the Body is part of a Block.

The default is to always emit a trailing newline after the last body structure.

Source

pub fn prefer_omit_trailing_newline(&self) -> bool

Returns true if the trailing newline after the last structure in the body should be omitted.

See the documentation of Body::set_prefer_omit_trailing_newline for more.

Trait Implementations§

Source§

impl Clone for Body

Source§

fn clone(&self) -> Body

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Body

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Decorate for Body

Source§

fn decor(&self) -> &Decor

Returns a reference to the object’s Decor.
Source§

fn decor_mut(&mut self) -> &mut Decor

Returns a mutable reference to the object’s Decor.
Source§

fn decorate(&mut self, decor: impl Into<Decor>)

Decorate the object with decor in-place.
Source§

fn decorated(self, decor: impl Into<Decor>) -> Self
where Self: Sized,

Decorate the object with decor and return the modified value.
Source§

impl Default for Body

Source§

fn default() -> Body

Returns the “default value” for a type. Read more
Source§

impl Display for Body

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Extend<T> for Body
where T: Into<Structure>,

Source§

fn extend<I>(&mut self, iterable: I)
where I: IntoIterator<Item = T>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl From<BodyBuilder> for Body

Source§

fn from(builder: BodyBuilder) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<Structure>> for Body

Source§

fn from(structures: Vec<Structure>) -> Self

Converts to this type from the input type.
Source§

impl<T> FromIterator<T> for Body
where T: Into<Structure>,

Source§

fn from_iter<I>(iterable: I) -> Self
where I: IntoIterator<Item = T>,

Creates a value from an iterator. Read more
Source§

impl FromStr for Body

Source§

type Err = Error

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl<'a> IntoIterator for &'a Body

Source§

type Item = &'a Structure

The type of the elements being iterated over.
Source§

type IntoIter = Box<dyn Iterator<Item = &'a Structure> + 'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for &'a mut Body

Source§

type Item = StructureMut<'a>

The type of the elements being iterated over.
Source§

type IntoIter = Box<dyn Iterator<Item = StructureMut<'a>> + 'a>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl IntoIterator for Body

Source§

type Item = Structure

The type of the elements being iterated over.
Source§

type IntoIter = Box<dyn Iterator<Item = Structure>>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for Body

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Span for Body

Source§

fn span(&self) -> Option<Range<usize>>

Obtains the span information. This only returns Some if the value was emitted by the parser. Read more
Source§

impl Eq for Body

Auto Trait Implementations§

§

impl Freeze for Body

§

impl RefUnwindSafe for Body

§

impl Send for Body

§

impl Sync for Body

§

impl Unpin for Body

§

impl UnwindSafe for Body

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.