Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
91 changes: 88 additions & 3 deletions tools/cli/internal/openapi/filter/code_sample.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,44 @@
package filter

import (
"bytes"
"fmt"
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main changes were in this file. The files under tests were autogenerated.

goFormat "go/format"
"strings"
"text/template"
"time"

"github.com/getkin/kin-openapi/openapi3"
"github.com/mongodb/openapi/tools/cli/internal/apiversion"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)

const goSDKTemplate = `import (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[follow up] conmsider creating a sdk.go.tmpl file and using embedded here, using a template file will give you some code highlighting

"os"
"context"
sdk "go.mongodb.org/atlas-sdk/v{{ .Version }}/admin"
)

func main() {
ctx := context.Background()
apiKey := os.Getenv("MONGODB_ATLAS_PUBLIC_KEY")
apiSecret := os.Getenv("MONGODB_ATLAS_PRIVATE_KEY")
url := os.Getenv("MONGODB_ATLAS_BASE_URL")

client, err := sdk.NewClient(
sdk.UseDigestAuth(apiKey, apiSecret),
sdk.UseBaseURL(url),
sdk.UseDebug(true))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not for regular users

Copy link
Collaborator Author

@andreaangiolillo andreaangiolillo Jun 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I will update it. I was re-using the example we have in https://github.com/mongodb/atlas-sdk-go/blob/6e94e42d2d395dfab18b67bc0ebf2e5437df3b1e/examples/db_users/db_users.go#L28. Maybe I should update also the example there?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

check https://github.com/mongodb/atlas-sdk-go/blob/8971b03030c6ed9fc5f52c87d7d16be59e1eb498/examples/service_account_management/sa_management.go is a bit closer to a good enough example

Maybe I should update also the example there?

If you want, I'm not sure if that example wanted to show more than it needs to but for simplicity on openapi let's keep it simple here


params = &sdk.{{ .OperationID }}ApiParams{}
{{ if eq .Method "DELETE" }} httpResp, err := sdk.{{ .Tag }}Api.
{{ .OperationID }}WithParams(ctx, params).
Execute(){{ else }} sdkResp, httpResp, err := sdk.{{ .Tag }}Api.
{{ .OperationID }}WithParams(ctx, params).
Execute(){{ end}}
}`

const codeSampleExtensionName = "x-codeSamples"

// https://redocly.com/docs-legacy/api-reference-docs/specification-extensions/x-code-samples#x-codesamples
Expand Down Expand Up @@ -121,6 +153,47 @@ func newAtlasCliCodeSamplesForOperation(op *openapi3.Operation) codeSample {
}
}

func (f *CodeSampleFilter) newGoSdkCodeSamplesForOperation(op *openapi3.Operation, opMethod string) (codeSample, error) {
version := strings.ReplaceAll(apiVersion(f.metadata.targetVersion), "-", "") + "001"
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This field represents the SDK version. The value is formatted as YYYY-MM-DD-001, where 001 indicates the first SDK release for that API version. The last three digits are incremented for subsequent releases, but 001 will always be available as the initial version for each API version.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A bit curious on how this version stays in sync with the latest SDK version:

  1. Is this reference to the SDK version always being published before SDK?
  2. Or there is a mechanism for reading the latest SDK version?

Copy link
Collaborator Author

@andreaangiolillo andreaangiolillo Jun 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, neither of those options apply. I generate the SDK version by combining the API version in the format YYYY-DD.MM with 001 as the suffix, which represents the first release for any new API version and is always present. Subsequent releases for the same API version will follow the format YYYY-DD.MM-002, YYYY-DD.MM-003, and so on, but the example will always use the initial 001 release.
If I merge this, I will then create a ticket to improve this to check for the release in the sdk repo but I don't think is critical for the initial example since the 001 is always present.

operationID := cases.Title(language.English, cases.NoLower).String(op.OperationID)
tag := strings.ReplaceAll(op.Tags[0], " ", "")
tag = strings.ReplaceAll(tag, ".", "")

t, err := template.New("goSDK").Parse(goSDKTemplate)
if err != nil {
return codeSample{}, err
}

var buffer bytes.Buffer
err = t.Execute(&buffer, struct {
Tag string
OperationID string
Version string
Method string
}{
Tag: tag,
OperationID: operationID,
Version: version,
Method: opMethod,
})

if err != nil {
return codeSample{}, err
}

formattedResult, err := goFormat.Source(buffer.Bytes())
if err != nil {
return codeSample{}, fmt.Errorf("tag: %s, operationId: %s code: %s: error: %w",
op.Tags[0], operationID, buffer.String(), err)
}

return codeSample{
Lang: "go",
Label: "Go",
Source: string(formattedResult),
}, nil
}

func (f *CodeSampleFilter) includeCodeSamplesForOperation(pathName, opMethod string, op *openapi3.Operation) error {
if op == nil || opMethod == "" || pathName == "" {
return nil
Expand All @@ -130,10 +203,22 @@ func (f *CodeSampleFilter) includeCodeSamplesForOperation(pathName, opMethod str
op.Extensions = map[string]any{}
}

op.Extensions[codeSampleExtensionName] = []codeSample{
codeSamples := []codeSample{
newAtlasCliCodeSamplesForOperation(op),
f.newServiceAccountCurlCodeSamplesForOperation(pathName, opMethod),
f.newDigestCurlCodeSamplesForOperation(pathName, opMethod),
}

if f.metadata.targetVersion.IsStable() {
sdkSample, err := f.newGoSdkCodeSamplesForOperation(op, opMethod)
if err != nil {
return err
}
codeSamples = append(codeSamples, sdkSample)
}

codeSamples = append(
codeSamples,
f.newServiceAccountCurlCodeSamplesForOperation(pathName, opMethod),
f.newDigestCurlCodeSamplesForOperation(pathName, opMethod))
op.Extensions[codeSampleExtensionName] = codeSamples
return nil
}
22 changes: 22 additions & 0 deletions tools/cli/internal/openapi/filter/code_sample_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ func TestCodeSampleFilter(t *testing.T) {
},
},
})),
Tags: []string{"TestTag"},
Extensions: map[string]any{
"x-sunset": "9999-12-31",
},
Expand All @@ -73,6 +74,7 @@ func TestCodeSampleFilter(t *testing.T) {
},
},
})),
Tags: []string{"TestTag"},
Extensions: map[string]any{
"x-sunset": "9999-12-31",
"x-codeSamples": []codeSample{
Expand All @@ -81,6 +83,26 @@ func TestCodeSampleFilter(t *testing.T) {
Label: "Atlas CLI",
Source: "atlas api testOperationID --help",
},
{
Lang: "go",
Label: "Go",
Source: "import (\n" +
"\t\"os\"\n \"context\"\n" +
"\tsdk \"go.mongodb.org/atlas-sdk/v20250101001/admin\"\n)\n\n" +
"func main() {\n" +
"\tctx := context.Background()\n" +
"\tapiKey := os.Getenv(\"MONGODB_ATLAS_PUBLIC_KEY\")\n" +
"\tapiSecret := os.Getenv(\"MONGODB_ATLAS_PRIVATE_KEY\")\n" +
"\turl := os.Getenv(\"MONGODB_ATLAS_BASE_URL\")\n\n" +
"\tclient, err := sdk.NewClient(\n" +
"\t\tsdk.UseDigestAuth(apiKey, apiSecret),\n" +
"\t\tsdk.UseBaseURL(url),\n" +
"\t\tsdk.UseDebug(true))\n\n" +
"\tparams = &sdk.TestOperationIDApiParams{}\n" +
"\tsdkResp, httpResp, err := sdk.TestTagApi.\n" +
"\t\tTestOperationIDWithParams(ctx, params).\n" +
"\t\tExecute()" + "\n}",
},
{
Lang: "cURL",
Label: "curl (Service Accounts)",
Expand Down
Loading
Loading