-
Notifications
You must be signed in to change notification settings - Fork 187
/
apply_type_rewrites.go
87 lines (72 loc) · 2.38 KB
/
apply_type_rewrites.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*/
package pipeline
import (
"context"
"github.com/go-logr/logr"
"github.com/pkg/errors"
"github.com/Azure/azure-service-operator/v2/tools/generator/internal/astmodel"
"github.com/Azure/azure-service-operator/v2/tools/generator/internal/config"
)
// ApplyTypeRewrites applies any typeTransformers.
func ApplyTypeRewrites(
config *config.Configuration,
log logr.Logger,
) *Stage {
stage := NewStage(
"typeRewrites",
"Modify types using configured type transforms",
func(ctx context.Context, state *State) (*State, error) {
definitions := make(astmodel.TypeDefinitionSet, len(state.Definitions()))
for name, def := range state.Definitions() {
// Apply type transformation, if any
newDef, err := transformDefinition(def, config, log)
if err != nil {
return nil, errors.Wrapf(err, "unable to transform type %q", name)
}
definitions.Add(newDef)
// If we renamed the type, add an alias from the old name to the new;
// When we remove type aliases later in the pipeline, these will result in any references being updated
if newDef.Name() != def.Name() {
alias := astmodel.MakeTypeDefinition(
def.Name(), newDef.Name())
definitions.Add(alias)
}
}
// Ensure the type transformers had no errors
if err := config.GetTransformersError(); err != nil {
return nil, err
}
return state.WithDefinitions(definitions), nil
})
stage.RequiresPrerequisiteStages("nameTypes", "allof-anyof-objects")
return stage
}
// TransformDefinition applies a type transformation to the definition if appropriate.
// If a transformation is applied, the new definition is returned along with a reason for the transformation.
// If something goes wrong, only an error is returned.
// If no transformation is found, returns nil, ""
func transformDefinition(
def astmodel.TypeDefinition,
config *config.Configuration,
log logr.Logger,
) (astmodel.TypeDefinition, error) {
name := def.Name()
for _, transformer := range config.Transformers {
if transformer.AppliesToDefinition(def) {
result, err := transformer.TransformDefinition(def)
if err != nil {
return astmodel.TypeDefinition{}, err
}
log.V(2).Info(
"Transforming type",
"type", name,
"because", transformer.Because,
"transformation", result.Type())
def = result
}
}
return def, nil
}