github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/pkg/error_helpers/error_and_warnings.go (about)

     1  package error_helpers
     2  
     3  import (
     4  	"github.com/hashicorp/hcl/v2"
     5  	"github.com/turbot/steampipe-plugin-sdk/v5/plugin"
     6  	"github.com/turbot/steampipe-plugin-sdk/v5/sperr"
     7  )
     8  
     9  type ErrorAndWarnings struct {
    10  	Error    error
    11  	Warnings []string
    12  }
    13  
    14  func DiagsToErrorsAndWarnings(errPrefix string, diags hcl.Diagnostics) ErrorAndWarnings {
    15  	return NewErrorsAndWarning(
    16  		plugin.DiagsToError(errPrefix, diags),
    17  		plugin.DiagsToWarnings(diags)...,
    18  	)
    19  }
    20  
    21  func EmptyErrorsAndWarning() ErrorAndWarnings {
    22  	return NewErrorsAndWarning(nil)
    23  }
    24  
    25  func NewErrorsAndWarning(err error, warnings ...string) ErrorAndWarnings {
    26  	return ErrorAndWarnings{
    27  		Error: err, Warnings: warnings,
    28  	}
    29  }
    30  
    31  func (r *ErrorAndWarnings) WrapErrorWithMessage(msg string) ErrorAndWarnings {
    32  	if r.Error != nil {
    33  		r.Error = sperr.WrapWithMessage(r.Error, msg)
    34  	}
    35  	return *r
    36  }
    37  
    38  func (r *ErrorAndWarnings) AddWarning(warnings ...string) {
    39  	// avoid duplicates
    40  	for _, w := range warnings {
    41  		if !r.hasWarning(w) {
    42  			r.Warnings = append(r.Warnings, w)
    43  		}
    44  	}
    45  
    46  }
    47  
    48  func (r *ErrorAndWarnings) ShowWarnings() {
    49  	for _, w := range r.Warnings {
    50  		ShowWarning(w)
    51  	}
    52  }
    53  
    54  func (r *ErrorAndWarnings) GetError() error {
    55  	if r == nil {
    56  		return nil
    57  	}
    58  	return r.Error
    59  }
    60  
    61  func (r *ErrorAndWarnings) Merge(other ErrorAndWarnings) ErrorAndWarnings {
    62  	// TODO: Restructure ErrorsAndWarning
    63  	// [issue](https://github.com/turbot/steampipe/issues/3845)
    64  	if r.Error == nil {
    65  		r.Error = other.Error
    66  	}
    67  	if len(other.Warnings) > 0 {
    68  		r.AddWarning(other.Warnings...)
    69  	}
    70  	return *r
    71  }
    72  
    73  func (r *ErrorAndWarnings) Empty() bool {
    74  	return r.Error == nil && len(r.Warnings) == 0
    75  }
    76  
    77  func (r *ErrorAndWarnings) hasWarning(w string) bool {
    78  	for _, warning := range r.Warnings {
    79  		if warning == w {
    80  			return true
    81  		}
    82  	}
    83  	return false
    84  }