Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(go): fix syntax error in generated source for VisitUndiscriminatedUnion #5190

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion generators/go/internal/generator/file_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,25 @@ func removeUnusedImports(filename string, buf []byte) ([]byte, error) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filename, buf, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("failed to parse Go code: %v", err)
badMetadata := strings.Split(err.Error(), ":")
badLine, _ := strconv.Atoi(badMetadata[1])
badLineCharIdx, _ := strconv.Atoi(badMetadata[2])

badSrcLines := strings.Split(string(bytes.ToValidUTF8(buf, []byte{'?'})), "\n")
badSrc := ""
maxLineDigitCount := len(fmt.Sprint(len(badSrcLines)))
for i, line := range badSrcLines {
if i >= badLine-5 && i <= badLine+3 {
if i == badLine-1 {
badSrc += "\n"
}
badSrc += fmt.Sprintf("%"+fmt.Sprint(maxLineDigitCount)+"d: %s\n", i+1, line)
if i == badLine-1 {
badSrc += strings.Repeat(" ", badLineCharIdx+maxLineDigitCount+1) + "^\n"
}
}
}
return nil, fmt.Errorf("failed to parse Go code: %w; source:\n=-=\n%s", err, badSrc)
}

imports := make(map[string]string)
Expand Down
54 changes: 27 additions & 27 deletions generators/go/internal/generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func New(config *Config, coordinator *coordinator.Client) (*Generator, error) {
func (g *Generator) Generate(mode Mode) ([]*File, error) {
ir, err := readIR(g.config.IRFilepath)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to read IR: %w", err)
}
return g.generate(ir, mode)
}
Expand Down Expand Up @@ -202,7 +202,7 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
referencedImportPath := fernFilepathToImportPath(g.config.ImportPath, referencedType.FernFilepath)
if typeImportPath != referencedImportPath {
return nil, fmt.Errorf(
"%s referneces %s from another package, but a generator import path was not specified",
"%s references %s from another package, but a generator import path was not specified",
typeDeclaration.Name.TypeId,
referencedType.TypeId,
)
Expand All @@ -214,7 +214,7 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
rootPackageName := getRootPackageName(ir, g.config.PackageName)
cycleInfo, err := cycleInfoFromIR(ir, g.config.ImportPath)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to cycle info from IR: %w", err)
}
if cycleInfo != nil {
for _, leafType := range cycleInfo.LeafTypes {
Expand Down Expand Up @@ -341,11 +341,11 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
g.config.ModuleConfig,
g.config.Version,
); err != nil {
return nil, err
return nil, fmt.Errorf("failed to write request options definition: %w", err)
}
file, err := writer.File()
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to open new writer.File: %w", err)
}
files = append(files, file)
if ir.Environments != nil {
Expand All @@ -366,11 +366,11 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
)
generatedEnvironment, err = writer.WriteEnvironments(ir.Environments, useCore)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to write environments: %w", err)
}
file, err = writer.File()
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to open new writer.File: %w", err)
}
files = append(files, file)
}
Expand All @@ -391,11 +391,11 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
)
generatedAuth, err = writer.WriteRequestOptions(ir.Auth, ir.Headers)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to write request options: %w", err)
}
file, err = writer.File()
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to open new writer.File: %w", err)
}
files = append(files, file)
rootClientInstantiation = generatedClientInstantiation(
Expand All @@ -420,11 +420,11 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
g.coordinator,
)
if err := writer.WriteIdempotentRequestOptionsDefinition(ir.IdempotencyHeaders); err != nil {
return nil, err
return nil, fmt.Errorf("failed to write idempotent request options definition: %w", err)
}
file, err = writer.File()
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to open new writer.File: %w", err)
}
files = append(files, file)
fileInfo = fileInfoForIdempotentRequestOptions()
Expand All @@ -442,11 +442,11 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
g.coordinator,
)
if err := writer.WriteIdempotentRequestOptions(ir.IdempotencyHeaders); err != nil {
return nil, err
return nil, fmt.Errorf("failed to write idempotent request options: %w", err)
}
file, err = writer.File()
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to open new writer.File: %w", err)
}
files = append(files, file)
}
Expand All @@ -467,11 +467,11 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
g.coordinator,
)
if err = writer.WriteLegacyClientOptions(ir.Auth, ir.Headers, ir.IdempotencyHeaders); err != nil {
return nil, err
return nil, fmt.Errorf("failed to write legacy client options: %w", err)
}
file, err = writer.File()
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to open new writer.File: %w", err)
}
files = append(files, file)
}
Expand All @@ -492,11 +492,11 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
)
if g.config.EnableExplicitNull {
if err := writer.WriteOptionalHelpers(useCore); err != nil {
return nil, err
return nil, fmt.Errorf("failed to write optional helpers: %w", err)
}
file, err = writer.File()
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to open new writer.File: %w", err)
}
files = append(files, file)
files = append(files, newOptionalFile(g.coordinator))
Expand Down Expand Up @@ -529,7 +529,7 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
}
clientTestFile, err := newClientTestFile(g.config.ImportPath, g.coordinator)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to create new client test file: %w", err)
}
files = append(files, clientTestFile)
// Generate the error types, if any.
Expand All @@ -549,12 +549,12 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
)
for _, irError := range irErrors {
if err := writer.WriteError(irError); err != nil {
return nil, err
return nil, fmt.Errorf("failed to write error type: %w", err)
}
}
file, err := writer.File()
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to open new writer.File: %w", err)
}
files = append(files, file)
}
Expand All @@ -579,7 +579,7 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
ir.RootPackage.FernFilepath,
)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to generate service: %w", err)
}
files = append(files, file)

Expand All @@ -594,7 +594,7 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
rootClientInstantiation,
)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to generate root service without endpoints: %w", err)
}
files = append(files, file)

Expand Down Expand Up @@ -631,7 +631,7 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
subpackageToGenerate.OriginalFernFilepath,
)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to generate service without endpoints: %w", err)
}
files = append(files, file)
continue
Expand All @@ -645,7 +645,7 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
subpackageToGenerate.OriginalFernFilepath,
)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to generate service: %w", err)
}
files = append(files, file)

Expand All @@ -656,7 +656,7 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
// Write the snippets, if any.
if g.config.SnippetFilepath != "" {
if err := maybeWriteSnippets(g.coordinator, generatedRootClient, g.config.SnippetFilepath); err != nil {
return nil, err
return nil, fmt.Errorf("failed to write snippets: %w", err)
}
}
// Finally, generate the go.mod file, if needed.
Expand All @@ -667,13 +667,13 @@ func (g *Generator) generate(ir *fernir.IntermediateRepresentation, mode Mode) (
requiresGenerics := g.config.EnableExplicitNull || ir.SdkConfig.HasStreamingEndpoints || generatedPagination
file, generatedGoVersion, err := NewModFile(g.coordinator, g.config.ModuleConfig, requiresGenerics)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to create new go.mod file: %w", err)
}
files = append(files, file)

if g.config.IncludeReadme && generatedRootClient.Instantiation != nil {
if err := g.generateReadme(generatedRootClient, generatedGoVersion); err != nil {
return nil, err
return nil, fmt.Errorf("failed to generate readme: %w", err)
}
files = append(files, file)
}
Expand Down
8 changes: 4 additions & 4 deletions generators/go/internal/generator/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -884,9 +884,9 @@ func (t *typeVisitor) VisitUndiscriminatedUnion(union *ir.UndiscriminatedUnionTy
for _, member := range members {
field := fmt.Sprintf("%s.%s", receiver, member.field)
if member.date != nil && !member.isOptional {
t.writer.P(fmt.Sprintf("if %s.typ == %q || !%s.IsZero() {", receiver, member.field, field))
t.writer.P(fmt.Sprintf("if (%s.typ == %q || !%s.IsZero()) {", receiver, member.field, field))
} else {
t.writer.P(fmt.Sprintf("if %s.typ == %q || %s != %s {", receiver, member.field, field, member.zeroValue))
t.writer.P(fmt.Sprintf("if (%s.typ == %q || %s != %s) {", receiver, member.field, field, member.zeroValue))
}
if member.isLiteral {
// If we have a literal, we need to marshal it directly.
Expand Down Expand Up @@ -918,9 +918,9 @@ func (t *typeVisitor) VisitUndiscriminatedUnion(union *ir.UndiscriminatedUnionTy
for _, member := range members {
field := fmt.Sprintf("%s.%s", receiver, member.field)
if member.date != nil && !member.isOptional {
t.writer.P(fmt.Sprintf("if %s.typ == %q || !%s.IsZero() {", receiver, member.field, field))
t.writer.P(fmt.Sprintf("if (%s.typ == %q || !%s.IsZero()) {", receiver, member.field, field))
} else {
t.writer.P(fmt.Sprintf("if %s.typ == %q || %s != %s {", receiver, member.field, field, member.zeroValue))
t.writer.P(fmt.Sprintf("if (%s.typ == %q || %s != %s) {", receiver, member.field, field, member.zeroValue))
}
t.writer.P("return visitor.Visit", strings.Title(member.field), "(", receiver, ".", member.field, ")")
t.writer.P("}")
Expand Down
Loading