-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherrs.go
69 lines (59 loc) · 1.9 KB
/
errs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* SPDX-FileCopyrightText: Copyright (c) 2025 Orange
* SPDX-License-Identifier: Mozilla Public License 2.0
*
* This software is distributed under the MPL-2.0 license.
* the text of which is available at https://www.mozilla.org/en-US/MPL/2.0/
* or see the "LICENSE" file for more details.
*/
package supertypes
import (
"errors"
"fmt"
"github.com/hashicorp/terraform-plugin-framework/diag"
)
// Must is a generic implementation of the Go Must idiom [1, 2]. It panics if
// the provided error is non-nil and returns x otherwise.
//
// [1]: https://pkg.go.dev/text/template#Must
// [2]: https://pkg.go.dev/regexp#MustCompile
func Must[T any](x T, err error) T {
if err != nil {
panic(err)
}
return x
}
// MustDiag is a generic implementation of the Go Must idiom [1, 2]. It panics if
// the provided Diagnostics has errors and returns x otherwise.
//
// [1]: https://pkg.go.dev/text/template#Must
// [2]: https://pkg.go.dev/regexp#MustCompile
func MustDiag[T any](x T, diags diag.Diagnostics) T {
return Must(x, DiagnosticsError(diags))
}
// MustDiags is a generic implementation of the Go Must idiom [1, 2]. It panics if
// the provided Diagnostics has errors
//
// [1]: https://pkg.go.dev/text/template#Must
// [2]: https://pkg.go.dev/regexp#MustCompile
func MustDiags(diags diag.Diagnostics) {
if DiagnosticsError(diags) != nil {
panic(DiagnosticsError(diags))
}
}
// DiagnosticsError returns an error containing all Diagnostic with SeverityError.
func DiagnosticsError(diags diag.Diagnostics) error {
var errs []error
for _, d := range diags.Errors() {
errs = append(errs, errors.New(DiagnosticString(d)))
}
return errors.Join(errs...)
}
// DiagnosticString formats a Diagnostic
// If there is no `Detail`, only prints summary, otherwise prints both.
func DiagnosticString(d diag.Diagnostic) string {
if d.Detail() == "" {
return d.Summary()
}
return fmt.Sprintf("%s\n\n%s", d.Summary(), d.Detail())
}