github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/tfdiags/override.go (about)

     1  package tfdiags
     2  
     3  // overriddenDiagnostic implements the Diagnostic interface by wrapping another
     4  // Diagnostic while overriding the severity of the original Diagnostic.
     5  type overriddenDiagnostic struct {
     6  	original Diagnostic
     7  	severity Severity
     8  	extra    interface{}
     9  }
    10  
    11  var _ Diagnostic = overriddenDiagnostic{}
    12  
    13  // OverrideAll accepts a set of Diagnostics and wraps them with a new severity
    14  // and, optionally, a new ExtraInfo.
    15  func OverrideAll(originals Diagnostics, severity Severity, createExtra func() DiagnosticExtraWrapper) Diagnostics {
    16  	var diags Diagnostics
    17  	for _, diag := range originals {
    18  		diags = diags.Append(Override(diag, severity, createExtra))
    19  	}
    20  	return diags
    21  }
    22  
    23  // Override matches OverrideAll except it operates over a single Diagnostic
    24  // rather than multiple Diagnostics.
    25  func Override(original Diagnostic, severity Severity, createExtra func() DiagnosticExtraWrapper) Diagnostic {
    26  	extra := original.ExtraInfo()
    27  	if createExtra != nil {
    28  		nw := createExtra()
    29  		nw.WrapDiagnosticExtra(extra)
    30  		extra = nw
    31  	}
    32  
    33  	return overriddenDiagnostic{
    34  		original: original,
    35  		severity: severity,
    36  		extra:    extra,
    37  	}
    38  }
    39  
    40  // UndoOverride will return the original diagnostic that was overridden within
    41  // the OverrideAll function.
    42  //
    43  // If the provided Diagnostic was never overridden then it is simply returned
    44  // unchanged.
    45  func UndoOverride(diag Diagnostic) Diagnostic {
    46  	if override, ok := diag.(overriddenDiagnostic); ok {
    47  		return override.original
    48  	}
    49  
    50  	// Then it wasn't overridden, so we'll just return the diag unchanged.
    51  	return diag
    52  }
    53  
    54  func (o overriddenDiagnostic) Severity() Severity {
    55  	return o.severity
    56  }
    57  
    58  func (o overriddenDiagnostic) Description() Description {
    59  	return o.original.Description()
    60  }
    61  
    62  func (o overriddenDiagnostic) Source() Source {
    63  	return o.original.Source()
    64  }
    65  
    66  func (o overriddenDiagnostic) FromExpr() *FromExpr {
    67  	return o.original.FromExpr()
    68  }
    69  
    70  func (o overriddenDiagnostic) ExtraInfo() interface{} {
    71  	return o.extra
    72  }