github.com/hashicorp/terraform-plugin-sdk@v1.17.2/internal/tfdiags/hcl.go (about)

     1  package tfdiags
     2  
     3  import (
     4  	"github.com/hashicorp/hcl/v2"
     5  )
     6  
     7  // hclDiagnostic is a Diagnostic implementation that wraps a HCL Diagnostic
     8  type hclDiagnostic struct {
     9  	diag *hcl.Diagnostic
    10  }
    11  
    12  var _ Diagnostic = hclDiagnostic{}
    13  
    14  func (d hclDiagnostic) Severity() Severity {
    15  	switch d.diag.Severity {
    16  	case hcl.DiagWarning:
    17  		return Warning
    18  	default:
    19  		return Error
    20  	}
    21  }
    22  
    23  func (d hclDiagnostic) Description() Description {
    24  	return Description{
    25  		Summary: d.diag.Summary,
    26  		Detail:  d.diag.Detail,
    27  	}
    28  }
    29  
    30  func (d hclDiagnostic) Source() Source {
    31  	var ret Source
    32  	if d.diag.Subject != nil {
    33  		rng := SourceRangeFromHCL(*d.diag.Subject)
    34  		ret.Subject = &rng
    35  	}
    36  	if d.diag.Context != nil {
    37  		rng := SourceRangeFromHCL(*d.diag.Context)
    38  		ret.Context = &rng
    39  	}
    40  	return ret
    41  }
    42  
    43  func (d hclDiagnostic) FromExpr() *FromExpr {
    44  	if d.diag.Expression == nil || d.diag.EvalContext == nil {
    45  		return nil
    46  	}
    47  	return &FromExpr{
    48  		Expression:  d.diag.Expression,
    49  		EvalContext: d.diag.EvalContext,
    50  	}
    51  }
    52  
    53  // SourceRangeFromHCL constructs a SourceRange from the corresponding range
    54  // type within the HCL package.
    55  func SourceRangeFromHCL(hclRange hcl.Range) SourceRange {
    56  	return SourceRange{
    57  		Filename: hclRange.Filename,
    58  		Start: SourcePos{
    59  			Line:   hclRange.Start.Line,
    60  			Column: hclRange.Start.Column,
    61  			Byte:   hclRange.Start.Byte,
    62  		},
    63  		End: SourcePos{
    64  			Line:   hclRange.End.Line,
    65  			Column: hclRange.End.Column,
    66  			Byte:   hclRange.End.Byte,
    67  		},
    68  	}
    69  }
    70  
    71  // ToHCL constructs a HCL Range from the receiving SourceRange. This is the
    72  // opposite of SourceRangeFromHCL.
    73  func (r SourceRange) ToHCL() hcl.Range {
    74  	return hcl.Range{
    75  		Filename: r.Filename,
    76  		Start: hcl.Pos{
    77  			Line:   r.Start.Line,
    78  			Column: r.Start.Column,
    79  			Byte:   r.Start.Byte,
    80  		},
    81  		End: hcl.Pos{
    82  			Line:   r.End.Line,
    83  			Column: r.End.Column,
    84  			Byte:   r.End.Byte,
    85  		},
    86  	}
    87  }