-
Notifications
You must be signed in to change notification settings - Fork 7
/
generation.go
75 lines (63 loc) · 2 KB
/
generation.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
package dingo
import (
"fmt"
"os"
"github.com/sarulabs/dingo/v4/templates"
)
// GenerateContainer generates a depedency injection container.
// The definitions are loaded from the Provider.
// The code is generated in the outputDirectory.
func GenerateContainer(provider Provider, outputDirectory string) error {
return GenerateContainerWithCustomPkgName(provider, outputDirectory, "dic")
}
// GenerateContainerWithCustomPkgName works like GenerateContainer
// but let you customize the package name in which files are generated.
// The package name must be a valid package name or the generation may fail unexpectedly.
func GenerateContainerWithCustomPkgName(provider Provider, outputDirectory, pkgName string) error {
scan, err := scanDefs(provider)
if err != nil {
return err
}
return writeScan(scan, outputDirectory, pkgName)
}
func scanDefs(provider Provider) (*Scan, error) {
scanner := &Scanner{Provider: provider}
scan, err := scanner.Scan()
if err != nil {
return nil, fmt.Errorf("could not scan definitions: %v", err)
}
return scan, nil
}
func writeScan(scan *Scan, outputDirectory, pkgName string) error {
err := os.RemoveAll(outputDirectory + "/" + pkgName)
if err != nil {
return fmt.Errorf("could not remove destination directory: %v", err)
}
err = templates.WriteTemplate(
outputDirectory+"/"+pkgName+"/defs.go",
templates.DefsTemplate,
map[string]interface{}{
"PkgName": pkgName,
"Imports": scan.TypeManager.Imports(),
"Defs": scan.Defs,
},
)
if err != nil {
return fmt.Errorf("could not generate definition file: %v", err)
}
err = templates.WriteTemplate(
outputDirectory+"/"+pkgName+"/container.go",
templates.ContainerTemplate,
map[string]interface{}{
"PkgName": pkgName,
"Imports": scan.ImportsWithoutParams,
"Defs": scan.Defs,
"ProviderPackage": scan.ProviderPackage,
"ProviderName": scan.ProviderName,
},
)
if err != nil {
return fmt.Errorf("could not generate container file: %v", err)
}
return nil
}