-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathimporter_csharp.go
More file actions
279 lines (237 loc) · 7.61 KB
/
importer_csharp.go
File metadata and controls
279 lines (237 loc) · 7.61 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package project
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"github.com/azure/azure-dev/cli/azd/pkg/azdext"
)
var _ azdext.ImporterProvider = &CSharpImporterProvider{}
const defaultInfraDir = "infra"
// CSharpImporterProvider generates Bicep infrastructure from C# Azure.Provisioning code.
// It detects .cs files in the infra directory, runs them with `dotnet run`, and captures
// the generated Bicep output.
type CSharpImporterProvider struct {
azdClient *azdext.AzdClient
}
func NewCSharpImporterProvider(azdClient *azdext.AzdClient) azdext.ImporterProvider {
return &CSharpImporterProvider{azdClient: azdClient}
}
// CanImport checks if this importer can handle the given service.
// This importer is infra-only (configured via infra.importer in azure.yaml),
// so it always returns false for service auto-detection.
func (p *CSharpImporterProvider) CanImport(
ctx context.Context,
svcConfig *azdext.ServiceConfig,
) (bool, error) {
return false, nil
}
// Services returns the original service as-is. This importer handles infrastructure
// generation, not service extraction.
func (p *CSharpImporterProvider) Services(
ctx context.Context,
projectConfig *azdext.ProjectConfig,
svcConfig *azdext.ServiceConfig,
) (map[string]*azdext.ServiceConfig, error) {
return map[string]*azdext.ServiceConfig{
svcConfig.Name: svcConfig,
}, nil
}
// ProjectInfrastructure compiles C# Azure.Provisioning code to Bicep for `azd provision`.
func (p *CSharpImporterProvider) ProjectInfrastructure(
ctx context.Context,
projectPath string,
options map[string]string,
progress azdext.ProgressReporter,
) (*azdext.ImporterProjectInfrastructureResponse, error) {
infraPath := resolvePath(projectPath, options)
progress("Detecting C# infrastructure entry point...")
entryPoint, err := resolveEntryPoint(infraPath)
if err != nil {
return nil, fmt.Errorf("resolving C# entry point: %w", err)
}
// Create temp directory for Bicep output
tempDir, err := os.MkdirTemp("", "azd-csharp-bicep-*")
if err != nil {
return nil, fmt.Errorf("creating temp directory: %w", err)
}
defer os.RemoveAll(tempDir)
progress(fmt.Sprintf("Compiling C# infrastructure from %s...", filepath.Base(entryPoint)))
// Forward importer options (excluding "path") as --key value args to the C# program
extraArgs := optionsToArgs(options)
// Run the C# program
if err := runDotnet(ctx, entryPoint, tempDir, extraArgs); err != nil {
return nil, err
}
// Read generated files
files, err := readGeneratedFiles(tempDir)
if err != nil {
return nil, fmt.Errorf("reading generated Bicep: %w", err)
}
if len(files) == 0 {
return nil, fmt.Errorf(
"no .bicep files generated by %s. Ensure your program calls Build().Save(outputDir) "+
"with the output directory passed as the first argument", entryPoint)
}
progress(fmt.Sprintf("Generated %d Bicep file(s)", len(files)))
return &azdext.ImporterProjectInfrastructureResponse{
InfraOptions: &azdext.InfraOptions{
Provider: "bicep",
Module: "main",
},
Files: files,
}, nil
}
// GenerateAllInfrastructure generates Bicep files for `azd infra gen` (ejection).
func (p *CSharpImporterProvider) GenerateAllInfrastructure(
ctx context.Context,
projectPath string,
options map[string]string,
) ([]*azdext.GeneratedFile, error) {
infraPath := resolvePath(projectPath, options)
entryPoint, err := resolveEntryPoint(infraPath)
if err != nil {
return nil, fmt.Errorf("resolving C# entry point: %w", err)
}
tempDir, err := os.MkdirTemp("", "azd-csharp-bicep-*")
if err != nil {
return nil, fmt.Errorf("creating temp directory: %w", err)
}
defer os.RemoveAll(tempDir)
if err := runDotnet(ctx, entryPoint, tempDir, optionsToArgs(options)); err != nil {
return nil, err
}
files, err := readGeneratedFiles(tempDir)
if err != nil {
return nil, fmt.Errorf("reading generated Bicep: %w", err)
}
// Prefix paths with infra/ for ejection
for _, f := range files {
f.Path = "infra/" + f.Path
}
return files, nil
}
// resolvePath determines the directory containing C# infrastructure files.
func resolvePath(projectPath string, options map[string]string) string {
dir := defaultInfraDir
if v, ok := options["path"]; ok && v != "" {
dir = v
}
return filepath.Join(projectPath, dir)
}
// hasCSharpInfra checks if a directory contains .cs or .csproj files.
func hasCSharpInfra(path string) bool {
entries, err := os.ReadDir(path)
if err != nil {
return false
}
for _, e := range entries {
if e.IsDir() {
continue
}
ext := strings.ToLower(filepath.Ext(e.Name()))
if ext == ".cs" || ext == ".csproj" {
return true
}
}
return false
}
// resolveEntryPoint finds the C# entry point in the given directory.
// Prefers .csproj over single .cs file.
func resolveEntryPoint(infraPath string) (string, error) {
info, err := os.Stat(infraPath)
if err != nil {
return "", fmt.Errorf("path '%s' does not exist: %w", infraPath, err)
}
if !info.IsDir() {
ext := strings.ToLower(filepath.Ext(infraPath))
if ext == ".cs" || ext == ".csproj" {
return infraPath, nil
}
return "", fmt.Errorf("'%s' is not a .cs or .csproj file", infraPath)
}
// Check for .csproj first
csprojFiles, _ := filepath.Glob(filepath.Join(infraPath, "*.csproj"))
if len(csprojFiles) > 0 {
return infraPath, nil
}
// Fall back to single .cs file
csFiles, _ := filepath.Glob(filepath.Join(infraPath, "*.cs"))
if len(csFiles) == 1 {
return csFiles[0], nil
}
if len(csFiles) > 1 {
return "", fmt.Errorf(
"multiple .cs files in '%s' — use a single .cs file or add a .csproj", infraPath)
}
return "", fmt.Errorf("no .cs or .csproj files found in '%s'", infraPath)
}
// optionsToArgs converts the importer options map to --key value CLI args,
// excluding the "path" key which is used for directory resolution.
func optionsToArgs(options map[string]string) []string {
// Sort keys for deterministic ordering
keys := make([]string, 0, len(options))
for k := range options {
if k == "path" {
continue
}
keys = append(keys, k)
}
sort.Strings(keys)
var args []string
for _, k := range keys {
args = append(args, "--"+k, options[k])
}
return args
}
// runDotnet executes the C# entry point with the output directory as the first argument,
// followed by any extra args from importer options.
func runDotnet(ctx context.Context, entryPoint string, outputDir string, extraArgs []string) error {
var args []string
if strings.HasSuffix(strings.ToLower(entryPoint), ".cs") {
args = []string{"run", entryPoint, "--", outputDir}
} else {
args = []string{"run", "--project", entryPoint, "--", outputDir}
}
args = append(args, extraArgs...)
cmd := exec.CommandContext(ctx, "dotnet", args...)
cmd.Env = append(os.Environ(),
"DOTNET_CLI_WORKLOAD_UPDATE_NOTIFY_DISABLE=1",
"DOTNET_NOLOGO=1",
)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("dotnet run failed: %w\nOutput: %s", err, string(output))
}
return nil
}
// readGeneratedFiles reads all .bicep and .json files from a directory.
func readGeneratedFiles(dir string) ([]*azdext.GeneratedFile, error) {
var files []*azdext.GeneratedFile
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
for _, e := range entries {
if e.IsDir() {
continue
}
ext := strings.ToLower(filepath.Ext(e.Name()))
if ext == ".bicep" || ext == ".json" {
content, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
return nil, fmt.Errorf("reading %s: %w", e.Name(), err)
}
files = append(files, &azdext.GeneratedFile{
Path: e.Name(),
Content: content,
})
}
}
return files, nil
}