| 1 |
// Copyright (c) HashiCorp, Inc. |
| 2 |
// SPDX-License-Identifier: MPL-2.0 |
| 3 |
|
| 4 |
package tfconfig |
| 5 |
|
| 6 |
import ( |
| 7 |
"fmt" |
| 8 |
"strconv" |
| 9 |
"strings" |
| 10 |
) |
| 11 |
|
| 12 |
// Resource represents a single "resource" or "data" block within a module. |
| 13 |
type Resource struct { |
| 14 |
Mode ResourceMode `json:"mode"` |
| 15 |
Type string `json:"type"` |
| 16 |
Name string `json:"name"` |
| 17 |
|
| 18 |
Provider ProviderRef `json:"provider"` |
| 19 |
|
| 20 |
Pos SourcePos `json:"pos"` |
| 21 |
} |
| 22 |
|
| 23 |
// MapKey returns a string that can be used to uniquely identify the receiver |
| 24 |
// in a map[string]*Resource. |
| 25 |
func (r *Resource) MapKey() string { |
| 26 |
switch r.Mode { |
| 27 |
case ManagedResourceMode: |
| 28 |
return fmt.Sprintf("%s.%s", r.Type, r.Name) |
| 29 |
case DataResourceMode: |
| 30 |
return fmt.Sprintf("data.%s.%s", r.Type, r.Name) |
| 31 |
default: |
| 32 |
// should never happen |
| 33 |
return fmt.Sprintf("[invalid_mode!].%s.%s", r.Type, r.Name) |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
// ResourceMode represents the "mode" of a resource, which is used to |
| 38 |
// distinguish between managed resources ("resource" blocks in config) and |
| 39 |
// data resources ("data" blocks in config). |
| 40 |
type ResourceMode rune |
| 41 |
|
| 42 |
const InvalidResourceMode ResourceMode = 0 |
| 43 |
const ManagedResourceMode ResourceMode = 'M' |
| 44 |
const DataResourceMode ResourceMode = 'D' |
| 45 |
|
| 46 |
func (m ResourceMode) String() string { |
| 47 |
switch m { |
| 48 |
case ManagedResourceMode: |
| 49 |
return "managed" |
| 50 |
case DataResourceMode: |
| 51 |
return "data" |
| 52 |
default: |
| 53 |
return "" |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
// MarshalJSON implements encoding/json.Marshaler. |
| 58 |
func (m ResourceMode) MarshalJSON() ([]byte, error) { |
| 59 |
return []byte(strconv.Quote(m.String())), nil |
| 60 |
} |
| 61 |
|
| 62 |
func resourceTypeDefaultProviderName(typeName string) string { |
| 63 |
if underPos := strings.IndexByte(typeName, '_'); underPos != -1 { |
| 64 |
return typeName[:underPos] |
| 65 |
} |
| 66 |
return typeName |
| 67 |
} |