diff --git a/README.md b/README.md index a299507ee..bf4fa9854 100644 --- a/README.md +++ b/README.md @@ -583,7 +583,7 @@ By default, Databricks SDK for Go uses [logger.SimpleLogger](https://pkg.go.dev/ Since v0.10.0, default logger prints only `INFO` level messages. To replicate more verbose behavior from the previous versions, set the `DEBUG` level in `SimpleLogger`: ```go -import "github.com/databricks/databricks-sdk-go/logger" +import "github.com/databricks/databricks-sdk-go/databricks/log" func init() { logger.DefaultLogger = &logger.SimpleLogger{ diff --git a/config/auth_azure_cli.go b/config/auth_azure_cli.go index 56959f4cc..ba4f71869 100644 --- a/config/auth_azure_cli.go +++ b/config/auth_azure_cli.go @@ -12,7 +12,7 @@ import ( "golang.org/x/oauth2" "github.com/databricks/databricks-sdk-go/config/credentials" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" ) // The header used to pass the service management token to the Databricks backend. @@ -47,7 +47,7 @@ func (c AzureCliCredentials) getVisitor(ctx context.Context, cfg *Config, inner ts := &azureCliTokenSource{ctx, cfg.Environment().AzureServiceManagementEndpoint(), cfg.AzureResourceID, cfg.AzureTenantID} t, err := ts.Token() if err != nil { - logger.Debugf(ctx, "Not including service management token in headers: %v", err) + log.DebugContext(ctx, "Not including service management token in headers: %v", err) return azureVisitor(cfg, refreshableVisitor(inner)), nil } management := azureReuseTokenSource(t, ts) @@ -72,7 +72,7 @@ func (c AzureCliCredentials) Configure(ctx context.Context, cfg *Config) (creden return nil, nil } if strings.Contains(err.Error(), "executable file not found") { - logger.Debugf(ctx, "Most likely Azure CLI is not installed. "+ + log.DebugContext(ctx, "Most likely Azure CLI is not installed. "+ "See https://docs.microsoft.com/en-us/cli/azure/?view=azure-cli-latest for details") return nil, nil } @@ -86,7 +86,7 @@ func (c AzureCliCredentials) Configure(ctx context.Context, cfg *Config) (creden if err != nil { return nil, err } - logger.Infof(ctx, "Using Azure CLI authentication with AAD tokens") + log.InfoContext(ctx, "Using Azure CLI authentication with AAD tokens") return credentials.NewOAuthCredentialsProvider(visitor, ts.Token), nil } @@ -119,7 +119,7 @@ func (ts *azureCliTokenSource) getSubscription() string { } components := strings.Split(ts.workspaceResourceId, "/") if len(components) < 3 { - logger.Warnf(context.Background(), "Invalid azure workspace resource ID") + log.Warning("Invalid azure workspace resource ID") return "" } return components[2] @@ -143,8 +143,12 @@ func (ts *azureCliTokenSource) Token() (*oauth2.Token, error) { if ts.azureTenantId != "" { tenantIdDebug = fmt.Sprintf(" for tenant %s", ts.azureTenantId) } - logger.Infof(context.Background(), "Refreshed OAuth token for %s%s from Azure CLI, which expires on %s", - ts.resource, tenantIdDebug, it.ExpiresOn) + log.Info( + "Refreshed OAuth token for %s%s from Azure CLI, which expires on %s", + ts.resource, + tenantIdDebug, + it.ExpiresOn, + ) var extra map[string]interface{} err = json.Unmarshal(tokenBytes, &extra) @@ -199,7 +203,7 @@ func (ts *azureCliTokenSource) getTokenBytesWithTenantId(tenantId string) ([]byt if err == nil { return result, nil } - logger.Infof(ts.ctx, "Failed to get token for subscription. Using resource only token.") + log.InfoContext(ts.ctx, "Failed to get token for subscription. Using resource only token.") } result, err := runCommand(ts.ctx, "az", args) if ee, ok := err.(*exec.ExitError); ok { diff --git a/config/auth_azure_client_secret.go b/config/auth_azure_client_secret.go index 85f09bb21..262eb5585 100644 --- a/config/auth_azure_client_secret.go +++ b/config/auth_azure_client_secret.go @@ -9,7 +9,7 @@ import ( "golang.org/x/oauth2/clientcredentials" "github.com/databricks/databricks-sdk-go/config/credentials" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" ) type AzureClientSecretCredentials struct { @@ -50,7 +50,7 @@ func (c AzureClientSecretCredentials) Configure(ctx context.Context, cfg *Config if err != nil { return nil, fmt.Errorf("resolve host: %w", err) } - logger.Infof(ctx, "Generating AAD token for Service Principal (%s)", cfg.AzureClientID) + log.InfoContext(ctx, "Generating AAD token for Service Principal (%s)", cfg.AzureClientID) env := cfg.Environment() aadEndpoint := env.AzureActiveDirectoryEndpoint() managementEndpoint := env.AzureServiceManagementEndpoint() diff --git a/config/auth_azure_github_oidc.go b/config/auth_azure_github_oidc.go index 2f82214f2..0aab4cd83 100644 --- a/config/auth_azure_github_oidc.go +++ b/config/auth_azure_github_oidc.go @@ -7,8 +7,8 @@ import ( "time" "github.com/databricks/databricks-sdk-go/config/credentials" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/httpclient" - "github.com/databricks/databricks-sdk-go/logger" "golang.org/x/oauth2" ) @@ -50,11 +50,11 @@ func (c AzureGithubOIDCCredentials) Configure(ctx context.Context, cfg *Config) // requestIDToken requests an ID token from the Github Action. func requestIDToken(ctx context.Context, cfg *Config) (string, error) { if cfg.ActionsIDTokenRequestURL == "" { - logger.Debugf(ctx, "Missing cfg.ActionsIDTokenRequestURL, likely not calling from a Github action") + log.DebugContext(ctx, "Missing cfg.ActionsIDTokenRequestURL, likely not calling from a Github action") return "", nil } if cfg.ActionsIDTokenRequestToken == "" { - logger.Debugf(ctx, "Missing cfg.ActionsIDTokenRequestToken, likely not calling from a Github action") + log.DebugContext(ctx, "Missing cfg.ActionsIDTokenRequestToken, likely not calling from a Github action") return "", nil } diff --git a/config/auth_azure_msi.go b/config/auth_azure_msi.go index 7a947d7d0..79bb4ff53 100644 --- a/config/auth_azure_msi.go +++ b/config/auth_azure_msi.go @@ -9,8 +9,8 @@ import ( "time" "github.com/databricks/databricks-sdk-go/config/credentials" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/httpclient" - "github.com/databricks/databricks-sdk-go/logger" "golang.org/x/oauth2" ) @@ -42,7 +42,7 @@ func (c AzureMsiCredentials) Configure(ctx context.Context, cfg *Config) (creden return nil, fmt.Errorf("resolve host: %w", err) } } - logger.Debugf(ctx, "Generating AAD token via Azure MSI") + log.DebugContext(ctx, "Generating AAD token via Azure MSI") inner := azureReuseTokenSource(nil, c.tokenSourceFor(ctx, cfg, "", env.AzureApplicationID)) management := azureReuseTokenSource(nil, c.tokenSourceFor(ctx, cfg, "", env.AzureServiceManagementEndpoint())) visitor := azureVisitor(cfg, serviceToServiceVisitor(inner, management, xDatabricksAzureSpManagementToken)) diff --git a/config/auth_azure_msi_test.go b/config/auth_azure_msi_test.go index c62db809c..d83914a15 100644 --- a/config/auth_azure_msi_test.go +++ b/config/auth_azure_msi_test.go @@ -6,15 +6,13 @@ import ( "time" "github.com/databricks/databricks-sdk-go/databricks/apierr" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/httpclient/fixtures" - "github.com/databricks/databricks-sdk-go/logger" "github.com/stretchr/testify/require" ) func init() { - logger.DefaultLogger = &logger.SimpleLogger{ - Level: logger.LevelDebug, - } + log.SetDefaultLogger(log.New(log.LevelDebug)) } func someValidToken(bearer string) any { diff --git a/config/auth_databricks_cli.go b/config/auth_databricks_cli.go index 1ec798307..139b4b97f 100644 --- a/config/auth_databricks_cli.go +++ b/config/auth_databricks_cli.go @@ -11,7 +11,7 @@ import ( "strings" "github.com/databricks/databricks-sdk-go/config/credentials" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "golang.org/x/oauth2" ) @@ -30,11 +30,11 @@ func (c DatabricksCliCredentials) Configure(ctx context.Context, cfg *Config) (c ts, err := newDatabricksCliTokenSource(ctx, cfg) if err != nil { if errors.Is(err, exec.ErrNotFound) { - logger.Debugf(ctx, "Most likely the Databricks CLI is not installed") + log.DebugContext(ctx, "Most likely the Databricks CLI is not installed") return nil, nil } if err == errLegacyDatabricksCli { - logger.Debugf(ctx, "Databricks CLI version <0.100.0 detected") + log.DebugContext(ctx, "Databricks CLI version <0.100.0 detected") return nil, nil } return nil, err @@ -53,7 +53,7 @@ func (c DatabricksCliCredentials) Configure(ctx context.Context, cfg *Config) (c } return nil, err } - logger.Debugf(ctx, "Using Databricks CLI authentication with Databricks OAuth tokens") + log.DebugContext(ctx, "Using Databricks CLI authentication with Databricks OAuth tokens") visitor := refreshableVisitor(ts) return credentials.NewOAuthCredentialsProvider(visitor, ts.Token), nil } @@ -118,6 +118,6 @@ func (ts *databricksCliTokenSource) Token() (*oauth2.Token, error) { if err != nil { return nil, fmt.Errorf("cannot unmarshal Databricks CLI result: %w", err) } - logger.Infof(context.Background(), "Refreshed OAuth token from Databricks CLI, expires on %s", t.Expiry) + log.Info("Refreshed OAuth token from Databricks CLI, expires on %s", t.Expiry) return &t, nil } diff --git a/config/auth_default.go b/config/auth_default.go index 5fc3080f7..54f197505 100644 --- a/config/auth_default.go +++ b/config/auth_default.go @@ -6,7 +6,7 @@ import ( "fmt" "github.com/databricks/databricks-sdk-go/config/credentials" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" ) var authProviders = []CredentialsStrategy{ @@ -48,10 +48,10 @@ func (c *DefaultCredentials) Configure(ctx context.Context, cfg *Config) (creden for _, p := range authProviders { if cfg.AuthType != "" && p.Name() != cfg.AuthType { // ignore other auth types if one is explicitly enforced - logger.Infof(ctx, "Ignoring %s auth, because %s is preferred", p.Name(), cfg.AuthType) + log.InfoContext(ctx, "Ignoring %s auth, because %s is preferred", p.Name(), cfg.AuthType) continue } - logger.Tracef(ctx, "Attempting to configure auth: %s", p.Name()) + log.TraceContext(ctx, "Attempting to configure auth: %s", p.Name()) credentialsProvider, err := p.Configure(ctx, cfg) if err != nil { return nil, fmt.Errorf("%s: %w", p.Name(), err) diff --git a/config/auth_gcp_google_credentials.go b/config/auth_gcp_google_credentials.go index 127a590f4..2c58a81c8 100644 --- a/config/auth_gcp_google_credentials.go +++ b/config/auth_gcp_google_credentials.go @@ -7,7 +7,7 @@ import ( "os" "github.com/databricks/databricks-sdk-go/config/credentials" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "golang.org/x/oauth2/google" "google.golang.org/api/idtoken" "google.golang.org/api/option" @@ -41,7 +41,7 @@ func (c GoogleCredentials) Configure(ctx context.Context, cfg *Config) (credenti if err != nil { return nil, fmt.Errorf("could not obtain OAuth2 token from JSON: %w", err) } - logger.Infof(ctx, "Using Google Credentials") + log.InfoContext(ctx, "Using Google Credentials") visitor := serviceToServiceVisitor(inner, creds.TokenSource, "X-Databricks-GCP-SA-Access-Token") return credentials.NewOAuthCredentialsProvider(visitor, inner.Token), nil } diff --git a/config/auth_gcp_google_id.go b/config/auth_gcp_google_id.go index 3d3a600b1..8a4b0a89d 100644 --- a/config/auth_gcp_google_id.go +++ b/config/auth_gcp_google_id.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/databricks/databricks-sdk-go/config/credentials" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "golang.org/x/oauth2" "google.golang.org/api/impersonate" "google.golang.org/api/option" @@ -29,7 +29,7 @@ func (c GoogleDefaultCredentials) Configure(ctx context.Context, cfg *Config) (c return nil, err } if !cfg.IsAccountClient() { - logger.Infof(ctx, "Using Google Default Application Credentials for Workspace") + log.InfoContext(ctx, "Using Google Default Application Credentials for Workspace") visitor := refreshableVisitor(inner) return credentials.NewCredentialsProvider(visitor), nil } @@ -44,7 +44,7 @@ func (c GoogleDefaultCredentials) Configure(ctx context.Context, cfg *Config) (c if err != nil { return nil, err } - logger.Infof(ctx, "Using Google Default Application Credentials for Accounts API") + log.InfoContext(ctx, "Using Google Default Application Credentials for Accounts API") visitor := serviceToServiceVisitor(inner, platform, "X-Databricks-GCP-SA-Access-Token") return credentials.NewOAuthCredentialsProvider(visitor, inner.Token), nil } diff --git a/config/auth_m2m.go b/config/auth_m2m.go index 70fe07d94..fdd007d8e 100644 --- a/config/auth_m2m.go +++ b/config/auth_m2m.go @@ -9,8 +9,8 @@ import ( "golang.org/x/oauth2/clientcredentials" "github.com/databricks/databricks-sdk-go/config/credentials" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/httpclient" - "github.com/databricks/databricks-sdk-go/logger" ) var errOAuthNotSupported = errors.New("databricks OAuth is not supported for this host") @@ -30,7 +30,7 @@ func (c M2mCredentials) Configure(ctx context.Context, cfg *Config) (credentials if err != nil { return nil, fmt.Errorf("oidc: %w", err) } - logger.Debugf(ctx, "Generating Databricks OAuth token for Service Principal (%s)", cfg.ClientID) + log.DebugContext(ctx, "Generating Databricks OAuth token for Service Principal (%s)", cfg.ClientID) ts := (&clientcredentials.Config{ ClientID: cfg.ClientID, ClientSecret: cfg.ClientSecret, diff --git a/config/auth_metadata_service.go b/config/auth_metadata_service.go index beae500c4..a8d2916cf 100644 --- a/config/auth_metadata_service.go +++ b/config/auth_metadata_service.go @@ -9,8 +9,8 @@ import ( "time" "github.com/databricks/databricks-sdk-go/config/credentials" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/httpclient" - "github.com/databricks/databricks-sdk-go/logger" "golang.org/x/oauth2" ) @@ -107,8 +107,6 @@ func (t metadataService) Token() (*oauth2.Token, error) { if token == nil { return nil, fmt.Errorf("no token returned from metadata service") } - logger.Debugf(context.Background(), - "Refreshed access token from local metadata service, which expires on %s", - token.Expiry.Format(time.RFC3339)) + log.Debug("Refreshed access token from local metadata service, which expires on %s", token.Expiry.Format(time.RFC3339)) return token, nil } diff --git a/config/azure.go b/config/azure.go index 86d6451dd..7b4822d85 100644 --- a/config/azure.go +++ b/config/azure.go @@ -10,8 +10,8 @@ import ( "strings" "github.com/databricks/databricks-sdk-go/databricks/apierr" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/httpclient" - "github.com/databricks/databricks-sdk-go/logger" "golang.org/x/oauth2" ) @@ -137,7 +137,7 @@ func (c *Config) azureEnsureWorkspaceUrl(ctx context.Context, ahr azureHostResol return fmt.Errorf("resolve workspace: %w", err) } c.Host = fmt.Sprintf("https://%s", workspaceMetadata.Properties.WorkspaceURL) - logger.Debugf(ctx, "Discovered workspace url: %s", c.Host) + log.DebugContext(ctx, "Discovered workspace url: %s", c.Host) return nil } diff --git a/config/command.go b/config/command.go index fc9528643..7232ebe34 100644 --- a/config/command.go +++ b/config/command.go @@ -5,11 +5,11 @@ import ( "os/exec" "strings" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" ) // Run a command and return the output. func runCommand(ctx context.Context, cmd string, args []string) ([]byte, error) { - logger.Debugf(ctx, "Running command: %s %v", cmd, strings.Join(args, " ")) + log.DebugContext(ctx, "Running command: %s %v", cmd, strings.Join(args, " ")) return exec.Command(cmd, args...).Output() } diff --git a/config/config.go b/config/config.go index b451d3ecc..ebb464c6f 100644 --- a/config/config.go +++ b/config/config.go @@ -14,8 +14,8 @@ import ( "github.com/databricks/databricks-sdk-go/common" "github.com/databricks/databricks-sdk-go/common/environment" "github.com/databricks/databricks-sdk-go/config/credentials" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/httpclient" - "github.com/databricks/databricks-sdk-go/logger" "golang.org/x/oauth2" ) @@ -291,7 +291,7 @@ func (c *Config) EnsureResolved() error { } ctx := context.Background() for _, loader := range c.Loaders { - logger.Tracef(ctx, "Loading config via %s", loader.Name()) + log.TraceContext(ctx, "Loading config via %s", loader.Name()) err := loader.Configure(c) if err != nil { diff --git a/config/config_file.go b/config/config_file.go index 2c7c33803..bf273e3e8 100644 --- a/config/config_file.go +++ b/config/config_file.go @@ -1,12 +1,11 @@ package config import ( - "context" "fmt" "os" "strings" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "gopkg.in/ini.v1" ) @@ -78,7 +77,7 @@ func (l configFileLoader) Configure(cfg *Config) error { if err != nil { if os.IsNotExist(err) { // early return for non-configured machines - logger.Debugf(context.Background(), "%s not found on current host", configFilePath) + log.Debug("%s not found on current host", configFilePath) return nil } return fmt.Errorf("cannot parse config file: %w", err) @@ -92,12 +91,12 @@ func (l configFileLoader) Configure(cfg *Config) error { profileValues := configFile.Section(profile) if len(profileValues.Keys()) == 0 { if !hasExplicitProfile { - logger.Debugf(context.Background(), "%s has no %s profile configured", configFile.Path(), profile) + log.Debug("%s has no %s profile configured", configFile.Path(), profile) return nil } return fmt.Errorf("%s has no %s profile configured", configFile.Path(), profile) } - logger.Debugf(context.Background(), "Loading %s profile from %s", profile, configFile.Path()) + log.Debug("Loading %s profile from %s", profile, configFile.Path()) err = ConfigAttributes.ResolveFromStringMapWithSource(cfg, profileValues.KeysHash(), Source{Type: SourceFile, Name: configFile.Path()}) if err != nil { return fmt.Errorf("%s %s profile: %w", configFile.Path(), profile, err) diff --git a/databricks/apierr/error_override.go b/databricks/apierr/error_override.go index 82b9a22c5..4ceea5bd7 100644 --- a/databricks/apierr/error_override.go +++ b/databricks/apierr/error_override.go @@ -6,7 +6,7 @@ import ( "regexp" "strconv" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" ) // errorOverride is a struct that allows for customizing error responses from @@ -65,7 +65,7 @@ func (e *errorOverride) matches(err *APIError, resp *http.Response) bool { func applyOverrides(ctx context.Context, err *APIError, resp *http.Response) { for _, override := range allOverrides { if override.matches(err, resp) { - logger.Debugf(ctx, "Applying error override: %s", override.debugName) + log.DebugContext(ctx, "Applying error override: %s", override.debugName) err.unwrap = override.customError return } diff --git a/databricks/apierr/errors.go b/databricks/apierr/errors.go index b764badab..dfbc19ad9 100644 --- a/databricks/apierr/errors.go +++ b/databricks/apierr/errors.go @@ -13,7 +13,7 @@ import ( "github.com/databricks/databricks-sdk-go/common" "github.com/databricks/databricks-sdk-go/databricks/httplog" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" ) const ( @@ -91,7 +91,7 @@ func (apiError *APIError) IsRetriable(ctx context.Context) bool { // Handle transient errors for retries for _, regex := range allTransientErrors { if regex.Match([]byte(apiError.Message)) { - logger.Debugf(ctx, "Attempting retry because of %s", regex.String()) + log.DebugContext(ctx, "Attempting retry because of %s", regex.String()) return true } } @@ -206,7 +206,7 @@ func standardErrorParser(ctx context.Context, resp *http.Response, responseBody ScimType string `json:"scimType,omitempty"` } if err := json.Unmarshal(responseBody, &errorBody); err != nil { - logger.Tracef(ctx, "standardErrorParser: failed to unmarshal error response: %s", err) + log.TraceContext(ctx, "standardErrorParser: failed to unmarshal error response: %s", err) return nil } @@ -244,7 +244,7 @@ var stringErrorRegex = regexp.MustCompile(`^([A-Z_]+): (.*)$`) func stringErrorParser(ctx context.Context, resp *http.Response, responseBody []byte) *APIError { matches := stringErrorRegex.FindSubmatch(responseBody) if len(matches) < 3 { - logger.Tracef(ctx, "stringErrorParser: failed to match error response") + log.TraceContext(ctx, "stringErrorParser: failed to match error response") return nil } return &APIError{ @@ -263,7 +263,7 @@ func htmlErrorParser(ctx context.Context, resp *http.Response, responseBody []by messageMatches := htmlMessageRe.FindStringSubmatch(string(responseBody)) // No messages with
format found so return a APIError if len(messageMatches) < 2 { - logger.Tracef(ctx, "htmlErrorParser: no
tag found in error response") + log.TraceContext(ctx, "htmlErrorParser: notag found in error response") return nil } diff --git a/databricks/log/log.go b/databricks/log/log.go index 769f9f6b7..20ba02642 100644 --- a/databricks/log/log.go +++ b/databricks/log/log.go @@ -59,10 +59,6 @@ func (l Level) String() string { // Logger is the interface that wraps the Log method. type Logger interface { Log(ctx context.Context, level Level, format string, a ...any) - - // TODO(renaud.hartert): Think about a potential alternative to exposing - // this method. - MinLevel() Level } type logger struct { @@ -85,10 +81,6 @@ func (l *logger) Log(_ context.Context, level Level, format string, a ...any) { } } -func (l *logger) MinLevel() Level { - return l.level -} - var defaultLogger Logger = New(LevelInfo) // DefaultLogger returns the default logger. diff --git a/examples/http-proxy/client/main.go b/examples/http-proxy/client/main.go index d110e439f..a007733f1 100644 --- a/examples/http-proxy/client/main.go +++ b/examples/http-proxy/client/main.go @@ -3,18 +3,18 @@ package main import ( "context" "crypto/tls" - "log" + golog "log" "net/http" "os" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/compute" ) func main() { if os.Getenv("HTTPS_PROXY") != "https://localhost:8443" { - log.Printf(`To run this example, first start the proxy server in the examples/http-proxy/proxy directory: + golog.Printf(`To run this example, first start the proxy server in the examples/http-proxy/proxy directory: $ go run ../proxy @@ -32,10 +32,9 @@ on Windows to see the list of clusters in your Databricks workspace using this p `) os.Exit(1) } - log.Printf("Constructing client...") - logger.DefaultLogger = &logger.SimpleLogger{ - Level: logger.LevelDebug, - } + golog.Printf("Constructing client...") + log.SetDefaultLogger(log.New(log.LevelDebug)) + var tlsNextProto map[string]func(authority string, c *tls.Conn) http.RoundTripper if os.Getenv("HTTPS_PROXY") != "" { // Go's HTTP client only supports HTTP/1.1 proxies when using TLS. See @@ -50,7 +49,7 @@ on Windows to see the list of clusters in your Databricks workspace using this p TLSNextProto: tlsNextProto, }, })) - log.Printf("Listing clusters...") + golog.Printf("Listing clusters...") all, err := w.Clusters.ListAll(context.Background(), compute.ListClustersRequest{}) if err != nil { panic(err) diff --git a/examples/slog/go.mod b/examples/slog/go.mod index b110735e3..13aeece2b 100644 --- a/examples/slog/go.mod +++ b/examples/slog/go.mod @@ -2,7 +2,7 @@ module main go 1.18 -replace github.com/databricks/databricks-sdk-go v0.0.0 => ../.. +replace github.com/databricks/databricks-sdk-go => ../.. require ( github.com/databricks/databricks-sdk-go v0.0.0 @@ -10,13 +10,14 @@ require ( ) require ( - cloud.google.com/go/compute v1.23.4 // indirect - cloud.google.com/go/compute/metadata v0.2.3 // indirect + cloud.google.com/go/auth v0.4.2 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.2 // indirect + cloud.google.com/go/compute/metadata v0.3.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/go-logr/logr v1.4.1 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/protobuf v1.5.3 // indirect + github.com/golang/protobuf v1.5.4 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/s2a-go v0.1.7 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect @@ -25,17 +26,16 @@ require ( go.opentelemetry.io/otel v1.24.0 // indirect go.opentelemetry.io/otel/metric v1.24.0 // indirect go.opentelemetry.io/otel/trace v1.24.0 // indirect - golang.org/x/crypto v0.21.0 // indirect - golang.org/x/mod v0.16.0 // indirect - golang.org/x/net v0.23.0 // indirect - golang.org/x/oauth2 v0.18.0 // indirect - golang.org/x/sys v0.18.0 // indirect - golang.org/x/text v0.14.0 // indirect + golang.org/x/crypto v0.31.0 // indirect + golang.org/x/mod v0.17.0 // indirect + golang.org/x/net v0.33.0 // indirect + golang.org/x/oauth2 v0.20.0 // indirect + golang.org/x/sys v0.28.0 // indirect + golang.org/x/text v0.21.0 // indirect golang.org/x/time v0.5.0 // indirect - google.golang.org/api v0.169.0 // indirect - google.golang.org/appengine v1.6.8 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20240304161311-37d4d3c04a78 // indirect - google.golang.org/grpc v1.62.0 // indirect - google.golang.org/protobuf v1.33.0 // indirect + google.golang.org/api v0.182.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240521202816-d264139d666e // indirect + google.golang.org/grpc v1.64.1 // indirect + google.golang.org/protobuf v1.34.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect ) diff --git a/examples/slog/go.sum b/examples/slog/go.sum index 32f5c50a0..6c8dede76 100644 --- a/examples/slog/go.sum +++ b/examples/slog/go.sum @@ -1,8 +1,10 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go/compute v1.23.4 h1:EBT9Nw4q3zyE7G45Wvv3MzolIrCJEuHys5muLY0wvAw= -cloud.google.com/go/compute v1.23.4/go.mod h1:/EJMj55asU6kAFnuZET8zqgwgJ9FvXWXOkkfQZa4ioI= -cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= -cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= +cloud.google.com/go/auth v0.4.2 h1:sb0eyLkhRtpq5jA+a8KWw0W70YcdVca7KJ8TM0AFYDg= +cloud.google.com/go/auth v0.4.2/go.mod h1:Kqvlz1cf1sNA0D+sYJnkPQOP+JMHkuHeIgVmCRtZOLc= +cloud.google.com/go/auth/oauth2adapt v0.2.2 h1:+TTV8aXpjeChS9M+aTtN/TjdQnzJvmzKFt//oWu7HX4= +cloud.google.com/go/auth/oauth2adapt v0.2.2/go.mod h1:wcYjgpZI9+Yu7LyYBg4pqSiaRkfEK3GQcpb7C/uyF1Q= +cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc= +cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= @@ -35,10 +37,8 @@ github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:W github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -46,7 +46,6 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= @@ -56,7 +55,7 @@ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs= github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= -github.com/googleapis/gax-go/v2 v2.12.2 h1:mhN09QQW1jEWeMF74zGR81R30z4VJzjZsfkUhuHF+DA= +github.com/googleapis/gax-go/v2 v2.12.4 h1:9gWcmF85Wvq4ryPFvGFaOgPIs1AQX0d0bcbGw4Z96qg= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -67,7 +66,6 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= -github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 h1:4Pp6oUg3+e/6M4C0A/3kJ2VYa++dsWVTtGgLVj5xtHg= @@ -81,55 +79,41 @@ go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA= -golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 h1:LfspQV/FYTatPTr/3HzIcmiUFH7PGP+OQ6mgDYo3yuQ= golang.org/x/exp v0.0.0-20240222234643-814bf88cf225/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= -golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= -golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.18.0 h1:09qnuIAgzdx1XplqJvW6CQqMCtGZykZWcXzPMPUusvI= -golang.org/x/oauth2 v0.18.0/go.mod h1:Wf7knwG0MPoWIMMBgFlEaSUDaKskp0dCfrlJRJXbBi8= +golang.org/x/oauth2 v0.20.0 h1:4mQdhULixXKP1rwYBW0vAijoXnkTG0BLCDRzfe1idMo= +golang.org/x/oauth2 v0.20.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= -golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= -golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -137,28 +121,23 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.169.0 h1:QwWPy71FgMWqJN/l6jVlFHUa29a7dcUy02I8o799nPY= -google.golang.org/api v0.169.0/go.mod h1:gpNOiMA2tZ4mf5R9Iwf4rK/Dcz0fbdIgWYWVoxmsyLg= +google.golang.org/api v0.182.0 h1:if5fPvudRQ78GeRx3RayIoiuV7modtErPIZC/T2bIvE= +google.golang.org/api v0.182.0/go.mod h1:cGhjy4caqA5yXRzEhkHI8Y9mfyC2VLTlER2l08xaqtM= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM= -google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240304161311-37d4d3c04a78 h1:Xs9lu+tLXxLIfuci70nG4cpwaRC+mRQPUL7LoIeDJC4= -google.golang.org/genproto/googleapis/rpc v0.0.0-20240304161311-37d4d3c04a78/go.mod h1:UCOku4NytXMJuLQE5VuqA5lX3PcHCBo8pxNyvkf4xBs= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240521202816-d264139d666e h1:Elxv5MwEkCI9f5SkoL6afed6NTdxaGoAo39eANBwHL8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240521202816-d264139d666e/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.62.0 h1:HQKZ/fa1bXkX1oFOvSjmZEUL8wLSaZTjCcLAlmZRtdk= -google.golang.org/grpc v1.62.0/go.mod h1:IWTG0VlJLCh1SkC58F7np9ka9mx/WNkjl4PGJaiq+QE= +google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA= +google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -168,10 +147,8 @@ google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2 google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= -google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= diff --git a/examples/slog/main.go b/examples/slog/main.go index c5a588c81..0a8f71128 100644 --- a/examples/slog/main.go +++ b/examples/slog/main.go @@ -3,43 +3,43 @@ package main import ( "context" "flag" - "os" "github.com/databricks/databricks-sdk-go" - sdk "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "golang.org/x/exp/slog" ) -var json bool +// slogAdapter makes an slog.Logger usable with the Databricks SDK. +type slogAdapter struct { + *slog.Logger +} -func init() { - flag.BoolVar(&json, "json", false, "log json messages") +func (s *slogAdapter) Log(ctx context.Context, level log.Level, format string, a ...any) { + slevel := slog.LevelDebug + switch level { + case log.LevelInfo: + slevel = slog.LevelInfo + case log.LevelWarn: + slevel = slog.LevelWarn + case log.LevelError: + slevel = slog.LevelError + } + s.Logger.Log(ctx, slevel, format, a...) } func main() { flag.Parse() - opts := slog.HandlerOptions{ - Level: slog.LevelDebug, - } - - var handler slog.Handler - if json { - handler = opts.NewJSONHandler(os.Stderr) - } else { - handler = opts.NewTextHandler(os.Stderr) - } - // Define global logger for the SDK. // This instance is used when no context is present (e.g. upon construction), // or when a context is present but doesn't hold a logger to use. - sdk.DefaultLogger = &slogAdapter{ - slog.New(handler).With("global", true), - } + log.SetDefaultLogger(&slogAdapter{ + slog.Default().With("global", true), + }) - // Define logger on context for the SDK to use. - ctx := sdk.NewContext(context.Background(), &slogAdapter{ - slog.New(handler).With("global", false), + logKey := &struct{}{} // define a unique key for the context value + ctx := context.WithValue(context.Background(), logKey, &slogAdapter{ + slog.Default().With("global", false), }) // Construct client and make a request. diff --git a/examples/slog/slog.go b/examples/slog/slog.go deleted file mode 100644 index b73788764..000000000 --- a/examples/slog/slog.go +++ /dev/null @@ -1,54 +0,0 @@ -package main - -import ( - "context" - "fmt" - - "github.com/databricks/databricks-sdk-go/logger" - "golang.org/x/exp/slog" -) - -// slogAdapter makes an slog.Logger usable with the Databricks SDK. -type slogAdapter struct { - *slog.Logger -} - -func (s *slogAdapter) Enabled(ctx context.Context, level logger.Level) bool { - switch level { - case logger.LevelTrace: - // Note: slog doesn't have a default trace level. - // An application can define their own fine grained levels - // and use those here, if needed. - return s.Logger.Enabled(ctx, slog.LevelDebug) - case logger.LevelDebug: - return s.Logger.Enabled(ctx, slog.LevelDebug) - case logger.LevelInfo: - return s.Logger.Enabled(ctx, slog.LevelInfo) - case logger.LevelWarn: - return s.Logger.Enabled(ctx, slog.LevelWarn) - case logger.LevelError: - return s.Logger.Enabled(ctx, slog.LevelError) - default: - return true - } -} - -func (s *slogAdapter) Tracef(ctx context.Context, format string, v ...any) { - s.DebugContext(ctx, fmt.Sprintf(format, v...)) -} - -func (s *slogAdapter) Debugf(ctx context.Context, format string, v ...any) { - s.DebugContext(ctx, fmt.Sprintf(format, v...)) -} - -func (s *slogAdapter) Infof(ctx context.Context, format string, v ...any) { - s.InfoContext(ctx, fmt.Sprintf(format, v...)) -} - -func (s *slogAdapter) Warnf(ctx context.Context, format string, v ...any) { - s.WarnContext(ctx, fmt.Sprintf(format, v...)) -} - -func (s *slogAdapter) Errorf(ctx context.Context, format string, v ...any) { - s.ErrorContext(ctx, fmt.Sprintf(format, v...), nil) -} diff --git a/examples/zerolog/go.mod b/examples/zerolog/go.mod index 996bf9407..443215bf6 100644 --- a/examples/zerolog/go.mod +++ b/examples/zerolog/go.mod @@ -2,36 +2,43 @@ module main go 1.18 -replace github.com/databricks/databricks-sdk-go v0.0.0 => ../.. +replace github.com/databricks/databricks-sdk-go => ../.. require ( - github.com/databricks/databricks-sdk-go v0.24.0 + github.com/databricks/databricks-sdk-go v0.0.0-00010101000000-000000000000 github.com/rs/zerolog v1.29.0 ) require ( - cloud.google.com/go/compute v1.23.0 // indirect - cloud.google.com/go/compute/metadata v0.2.3 // indirect + cloud.google.com/go/auth v0.4.2 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.2 // indirect + cloud.google.com/go/compute/metadata v0.3.0 // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/go-logr/logr v1.4.1 // indirect + github.com/go-logr/stdr v1.2.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect - github.com/golang/protobuf v1.5.3 // indirect + github.com/golang/protobuf v1.5.4 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/s2a-go v0.1.7 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.1 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.17 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/crypto v0.21.0 // indirect - golang.org/x/exp v0.0.0-20230307190834-24139beb5833 // indirect - golang.org/x/mod v0.13.0 // indirect - golang.org/x/net v0.23.0 // indirect - golang.org/x/oauth2 v0.13.0 // indirect - golang.org/x/sys v0.18.0 // indirect - golang.org/x/text v0.14.0 // indirect - golang.org/x/time v0.3.0 // indirect - google.golang.org/api v0.146.0 // indirect - google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20230920204549-e6e6cdab5c13 // indirect - google.golang.org/grpc v1.58.3 // indirect - google.golang.org/protobuf v1.33.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect + go.opentelemetry.io/otel v1.24.0 // indirect + go.opentelemetry.io/otel/metric v1.24.0 // indirect + go.opentelemetry.io/otel/trace v1.24.0 // indirect + golang.org/x/crypto v0.31.0 // indirect + golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 // indirect + golang.org/x/mod v0.17.0 // indirect + golang.org/x/net v0.33.0 // indirect + golang.org/x/oauth2 v0.20.0 // indirect + golang.org/x/sys v0.28.0 // indirect + golang.org/x/text v0.21.0 // indirect + golang.org/x/time v0.5.0 // indirect + google.golang.org/api v0.182.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240521202816-d264139d666e // indirect + google.golang.org/grpc v1.64.1 // indirect + google.golang.org/protobuf v1.34.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect ) diff --git a/examples/zerolog/go.sum b/examples/zerolog/go.sum index ae8c9ebbf..86e00c424 100644 --- a/examples/zerolog/go.sum +++ b/examples/zerolog/go.sum @@ -1,15 +1,15 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go/compute v1.23.0 h1:tP41Zoavr8ptEqaW6j+LQOnyBBhO7OkOMAGrgLopTwY= -cloud.google.com/go/compute v1.23.0/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdiEZc9FEIbM= -cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= -cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= +cloud.google.com/go/auth v0.4.2 h1:sb0eyLkhRtpq5jA+a8KWw0W70YcdVca7KJ8TM0AFYDg= +cloud.google.com/go/auth v0.4.2/go.mod h1:Kqvlz1cf1sNA0D+sYJnkPQOP+JMHkuHeIgVmCRtZOLc= +cloud.google.com/go/auth/oauth2adapt v0.2.2 h1:+TTV8aXpjeChS9M+aTtN/TjdQnzJvmzKFt//oWu7HX4= +cloud.google.com/go/auth/oauth2adapt v0.2.2/go.mod h1:wcYjgpZI9+Yu7LyYBg4pqSiaRkfEK3GQcpb7C/uyF1Q= +cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc= +cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/databricks/databricks-sdk-go v0.24.0 h1:fx34MOGYXVc72QBSFnKuDa/H3ekDMqZYH4jKZF8mrXk= -github.com/databricks/databricks-sdk-go v0.24.0/go.mod h1:a6rErRNh5bz+IJbO07nwW70iGyvtWidy1p/S5thepXI= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -17,6 +17,13 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -24,7 +31,6 @@ github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= @@ -33,9 +39,8 @@ github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:W github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= -github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -43,17 +48,16 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o= github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= -github.com/googleapis/enterprise-certificate-proxy v0.3.1 h1:SBWmZhjUDRorQxrN0nwzf+AHBxnbFjViHQS4P0yVpmQ= -github.com/googleapis/enterprise-certificate-proxy v0.3.1/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= -github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs= +github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= +github.com/googleapis/gax-go/v2 v2.12.4 h1:9gWcmF85Wvq4ryPFvGFaOgPIs1AQX0d0bcbGw4Z96qg= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= @@ -74,37 +78,45 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 h1:4Pp6oUg3+e/6M4C0A/3kJ2VYa++dsWVTtGgLVj5xtHg= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw= +go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= +go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= +go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI= +go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco= +go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI= +go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA= -golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20230307190834-24139beb5833 h1:SChBja7BCQewoTAU7IgvucQKMIXrEpFxNMs0spT3/5s= -golang.org/x/exp v0.0.0-20230307190834-24139beb5833/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= +golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 h1:LfspQV/FYTatPTr/3HzIcmiUFH7PGP+OQ6mgDYo3yuQ= +golang.org/x/exp v0.0.0-20240222234643-814bf88cf225/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.13.0 h1:I/DsJXRlw/8l/0c24sM9yb0T4z9liZTduXvdAWYiysY= -golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= -golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.13.0 h1:jDDenyj+WgFtmV3zYVoi8aE2BwtXFLWOA67ZfNWftiY= -golang.org/x/oauth2 v0.13.0/go.mod h1:/JMhi4ZRXAf4HG9LiNmxvk+45+96RUlVThiH8FzNBn0= +golang.org/x/oauth2 v0.20.0 h1:4mQdhULixXKP1rwYBW0vAijoXnkTG0BLCDRzfe1idMo= +golang.org/x/oauth2 v0.20.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -112,39 +124,36 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= -golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= -golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.146.0 h1:9aBYT4vQXt9dhCuLNfwfd3zpwu8atg0yPkjBymwSrOM= -google.golang.org/api v0.146.0/go.mod h1:OARJqIfoYjXJj4C1AiBSXYZt03qsoz8FQYU6fBEfrHM= +google.golang.org/api v0.182.0 h1:if5fPvudRQ78GeRx3RayIoiuV7modtErPIZC/T2bIvE= +google.golang.org/api v0.182.0/go.mod h1:cGhjy4caqA5yXRzEhkHI8Y9mfyC2VLTlER2l08xaqtM= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto/googleapis/rpc v0.0.0-20230920204549-e6e6cdab5c13 h1:N3bU/SQDCDyD6R528GJ/PwW9KjYcJA3dgyH+MovAkIM= -google.golang.org/genproto/googleapis/rpc v0.0.0-20230920204549-e6e6cdab5c13/go.mod h1:KSqppvjFjtoCI+KGd4PELB0qLNxdJHRGqRI09mB6pQA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240521202816-d264139d666e h1:Elxv5MwEkCI9f5SkoL6afed6NTdxaGoAo39eANBwHL8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240521202816-d264139d666e/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.58.3 h1:BjnpXut1btbtgN/6sp+brB2Kbm2LjNXnidYujAVbSoQ= -google.golang.org/grpc v1.58.3/go.mod h1:tgX3ZQDlNJGU96V6yHh1T/JeoBQ2TXdr43YbYSsCJk0= +google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA= +google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -154,10 +163,8 @@ google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2 google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI= -google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= diff --git a/examples/zerolog/main.go b/examples/zerolog/main.go index 36e1283ed..b4f6ae049 100644 --- a/examples/zerolog/main.go +++ b/examples/zerolog/main.go @@ -6,9 +6,9 @@ import ( "os" "github.com/databricks/databricks-sdk-go" - sdk "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/rs/zerolog" - "github.com/rs/zerolog/log" + zlog "github.com/rs/zerolog/log" ) var json bool @@ -17,23 +17,43 @@ func init() { flag.BoolVar(&json, "json", false, "log json messages") } +// zerologAdapter makes an zerolog.Logger usable with the Databricks SDK. +type zerologAdapter struct { + zerolog.Logger +} + +func (z *zerologAdapter) Log(ctx context.Context, level log.Level, format string, a ...any) { + switch level { + case log.LevelTrace: + z.Logger.Trace().Msgf(format, a...) + case log.LevelDebug: + z.Logger.Debug().Msgf(format, a...) + case log.LevelInfo: + z.Logger.Info().Msgf(format, a...) + case log.LevelWarn: + z.Logger.Warn().Msgf(format, a...) + case log.LevelError: + z.Logger.Error().Msgf(format, a...) + } +} + func main() { flag.Parse() var l zerolog.Logger if json { - l = log.Output(os.Stderr) + l = zlog.Output(os.Stderr) } else { - l = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}) + l = zlog.Output(zerolog.ConsoleWriter{Out: os.Stderr}) } // Define global logger for the SDK. // This instance is used when no context is present (e.g. upon construction), // or when a context is present but doesn't hold a logger to use. - sdk.DefaultLogger = &zerologAdapter{l.With().Bool("global", true).Logger()} + log.SetDefaultLogger(&zerologAdapter{l.With().Bool("global", true).Logger()}) - // Define logger on context for the SDK to use. - ctx := sdk.NewContext(context.Background(), &zerologAdapter{ + logKey := &struct{}{} // define a unique key for the context value + ctx := context.WithValue(context.Background(), logKey, &zerologAdapter{ l.With().Bool("global", false).Logger(), }) diff --git a/examples/zerolog/zerolog.go b/examples/zerolog/zerolog.go deleted file mode 100644 index 16906360c..000000000 --- a/examples/zerolog/zerolog.go +++ /dev/null @@ -1,50 +0,0 @@ -package main - -import ( - "context" - - "github.com/databricks/databricks-sdk-go/logger" - "github.com/rs/zerolog" -) - -// zerologAdapter makes an zerolog.Logger usable with the Databricks SDK. -type zerologAdapter struct { - zerolog.Logger -} - -func (z *zerologAdapter) Enabled(_ context.Context, level logger.Level) bool { - switch level { - case logger.LevelTrace: - return z.Logger.GetLevel() <= zerolog.TraceLevel - case logger.LevelDebug: - return z.Logger.GetLevel() <= zerolog.DebugLevel - case logger.LevelInfo: - return z.Logger.GetLevel() <= zerolog.InfoLevel - case logger.LevelWarn: - return z.Logger.GetLevel() <= zerolog.WarnLevel - case logger.LevelError: - return z.Logger.GetLevel() <= zerolog.ErrorLevel - default: - return true - } -} - -func (s *zerologAdapter) Tracef(_ context.Context, format string, v ...any) { - s.Logger.Trace().Msgf(format, v...) -} - -func (s *zerologAdapter) Debugf(_ context.Context, format string, v ...any) { - s.Logger.Debug().Msgf(format, v...) -} - -func (s *zerologAdapter) Infof(_ context.Context, format string, v ...any) { - s.Logger.Info().Msgf(format, v...) -} - -func (s *zerologAdapter) Warnf(_ context.Context, format string, v ...any) { - s.Logger.Warn().Msgf(format, v...) -} - -func (s *zerologAdapter) Errorf(_ context.Context, format string, v ...any) { - s.Logger.Error().Msgf(format, v...) -} diff --git a/go.mod b/go.mod index 0f7fbce9f..27c55a092 100644 --- a/go.mod +++ b/go.mod @@ -2,6 +2,8 @@ module github.com/databricks/databricks-sdk-go go 1.18 +replace github.com/databricks/databricks-sdk-go => . + require ( github.com/google/go-cmp v0.6.0 github.com/google/go-querystring v1.1.0 diff --git a/httpclient/api_client.go b/httpclient/api_client.go index 2b51cdb44..dfa389ef4 100644 --- a/httpclient/api_client.go +++ b/httpclient/api_client.go @@ -14,8 +14,8 @@ import ( "github.com/databricks/databricks-sdk-go/common" "github.com/databricks/databricks-sdk-go/databricks/httplog" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/httpclient/traceparent" - "github.com/databricks/databricks-sdk-go/logger" "github.com/databricks/databricks-sdk-go/retries" "github.com/databricks/databricks-sdk-go/useragent" "golang.org/x/oauth2" @@ -176,14 +176,14 @@ func (c *ApiClient) isRetriable(ctx context.Context, err error) bool { } if isRetriableUrlError(err) { // all IO errors are retriable - logger.Debugf(ctx, "Attempting retry because of IO error: %s", err) + log.DebugContext(ctx, "Attempting retry because of IO error: %s", err) return true } message := err.Error() // Handle transient errors for retries for _, substring := range c.config.TransientErrors { if strings.Contains(message, substring) { - logger.Debugf(ctx, "Attempting retry because of %#v", substring) + log.DebugContext(ctx, "Attempting retry because of %#v", substring) return true } } @@ -310,11 +310,9 @@ func (c *ApiClient) recordRequestLog( err error, requestBody, responseBody []byte, ) { - // Don't compute expensive debug message if debug logging is not enabled. - if !logger.Get(ctx).Enabled(ctx, logger.LevelDebug) { - return - } - message := httplog.RoundTripStringer{ + // TODO: Find a way to avoid computing expensive debug message if debug + // logging is not enabled. + log.DebugContext(ctx, "%s", httplog.RoundTripStringer{ Request: request, Response: response, Err: err, @@ -323,8 +321,7 @@ func (c *ApiClient) recordRequestLog( DebugHeaders: c.config.DebugHeaders, DebugTruncateBytes: c.config.DebugTruncateBytes, DebugAuthorizationHeader: true, - }.String() - logger.Debugf(ctx, "%s", message) + }) } // RoundTrip implements http.RoundTripper to integrate with golang.org/x/oauth2 diff --git a/httpclient/api_client_test.go b/httpclient/api_client_test.go index 5e382a565..1c14d0df0 100644 --- a/httpclient/api_client_test.go +++ b/httpclient/api_client_test.go @@ -13,7 +13,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go/common" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/oauth2" @@ -329,36 +329,16 @@ type BufferLogger struct { strings.Builder } -func (l *BufferLogger) Enabled(_ context.Context, level logger.Level) bool { - return true -} - -func (l *BufferLogger) Tracef(_ context.Context, format string, v ...interface{}) { - l.WriteString(fmt.Sprintf("[TRACE] "+format+"\n", v...)) -} - -func (l *BufferLogger) Debugf(_ context.Context, format string, v ...interface{}) { - l.WriteString(fmt.Sprintf("[DEBUG] "+format+"\n", v...)) -} - -func (l *BufferLogger) Infof(_ context.Context, format string, v ...interface{}) { - l.WriteString(fmt.Sprintf("[INFO] "+format+"\n", v...)) -} - -func (l *BufferLogger) Warnf(_ context.Context, format string, v ...interface{}) { - l.WriteString(fmt.Sprintf("[WARN] "+format+"\n", v...)) -} - -func (l *BufferLogger) Errorf(_ context.Context, format string, v ...interface{}) { - l.WriteString(fmt.Sprintf("[ERROR] "+format+"\n", v...)) +func (l *BufferLogger) Log(ctx context.Context, level log.Level, format string, a ...any) { + l.WriteString(fmt.Sprintf("[%s] %s\n", level, fmt.Sprintf(format, a...))) } func configureBufferedLogger(t *testing.T) *BufferLogger { - prevLogger := logger.DefaultLogger + prevLogger := log.DefaultLogger() bufLogger := &BufferLogger{} - logger.DefaultLogger = bufLogger + log.SetDefaultLogger(bufLogger) t.Cleanup(func() { - logger.DefaultLogger = prevLogger + log.SetDefaultLogger(prevLogger) }) return bufLogger } diff --git a/httpclient/fixtures/map_transport_test.go b/httpclient/fixtures/map_transport_test.go index 8fc9fe051..720397219 100644 --- a/httpclient/fixtures/map_transport_test.go +++ b/httpclient/fixtures/map_transport_test.go @@ -4,17 +4,15 @@ import ( "context" "testing" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/httpclient" "github.com/databricks/databricks-sdk-go/httpclient/fixtures" - "github.com/databricks/databricks-sdk-go/logger" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func init() { - logger.DefaultLogger = &logger.SimpleLogger{ - Level: logger.LevelDebug, - } + log.SetDefaultLogger(log.New(log.LevelDebug)) } func TestSimpleGetErrorStub(t *testing.T) { diff --git a/httpclient/fixtures/named.go b/httpclient/fixtures/named.go new file mode 100644 index 000000000..d6582bc4d --- /dev/null +++ b/httpclient/fixtures/named.go @@ -0,0 +1,116 @@ +package fixtures + +import ( + "strings" + "unicode" +) + +// Named holds common methods for identifying and describing things +type Named struct { + Name string + Description string +} + +// Return the value of cond evaluated at the nearest letter to index i in name. +// dir determines the direction of search: if true, search forwards, if false, +// search backwards. +func (n *Named) search(name string, cond func(rune) bool, dir bool, i int) bool { + nameLen := len(name) + incr := 1 + if !dir { + incr = -1 + } + for j := i; j >= 0 && j < nameLen; j += incr { + if unicode.IsLetter(rune(name[j])) { + return cond(rune(name[j])) + } + } + return false +} + +// Return the value of cond evaluated on the rune at index i in name. If that +// rune is not a letter, search in both directions for the nearest letter and +// return the result of cond on those letters. +func (n *Named) checkCondAtNearestLetters(name string, cond func(rune) bool, i int) bool { + r := rune(name[i]) + + if unicode.IsLetter(r) { + return cond(r) + } + return n.search(name, cond, true, i) && n.search(name, cond, false, i) +} + +// emulate positive lookaheads from JVM regex: +// (?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|([-_\s]) +// and convert all words to lower case + +func (n *Named) splitASCII() (w []string) { + var current []rune + var name = n.Name + nameLen := len(name) + var isPrevUpper, isCurrentUpper, isNextLower, isNextUpper, isNotLastChar bool + // we do assume here that all named entities are strictly ASCII + for i := 0; i < nameLen; i++ { + r := rune(name[i]) + if r == '$' { + // we're naming language literals, $ is usually not allowed + continue + } + // if the current rune is a digit, check the neighboring runes to + // determine whether to treat this one as upper-case. + isCurrentUpper = n.checkCondAtNearestLetters(name, unicode.IsUpper, i) + r = unicode.ToLower(r) + isNextLower = false + isNextUpper = false + isNotLastChar = i+1 < nameLen + if isNotLastChar { + isNextLower = n.checkCondAtNearestLetters(name, unicode.IsLower, i+1) + isNextUpper = n.checkCondAtNearestLetters(name, unicode.IsUpper, i+1) + } + split, before, after := false, false, true + // At the end of a string of capital letters (e.g. HTML[P]arser). + if isPrevUpper && isCurrentUpper && isNextLower && isNotLastChar { + // (?<=[A-Z])(?=[A-Z][a-z]) + split = true + before = false + after = true + } + // At the end of a camel- or pascal-case word (e.g. htm[l]Parser). + if !isCurrentUpper && isNextUpper { + // (?<=[a-z])(?=[A-Z]) + split = true + before = true + after = false + } + if !unicode.IsLetter(r) && !unicode.IsNumber(r) { + // ([-_\s]) + split = true + before = false + after = false + } + if before { + current = append(current, r) + } + if split && len(current) > 0 { + w = append(w, string(current)) + current = []rune{} + } + if after { + current = append(current, r) + } + isPrevUpper = isCurrentUpper + } + if len(current) > 0 { + w = append(w, string(current)) + } + return w +} + +// PascalName creates NamesLikesThis +func (n *Named) PascalName() string { + var sb strings.Builder + for _, w := range n.splitASCII() { + sb.WriteString(strings.Title(w)) + } + return sb.String() +} diff --git a/httpclient/fixtures/stub.go b/httpclient/fixtures/stub.go index 7c213bf03..1aa8b8009 100644 --- a/httpclient/fixtures/stub.go +++ b/httpclient/fixtures/stub.go @@ -6,8 +6,6 @@ import ( "fmt" "net/http" "net/url" - - "github.com/databricks/databricks-sdk-go/openapi/code" ) func resourceFromRequest(req *http.Request) string { @@ -57,7 +55,7 @@ func bodyStub(req *http.Request) (string, error) { // which is not something i'm willing to write on my weekend expectedRequest += "ExpectedRequest: XXX {\n" for key, value := range receivedRequest { - camel := (&code.Named{Name: key}).PascalName() + camel := (&Named{Name: key}).PascalName() expectedRequest += fmt.Sprintf("\t\t\t%s: %#v,\n", camel, value) } expectedRequest += "\t\t},\n" diff --git a/httpclient/response.go b/httpclient/response.go index 521aa5358..339aee05b 100644 --- a/httpclient/response.go +++ b/httpclient/response.go @@ -2,7 +2,6 @@ package httpclient import ( "bytes" - "context" "encoding/json" "fmt" "io" @@ -13,7 +12,7 @@ import ( "github.com/databricks/databricks-sdk-go/common" "github.com/databricks/databricks-sdk-go/databricks/apierr" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" ) func WithResponseHeader(key string, value *string) DoOption { @@ -154,7 +153,7 @@ func injectHeaders(response any, body *common.ResponseWrapper) error { value.Field(i).Set(reflect.ValueOf(intValue)) default: // Do not fail the request if the header is not supported to avoid breaking changes. - logger.Warnf(context.Background(), "unsupported header type %s for field %s", field.Type.Kind(), field.Name) + log.Warning("unsupported header type %s for field %s", field.Type.Kind(), field.Name) } } diff --git a/internal/acceptance_test.go b/internal/acceptance_test.go index 3d8d6e3b1..470371838 100644 --- a/internal/acceptance_test.go +++ b/internal/acceptance_test.go @@ -8,17 +8,15 @@ import ( "github.com/databricks/databricks-sdk-go" "github.com/databricks/databricks-sdk-go/config" "github.com/databricks/databricks-sdk-go/databricks/apierr" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/internal/env" - "github.com/databricks/databricks-sdk-go/logger" "github.com/databricks/databricks-sdk-go/service/compute" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func init() { - logger.DefaultLogger = &logger.SimpleLogger{ - Level: logger.LevelDebug, - } + log.SetDefaultLogger(log.New(log.LevelDebug)) } func TestAccDefaultCredentials(t *testing.T) { diff --git a/internal/init_test.go b/internal/init_test.go index 7a427b588..41ea2caad 100644 --- a/internal/init_test.go +++ b/internal/init_test.go @@ -14,7 +14,7 @@ import ( "github.com/databricks/databricks-sdk-go" "github.com/databricks/databricks-sdk-go/config" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/qa" ) @@ -23,9 +23,7 @@ const hexCharset = "0123456789abcdef" func init() { databricks.WithProduct("integration-tests", databricks.Version()) - logger.DefaultLogger = &logger.SimpleLogger{ - Level: logger.LevelDebug, - } + log.SetDefaultLogger(log.New(log.LevelDebug)) } // prelude for all workspace-level tests diff --git a/logger/context.go b/logger/context.go deleted file mode 100644 index c74661a71..000000000 --- a/logger/context.go +++ /dev/null @@ -1,18 +0,0 @@ -package logger - -import "context" - -type logger int - -var loggerKey logger - -// NewContext returns a new Context that carries the specified logger. -func NewContext(ctx context.Context, logger Logger) context.Context { - return context.WithValue(ctx, loggerKey, logger) -} - -// FromContext returns the Logger value stored in ctx, if any. -func FromContext(ctx context.Context) (Logger, bool) { - u, ok := ctx.Value(loggerKey).(Logger) - return u, ok -} diff --git a/logger/context_test.go b/logger/context_test.go deleted file mode 100644 index 20d7f510f..000000000 --- a/logger/context_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package logger - -import ( - "context" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestLoggerContext(t *testing.T) { - logger, ok := FromContext(context.Background()) - assert.Nil(t, logger) - assert.False(t, ok) - - ctx := NewContext(context.Background(), &SimpleLogger{}) - logger, ok = FromContext(ctx) - assert.NotNil(t, logger) - assert.True(t, ok) -} diff --git a/logger/logger.go b/logger/logger.go deleted file mode 100644 index 43d9219c1..000000000 --- a/logger/logger.go +++ /dev/null @@ -1,70 +0,0 @@ -package logger - -import ( - "context" -) - -var DefaultLogger Logger = &SimpleLogger{} - -// Level maps to the logging levels in [Logger]. -type Level int - -const ( - LevelTrace = -8 - LevelDebug = -4 - LevelInfo = 0 - LevelWarn = 4 - LevelError = 8 -) - -type Logger interface { - // Enabled returns if logging at the specified level is enabled. - // This can be used to avoid computating an expensive value if it - // won't be logged anyway. - Enabled(ctx context.Context, level Level) bool - - // Tracef logs a formatted string at [LevelTrace]. - Tracef(ctx context.Context, format string, v ...any) - - // Debugf logs a formatted string at [LevelDebug]. - Debugf(ctx context.Context, format string, v ...any) - - // Infof logs a formatted string at [LevelInfo]. - Infof(ctx context.Context, format string, v ...any) - - // Warnf logs a formatted string at [LevelWarn]. - Warnf(ctx context.Context, format string, v ...any) - - // Errorf logs a formatted string at [LevelError]. - Errorf(ctx context.Context, format string, v ...any) -} - -// Get returns either the logger configured on the context, -// or the global logger if one isn't defined. -func Get(ctx context.Context) Logger { - logger, ok := FromContext(ctx) - if !ok { - logger = DefaultLogger - } - return logger -} - -func Tracef(ctx context.Context, format string, v ...any) { - Get(ctx).Tracef(ctx, format, v...) -} - -func Debugf(ctx context.Context, format string, v ...any) { - Get(ctx).Debugf(ctx, format, v...) -} - -func Infof(ctx context.Context, format string, v ...any) { - Get(ctx).Infof(ctx, format, v...) -} - -func Warnf(ctx context.Context, format string, v ...any) { - Get(ctx).Warnf(ctx, format, v...) -} - -func Errorf(ctx context.Context, format string, v ...any) { - Get(ctx).Errorf(ctx, format, v...) -} diff --git a/logger/logger_test.go b/logger/logger_test.go deleted file mode 100644 index 31bfb6197..000000000 --- a/logger/logger_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package logger - -import ( - "context" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGetLogger(t *testing.T) { - t.Cleanup(func() { - DefaultLogger = &SimpleLogger{} - }) - - t1 := &SimpleLogger{} - t2 := &SimpleLogger{} - DefaultLogger = t1 - - logger := Get(context.Background()) - assert.Equal(t, logger, t1) - - ctx := NewContext(context.Background(), t2) - logger = Get(ctx) - assert.Equal(t, logger, t2) -} - -func TestWhenInfoLevelThenDebugDisabled(t *testing.T) { - t.Cleanup(func() { - DefaultLogger = &SimpleLogger{} - }) - - infoLevelLogger := &SimpleLogger{ - Level: LevelInfo, - } - debugEnabled := infoLevelLogger.Enabled(context.Background(), LevelDebug) - assert.False(t, debugEnabled) -} - -func TestWhenInfoLevelThenErrorEnabled(t *testing.T) { - infoLevelLogger := &SimpleLogger{ - Level: LevelInfo, - } - - errorEnabled := infoLevelLogger.Enabled(context.Background(), LevelError) - assert.True(t, errorEnabled) -} - -func TestDefaultLevelInfo(t *testing.T) { - logger := &SimpleLogger{} - assert.EqualValues(t, LevelInfo, logger.Level) -} diff --git a/logger/simple.go b/logger/simple.go deleted file mode 100644 index 62ae04242..000000000 --- a/logger/simple.go +++ /dev/null @@ -1,49 +0,0 @@ -package logger - -import ( - "context" - "log" -) - -type SimpleLogger struct { - Level Level -} - -func (l *SimpleLogger) Enabled(_ context.Context, level Level) bool { - return level >= l.Level -} - -func (l *SimpleLogger) Tracef(ctx context.Context, format string, v ...any) { - if !l.Enabled(ctx, LevelTrace) { - return - } - log.Printf("[TRACE] "+format, v...) -} - -func (l *SimpleLogger) Debugf(ctx context.Context, format string, v ...any) { - if !l.Enabled(ctx, LevelDebug) { - return - } - log.Printf("[DEBUG] "+format, v...) -} - -func (l *SimpleLogger) Infof(ctx context.Context, format string, v ...any) { - if !l.Enabled(ctx, LevelInfo) { - return - } - log.Printf("[INFO] "+format, v...) -} - -func (l *SimpleLogger) Warnf(ctx context.Context, format string, v ...any) { - if !l.Enabled(ctx, LevelWarn) { - return - } - log.Printf("[WARN] "+format, v...) -} - -func (l *SimpleLogger) Errorf(ctx context.Context, format string, v ...any) { - if !l.Enabled(ctx, LevelError) { - return - } - log.Printf("[ERROR] "+format, v...) -} diff --git a/openapi/code/entity.go b/openapi/code/entity.go deleted file mode 100644 index 67d137277..000000000 --- a/openapi/code/entity.go +++ /dev/null @@ -1,403 +0,0 @@ -package code - -import ( - "fmt" - "sort" - - "github.com/databricks/databricks-sdk-go/openapi" -) - -// Field of a Type (Entity) -type Field struct { - Named - Required bool - Entity *Entity - Of *Entity - IsJson bool - IsPath bool - IsPathMultiSegment bool - IsQuery bool - IsHeader bool - Schema *openapi.Schema -} - -func (f *Field) IsOptionalObject() bool { - return f.Entity != nil && !f.Required && (f.Entity.IsObject() || f.Entity.IsExternal()) -} - -// IsPrivatePreview flags object being in private preview. -func (f *Field) IsPrivatePreview() bool { - return f.Schema != nil && isPrivatePreview(&f.Schema.Node) -} - -// IsPublicPreview flags object being in public preview. -func (f *Field) IsPublicPreview() bool { - return f.Schema != nil && isPublicPreview(&f.Schema.Node) -} - -// IsRequestBodyField indicates a field which can only be set as part of request body -// There are some fields, such as PipelineId for example, which can be both used in JSON and -// as path parameters. In code generation we handle path and request body parameters separately -// by making path parameters always required. Thus, we don't need to consider such fields -// as request body fields anymore. -func (f *Field) IsRequestBodyField() bool { - return f.IsJson && !f.IsPath && !f.IsQuery && !f.IsHeader -} - -// Call the provided callback on this field and any nested fields in its entity, -// recursively. -func (f *Field) Traverse(fn func(*Field)) { - fn(f) - if f.Entity != nil && len(f.Entity.fields) > 0 { - for _, field := range f.Entity.fields { - field.Traverse(fn) - } - } -} - -type EnumEntry struct { - Named - Entity *Entity - // SCIM API has schema specifiers - Content string -} - -// Entity represents a Type -type Entity struct { - Named - Package *Package - enum map[string]EnumEntry - ArrayValue *Entity - MapValue *Entity - IsInt bool - IsInt64 bool - IsFloat64 bool - IsBool bool - IsString bool - IsByteStream bool - - // this field does not have a concrete type - IsAny bool - - // this field is computed on the platform side - IsComputed bool - - // if entity has required fields, this is the order of them - RequiredOrder []string - fields map[string]*Field - - // Schema references the OpenAPI schema this entity was created from. - Schema *openapi.Schema - Terraform *Terraform -} - -type Terraform struct { - Alias string -} - -// Whether the Entity contains a basic GoLang type which is not required -func (e *Entity) ShouldIncludeForceSendFields() bool { - for _, field := range e.fields { - fieldType := field.Entity - if !field.Required && fieldType.IsBasicGoLangType() { - return true - } - } - return false -} - -// Whether this entity represents a basic GoLang type -func (e *Entity) IsBasicGoLangType() bool { - return e.IsBool || e.IsInt64 || e.IsInt || e.IsFloat64 || e.IsString -} - -// FullName includes package name and untransformed name of the entity -func (e *Entity) FullName() string { - return fmt.Sprintf("%s.%s", e.Package.FullName(), e.PascalName()) -} - -// PascalName overrides parent implementation by appending List -// suffix for unnamed list types -func (e *Entity) PascalName() string { - if e.Name == "" && e.ArrayValue != nil { - return e.ArrayValue.PascalName() + "List" - } - return e.Named.PascalName() -} - -// CamelName overrides parent implementation by appending List -// suffix for unnamed list types -func (e *Entity) CamelName() string { - if e.Name == "" && e.ArrayValue != nil { - return e.ArrayValue.CamelName() + "List" - } - return e.Named.CamelName() -} - -// Field gets field representation by name or nil -func (e *Entity) Field(name string) *Field { - if e == nil { - // nil received: entity is not present - return nil - } - field, ok := e.fields[name] - if !ok { - return nil - } - field.Of = e - return field -} - -// Given a list of field names, return the list of *Field objects which result -// from following the path of fields in the entity. -func (e *Entity) GetUnderlyingFields(path []string) ([]*Field, error) { - if len(path) == 0 { - return nil, fmt.Errorf("empty path is not allowed (entity: %s)", e.FullName()) - } - if len(path) == 1 { - return []*Field{e.Field(path[0])}, nil - } - field := e.Field(path[0]) - if field == nil { - return nil, fmt.Errorf("field %s not found in entity %s", path[0], e.FullName()) - } - rest, err := field.Entity.GetUnderlyingFields(path[1:]) - if err != nil { - return nil, err - } - return append([]*Field{field}, rest...), nil -} - -// IsObject returns true if entity is an object. We determine this by checking if -// it is any other type of structure. -func (e *Entity) IsObject() bool { - return len(e.enum) == 0 && - e.ArrayValue == nil && - e.MapValue == nil && - !e.IsInt && - !e.IsInt64 && - !e.IsFloat64 && - !e.IsBool && - !e.IsString && - !e.IsByteStream && - !e.IsAny -} - -func (e *Entity) IsMap() bool { - return e.MapValue != nil -} - -// IsExternal returns true if entity is declared in external package and -// has to be imported from it -func (e *Entity) IsExternal() bool { - return e.Package != nil && len(e.Package.types) == 0 -} - -func (e *Entity) IsEmpty() bool { - return e.IsObject() && - len(e.fields) == 0 && - !e.IsComputed && - !e.IsExternal() -} - -func (e *Entity) RequiredFields() (fields []*Field) { - for _, r := range e.RequiredOrder { - v := e.fields[r] - v.Of = e - fields = append(fields, v) - } - - // Path fields should always be first in required arguments order. - // We use stable sort to male sure we preserve the path arguments order - sort.SliceStable(fields, func(a, b int) bool { - return fields[a].IsPath && !fields[b].IsPath - }) - return -} - -func (e *Entity) RequiredPathFields() (fields []*Field) { - for _, r := range e.RequiredOrder { - v := e.fields[r] - if !v.IsPath { - continue - } - v.Of = e - fields = append(fields, v) - } - return -} - -func (e *Entity) RequiredRequestBodyFields() (fields []*Field) { - for _, r := range e.RequiredOrder { - v := e.fields[r] - if !v.IsRequestBodyField() { - continue - } - v.Of = e - fields = append(fields, v) - } - return -} - -func (e *Entity) NonRequiredFields() (fields []*Field) { - required := map[string]bool{} - for _, r := range e.RequiredOrder { - required[r] = true - } - for k, v := range e.fields { - if required[k] { - // handled in [Entity.RequiredFields] - continue - } - v.Of = e - fields = append(fields, v) - } - pascalNameSort(fields) - return -} - -// Fields returns sorted slice of field representations -func (e *Entity) Fields() (fields []*Field) { - for _, v := range e.fields { - v.Of = e - fields = append(fields, v) - } - pascalNameSort(fields) - return fields -} - -// HasQueryField returns true if any of the fields is from query -func (e *Entity) HasQueryField() bool { - for _, v := range e.fields { - if v.IsQuery { - return true - } - } - return false -} - -// HasByteStreamField returns true if any of the fields is a ByteStream -func (e *Entity) HasByteStreamField() bool { - for _, v := range e.fields { - if v.Entity.IsByteStream { - return true - } - } - return false -} - -// HasHeaderField returns true if any of the fields is from header -func (e *Entity) HasHeaderField() bool { - for _, v := range e.fields { - if v.IsHeader { - return true - } - } - return false -} - -// HasJsonField returns true if any of the fields is in the body -func (e *Entity) HasJsonField() bool { - for _, v := range e.fields { - if v.IsJson { - return true - } - } - return false -} - -// Enum returns all entries for enum entities -func (e *Entity) Enum() (enum []EnumEntry) { - for _, v := range e.enum { - enum = append(enum, v) - } - sort.Slice(enum, func(i, j int) bool { - return enum[i].Name < enum[j].Name - }) - return enum -} - -func (e *Entity) IsPrimitive() bool { - return e.IsNumber() || e.IsBool || e.IsString || len(e.enum) > 0 -} - -// IsNumber returns true if field is numeric -func (e *Entity) IsNumber() bool { - return e.IsInt64 || e.IsInt || e.IsFloat64 -} - -func (e *Entity) IsOnlyPrimitiveFields() bool { - for _, v := range e.fields { - if !v.Entity.IsPrimitive() { - return false - } - } - return true -} - -func (e *Entity) IsAllRequiredFieldsPrimitive() bool { - for _, v := range e.RequiredFields() { - if !v.Entity.IsPrimitive() { - return false - } - } - return true -} - -func (e *Entity) HasRequiredPathFields() bool { - return len(e.RequiredPathFields()) > 0 -} - -func (e *Entity) HasRequiredRequestBodyFields() bool { - return len(e.RequiredRequestBodyFields()) > 0 -} - -// IsPrivatePreview flags object being in private preview. -func (e *Entity) IsPrivatePreview() bool { - return e.Schema != nil && isPrivatePreview(&e.Schema.Node) -} - -// IsPublicPreview flags object being in public preview. -func (e *Entity) IsPublicPreview() bool { - return e.Schema != nil && isPublicPreview(&e.Schema.Node) -} - -func (e *Entity) IsRequest() bool { - for _, svc := range e.Package.services { - for _, m := range svc.methods { - if m.Request == e { - return true - } - } - } - return false -} - -func (e *Entity) IsResponse() bool { - for _, svc := range e.Package.services { - for _, m := range svc.methods { - if m.Response == e { - return true - } - } - } - return false -} - -func (e *Entity) IsReferred() bool { - for _, t := range e.Package.types { - for _, f := range t.fields { - if f.Entity == e { - return true - } - } - } - return false -} - -func (e *Entity) Traverse(fn func(*Entity)) { - fn(e) - for _, f := range e.fields { - f.Entity.Traverse(fn) - } -} diff --git a/openapi/code/errors.go b/openapi/code/errors.go deleted file mode 100644 index 074938fc3..000000000 --- a/openapi/code/errors.go +++ /dev/null @@ -1,108 +0,0 @@ -package code - -import ( - "github.com/databricks/databricks-sdk-go/openapi" -) - -type ExceptionType struct { - Named - StatusCode int - Inherit *Named -} - -func (et *ExceptionType) FullName() string { - return et.Name -} - -type ErrorMappingRule struct { - Named - StatusCode int - ErrorCode string -} - -func (b *Batch) ErrorStatusCodeMapping() (rules []ErrorMappingRule) { - for _, em := range openapi.ErrorStatusCodeMapping { - rules = append(rules, ErrorMappingRule{ - StatusCode: em.StatusCode, - Named: Named{ - Name: em.ErrorCode, - }, - }) - } - return rules -} - -func (b *Batch) ErrorCodeMapping() (rules []ErrorMappingRule) { - for _, em := range openapi.ErrorCodeMapping { - rules = append(rules, ErrorMappingRule{ - ErrorCode: em.ErrorCode, - Named: Named{ - Name: em.ErrorCode, - }, - }) - } - return rules -} - -func (b *Batch) ExceptionTypes() []*ExceptionType { - statusCodeMapping := map[int]*Named{} - exceptionTypes := []*ExceptionType{} - for _, em := range openapi.ErrorStatusCodeMapping { - statusCodeMapping[em.StatusCode] = &Named{ - Name: em.ErrorCode, - } - exceptionTypes = append(exceptionTypes, &ExceptionType{ - Named: Named{ - Name: em.ErrorCode, - Description: em.Description, - }, - StatusCode: em.StatusCode, - }) - } - for _, em := range openapi.ErrorCodeMapping { - exceptionTypes = append(exceptionTypes, &ExceptionType{ - Named: Named{ - Name: em.ErrorCode, - Description: em.Description, - }, - StatusCode: em.StatusCode, - Inherit: statusCodeMapping[em.StatusCode], - }) - } - return exceptionTypes -} - -type ErrorOverride struct { - Name string - PathRegex string - Verb string - StatusCodeMatcher string - ErrorCodeMatcher string - MessageMatcher string - OverrideErrorCode Named -} - -func (b *Batch) ErrorOverrides() []ErrorOverride { - res := []ErrorOverride{} - for _, eo := range openapi.ErrorOverrides { - res = append(res, ErrorOverride{ - Name: eo.Name, - PathRegex: eo.PathRegex.String(), - Verb: eo.Verb, - StatusCodeMatcher: eo.StatusCodeMatcher.String(), - ErrorCodeMatcher: eo.ErrorCodeMatcher.String(), - MessageMatcher: eo.MessageMatcher.String(), - OverrideErrorCode: Named{ - Name: eo.OverrideErrorCode, - }, - }) - } - return res -} - -func (b *Batch) TransientErrorRegexes() (res []string) { - for _, r := range openapi.TransientErrorRegexes { - res = append(res, r.String()) - } - return res -} diff --git a/openapi/code/load.go b/openapi/code/load.go deleted file mode 100644 index 9be8c2c40..000000000 --- a/openapi/code/load.go +++ /dev/null @@ -1,129 +0,0 @@ -package code - -import ( - "context" - "fmt" - "os" - "sort" - "strings" - - "github.com/databricks/databricks-sdk-go/openapi" -) - -type Batch struct { - packages map[string]*Package -} - -// NewFromFile loads OpenAPI specification from file -func NewFromFile(ctx context.Context, name string) (*Batch, error) { - f, err := os.Open(name) - if err != nil { - return nil, fmt.Errorf("no %s file: %w", name, err) - } - defer f.Close() - spec, err := openapi.NewFromReader(f) - if err != nil { - return nil, fmt.Errorf("spec from %s: %w", name, err) - } - return NewFromSpec(ctx, spec) -} - -// NewFromSpec converts OpenAPI spec to intermediate representation -func NewFromSpec(ctx context.Context, spec *openapi.Specification) (*Batch, error) { - batch := Batch{ - packages: map[string]*Package{}, - } - for _, tag := range spec.Tags { - pkg, ok := batch.packages[tag.Package] - if !ok { - pkg = &Package{ - Named: Named{tag.Package, ""}, - Components: spec.Components, - services: map[string]*Service{}, - types: map[string]*Entity{}, - } - batch.packages[tag.Package] = pkg - } - err := pkg.Load(ctx, spec, tag) - if err != nil { - return nil, fmt.Errorf("fail to load %s: %w", tag.Name, err) - } - } - // add some packages at least some description - for _, pkg := range batch.packages { - if len(pkg.services) > 1 { - continue - } - // we know that we have just one service - for _, svc := range pkg.services { - pkg.Description = svc.Summary() - } - } - return &batch, nil -} - -func (b *Batch) FullName() string { - return "all" -} - -// Packages returns sorted slice of packages -func (b *Batch) Packages() (pkgs []*Package) { - for _, pkg := range b.packages { - pkgs = append(pkgs, pkg) - } - // add some determinism into code generation for globally stable order in - // files like for workspaces/accounts clinets. - fullNameSort(pkgs) - return pkgs -} - -// Pkgs returns sorted slice of packages -func (b *Batch) Types() (types []*Entity) { - for _, pkg := range b.packages { - types = append(types, pkg.Types()...) - } - // add some determinism into code generation for globally stable order in - // files like api.go and/or {{.Package.Name}}.py and clients. - fullNameSort(types) - return types -} - -// Pkgs returns sorted slice of packages -func (b *Batch) Services() (services []*Service) { - for _, pkg := range b.packages { - services = append(services, pkg.Services()...) - } - // we'll have more and more account level equivalents of APIs that are - // currently workspace-level. In the AccountsClient we're striping - // the `Account` prefix, so that naming and ordering is more logical. - // this requires us to do the proper sorting of services. E.g. - // - // - Groups: scim.NewAccountGroups(apiClient), - // - ServicePrincipals: scim.NewAccountServicePrincipals(apiClient), - // - Users: scim.NewAccountUsers(apiClient), - // - // more services may follow this pattern in the future. - norm := func(name string) string { - if !strings.HasPrefix(name, "Account") { - return name - } - // sorting-only rename: AccountGroups -> GroupsAccount - return name[7:] + "Account" - } - // add some determinism into code generation for globally stable order in - // files like api.go and/or {{.Package.Name}}.py and clients. - sort.Slice(services, func(a, b int) bool { - // not using .FullName() here, as in "batch" context - // services have to be sorted globally, not only within a package. - // alternatively we may think on adding .ReverseFullName() to sort on. - return norm(services[a].Name) < norm(services[b].Name) - }) - return services -} - -func (b *Batch) ServicesSortedByParent() (services []*Service) { - for _, pkg := range b.packages { - services = append(services, pkg.ServicesSortedByParent()...) - } - return services -} diff --git a/openapi/code/load_test.go b/openapi/code/load_test.go deleted file mode 100644 index ce2bb62b9..000000000 --- a/openapi/code/load_test.go +++ /dev/null @@ -1,152 +0,0 @@ -package code - -import ( - "context" - "fmt" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestNested(t *testing.T) { - ctx := context.Background() - batch, err := NewFromFile(ctx, "../testdata/spec_subservices.json") - require.NoError(t, err) - require.Contains(t, batch.packages["settings"].services, "Settings") - require.Contains(t, batch.packages["settings"].services["Settings"].subservices, "DefaultNamespace") - require.Equal(t, batch.packages["settings"].services["DefaultNamespace"].ParentService.Name, "Settings") - require.Equal(t, batch.packages["settings"].services["DefaultNamespace"].methods["cancel"].Response.fields["last-modified"].Entity.Terraform.Alias, "new_name") -} - -func TestBasic(t *testing.T) { - ctx := context.Background() - batch, err := NewFromFile(ctx, "../testdata/spec.json") - require.NoError(t, err) - - require.Len(t, batch.Packages(), 1) - require.Len(t, batch.Services(), 1) - require.Len(t, batch.Types(), 19) - commands, ok := batch.packages["commands"] - require.True(t, ok) - - assert.Equal(t, "commands", commands.FullName()) - - ce, ok := commands.services["CommandExecution"] - require.True(t, ok) - assert.Equal(t, "commands.CommandExecution", ce.FullName()) - assert.Equal(t, "commandExecution", ce.CamelName()) - assert.Equal(t, "CommandExecution", ce.PascalName()) - assert.Equal(t, commands, ce.Package) - - methods := ce.Methods() - assert.Equal(t, 7, len(methods)) - - execute := methods[5] - assert.Equal(t, "execute", execute.Name) - assert.Equal(t, "Execute", execute.PascalName()) - assert.Equal(t, "Post", execute.TitleVerb()) - assert.Nil(t, execute.Shortcut()) - - wait := execute.Wait() - require.NotNil(t, wait) - binding := wait.Binding() - assert.Equal(t, 3, len(binding)) - - assert.Equal(t, "finished", wait.Success()[0].CamelName()) - assert.Equal(t, "CommandStatus", wait.Failure()[0].Entity.PascalName()) - assert.Equal(t, 0, len(wait.MessagePath())) - - types := commands.Types() - assert.Equal(t, 19, len(types)) - - command := types[2] - assert.Equal(t, "Command", command.PascalName()) - assert.Equal(t, "command", command.CamelName()) - assert.Equal(t, "commands.Command", command.FullName()) - assert.Equal(t, 4, len(command.Fields())) - - assert.Nil(t, command.Field("nothing")) - - language := command.Field("language") - assert.NotNil(t, language) - assert.False(t, language.IsOptionalObject()) - assert.Equal(t, 3, len(language.Entity.Enum())) - - cancel := methods[0] - cancelResponse := cancel.Response - assert.Equal(t, "cancel", cancel.Name) - assert.Equal(t, "cancelResponse", cancelResponse.Name) - assert.Equal(t, 2, len(cancelResponse.fields)) - assert.Equal(t, "content-type", cancelResponse.fields["content-type"].Name) - assert.Equal(t, "last-modified", cancelResponse.fields["last-modified"].Name) -} - -// This test is used for debugging purposes -func TestMethodsReport(t *testing.T) { - t.SkipNow() - ctx := context.Background() - home, _ := os.UserHomeDir() - batch, err := NewFromFile(ctx, filepath.Join(home, - "universe/bazel-bin/openapi/all-internal.json")) - assert.NoError(t, err) - - for _, pkg := range batch.Packages() { - for _, svc := range pkg.Services() { - singleService := strings.EqualFold(pkg.PascalName(), svc.PascalName()) - serviceSingularKebab := svc.Singular().KebabName() - for _, m := range svc.Methods() { - var fields []string - if m.Request != nil { - for _, f := range m.Request.Fields() { - flag := fmt.Sprintf("--%s", f.KebabName()) - if f.Entity.IsObject() || f.Entity.MapValue != nil { - flag = fmt.Sprintf("%%%s", flag) - } - fields = append(fields, flag) - } - } - methodWithoutService := (&Named{ - Name: strings.ReplaceAll( - strings.ReplaceAll( - m.KebabName(), svc.KebabName(), ""), - serviceSingularKebab, ""), - }).KebabName() - println(fmt.Sprintf("| %s | %s | %s | %s | %v | %s | %s |", - pkg.KebabName(), - svc.KebabName(), - m.KebabName(), - methodWithoutService, - singleService, - m.Operation.Crud, - strings.Join(fields, ", "), - )) - } - } - } - - assert.Equal(t, len(batch.packages), 1) -} - -func TestDataPlane(t *testing.T) { - ctx := context.Background() - batch, err := NewFromFile(ctx, "../testdata/spec_dataplane.json") - require.NoError(t, err) - dataPlane := batch.packages["model"].services["Model"].methods["query"].DataPlane - require.Equal(t, "get", dataPlane.ConfigMethod) - require.Equal(t, "dataplaneInfo", dataPlane.Fields[0]) -} - -func TestJobs2Dot2Compatability(t *testing.T) { - ctx := context.Background() - batch, err := NewFromFile(ctx, "../testdata/spec_jobs_2.2.json") - require.NoError(t, err) - jobs := batch.packages["jobs"] - require.NotNil(t, jobs) - require.NotNil(t, jobs.services["Jobs"]) - require.Equal(t, "/api/2.1/jobs/get", jobs.services["Jobs"].methods["get"].Path) - require.Equal(t, "/api/2.2/jobs/runs/submit", jobs.services["Jobs"].methods["submitRun"].Path) -} diff --git a/openapi/code/method.go b/openapi/code/method.go deleted file mode 100644 index df759724d..000000000 --- a/openapi/code/method.go +++ /dev/null @@ -1,505 +0,0 @@ -package code - -import ( - "fmt" - "regexp" - "strings" - - "github.com/databricks/databricks-sdk-go/openapi" -) - -// Method represents service RPC -type Method struct { - Named - Service *Service - // HTTP method name - Verb string - // Full API Path, including /api/2.x prefix - Path string - // Slice of path params, e.g. permissions/{type}/{id} - PathParts []PathPart - // Request type representation - Request *Entity - // Response type representation - Response *Entity - - // The style of the request, either "rpc" or "rest". See the documentation on - // Operation for more details. - PathStyle openapi.PathStyle - - // For list APIs, the path of fields in the response entity to follow to get - // the resource ID. - IdFieldPath []*Field - - // For list APIs, the path of fields in the response entity to follow to get - // the user-friendly name of the resource. - NameFieldPath []*Field - - // If not nil, the field in the request and reponse entities that should be - // mapped to the request/response body. - RequestBodyField *Field - ResponseBodyField *Field - - // Expected content type of the request and response - FixedRequestHeaders map[string]string - - wait *openapi.Wait - pagination *openapi.Pagination - Operation *openapi.Operation - DataPlane *openapi.DataPlane - shortcut bool -} - -// DataPlaneInfoFields returns the fields which contains the DataPlane info. Each field is nested in the previous one. -func (m *Method) DataPlaneInfoFields() []*Field { - if m.DataPlane == nil { - return nil - } - method := m.Service.DataPlaneInfoMethod() - fieldNames := m.DataPlane.Fields - currentLevelFields := method.Response.fields - fields := []*Field{} - for _, name := range fieldNames { - field := currentLevelFields[name] - fields = append(fields, field) - currentLevelFields = field.Entity.fields - } - return fields -} - -// Shortcut holds definition of "shortcut" methods, that are generated for -// methods with request entities only with required fields. -type Shortcut struct { - Named - Params []Field - Method *Method -} - -// Pagination holds definition of result iteration type per specific RPC. -// Databricks as of now has a couple different types of pagination: -// - next_token/next_page_token + repeated field -// - offset/limit with zero-based offsets + repeated field -// - page/limit with 1-based pages + repeated field -// - repeated inline field -// - repeated field -type Pagination struct { - Offset *Field - Limit *Field - Results *Field - Entity *Entity - Token *Binding - Increment int -} - -// NamedIdMap depends on Pagination and is generated, when paginated item -// entity has Identifier and Name fields. End-users usually use this method for -// drop-downs or any other selectors. -type NamedIdMap struct { - Named - IdPath []*Field - NamePath []*Field - Entity *Entity - - // if List method returns []Item directly - // without generated iteration wrapper - Direct bool -} - -// PathPart represents required field, that is always part of the path -type PathPart struct { - Prefix string - Field *Field - IsAccountId bool -} - -var pathPairRE = regexp.MustCompile(`(?m)([^\{]+)(\{(\w+)\})?`) - -func (m *Method) pathParams() (params []Field) { - if len(m.PathParts) == 0 { - return nil - } - if !(m.Verb == "GET" || m.Verb == "DELETE" || m.Verb == "HEAD") { - return nil - } - for _, part := range m.PathParts { - if part.Field == nil { - continue - } - params = append(params, *part.Field) - } - return params -} - -func (m *Method) ResponseHeaders() (headers []Field) { - if m.Response == nil { - return headers - } - for _, field := range m.Response.Fields() { - if field.IsHeader { - headers = append(headers, *field) - } - } - return headers -} - -func (m *Method) allowShortcut() bool { - if m.shortcut { - return true - } - if m.PathStyle == openapi.PathStyleRpc { - return true - } - return false -} - -func (m *Method) rpcSingleFields() (params []Field) { - if !m.allowShortcut() { - return nil - } - if m.Request == nil { - return nil - } - if len(m.Request.fields) != 1 { - // TODO: explicitly annotate with x-databricks-shortcut - return nil - } - return []Field{*m.Request.Fields()[0]} -} - -func (m *Method) requestShortcutFields() []Field { - pathParams := m.pathParams() - rpcFields := m.rpcSingleFields() - if len(pathParams) == 0 && len(rpcFields) == 0 { - return nil - } - if len(pathParams) > 0 { - return pathParams - } - return rpcFields -} - -// Shortcut creates definition from path params and single-field request entities -func (m *Method) Shortcut() *Shortcut { - params := m.requestShortcutFields() - if len(params) == 0 { - return nil - } - nameParts := []string{} - for _, part := range params { - nameParts = append(nameParts, part.PascalName()) - } - name := fmt.Sprintf("%sBy%s", m.PascalName(), strings.Join(nameParts, "And")) - return &Shortcut{ - Named: Named{name, ""}, - Method: m, - Params: params, - } -} - -func (m *Method) IsCrudRead() bool { - return m.Operation.Crud == "read" -} - -func (m *Method) IsCrudCreate() bool { - return m.Operation.Crud == "create" -} - -func (m *Method) IsJsonOnly() bool { - return m.Operation.JsonOnly -} - -// MustUseJson indicates whether we have to use -// JSON input to set all required fields for request. -// If we can do so, it means we can only use JSON input passed via --json flag. -func (m *Method) MustUseJson() bool { - // method supports only JSON input - if m.IsJsonOnly() { - return true - } - - // if not all required fields are primitive, then fields must be provided in JSON - if m.Request != nil && !m.Request.IsAllRequiredFieldsPrimitive() { - return true - } - - // if request is a map, then we have to use JSON input - if m.Request != nil && m.Request.IsMap() { - return true - } - - return false -} - -// CanUseJson indicates whether the generated command supports --json flag. -// It happens when either method has to use JSON input or not all fields in request -// are primitives. Because such fields are not required, the command has not but -// should support JSON input. -func (m *Method) CanUseJson() bool { - return m.MustUseJson() || (m.Request != nil && m.Request.HasJsonField()) -} - -func (m *Method) HasRequiredPositionalArguments() bool { - if m.Request == nil { - return false - } - - e := m.Request - return e.HasRequiredPathFields() || (!m.MustUseJson() && e.IsAllRequiredFieldsPrimitive()) -} - -func (m *Method) RequiredPositionalArguments() (fields []*Field) { - if m.Request == nil { - return nil - } - - e := m.Request - // Path fields are always required as positional arguments - posArgs := e.RequiredPathFields() - if !m.MustUseJson() && e.IsAllRequiredFieldsPrimitive() { - for _, f := range e.RequiredFields() { - if f.IsPath { - continue - } - posArgs = append(posArgs, f) - } - } - return posArgs -} - -func (m *Method) HasIdentifierField() bool { - return len(m.IdFieldPath) > 0 -} - -func (m *Method) IdentifierField() *Field { - if !m.HasIdentifierField() { - return nil - } - return m.IdFieldPath[len(m.IdFieldPath)-1] -} - -func (m *Method) HasNameField() bool { - return len(m.NameFieldPath) > 0 -} - -// Wait returns definition for long-running operation -func (m *Method) Wait() *Wait { - if m.wait == nil { - return nil - } - // here it's easier to follow the snake_case, as success states are already - // in the CONSTANT_CASE and it's easier to convert from constant to snake, - // than from constant to camel or pascal. - name := m.Service.Singular().SnakeName() - success := strings.ToLower(strings.Join(m.wait.Success, "_or_")) - getStatus, ok := m.Service.methods[m.wait.Poll] - if !ok { - panic(fmt.Errorf("cannot find %s.%s", m.Service.Name, m.wait.Poll)) - } - name = fmt.Sprintf("wait_%s_%s_%s", getStatus.SnakeName(), name, success) - return &Wait{ - Named: Named{ - Name: name, - }, - Method: m, - } -} - -// Pagination returns definition for possibly multi-request result iterator -func (m *Method) Pagination() *Pagination { - if m.pagination == nil { - return nil - } - if m.Response.ArrayValue != nil { - // we assume that method already returns body-as-array - return nil - } - var token *Binding - if m.pagination.Token != nil { - token = &Binding{ // reuse the same datastructure as for waiters - PollField: m.Request.Field(m.pagination.Token.Request), - Bind: m.Response.Field(m.pagination.Token.Response), - } - } - offset := m.Request.Field(m.pagination.Offset) - limit := m.Request.Field(m.pagination.Limit) - results := m.Response.Field(m.pagination.Results) - if results == nil { - panic(fmt.Errorf("invalid results field '%v': %s", - m.pagination.Results, m.Operation.OperationId)) - } - entity := results.Entity.ArrayValue - increment := m.pagination.Increment - return &Pagination{ - Results: results, - Token: token, - Entity: entity, - Offset: offset, - Limit: limit, - Increment: increment, - } -} - -func (m *Method) paginationItem() *Entity { - if m.pagination == nil { - return nil - } - if m.Response.ArrayValue != nil { - // we assume that method already returns body-as-array - return m.Response.ArrayValue - } - p := m.Pagination() - return p.Entity -} - -func (m *Method) NeedsOffsetDedupe() bool { - p := m.Pagination() - return p.Offset != nil && m.HasIdentifierField() -} - -func (p *Pagination) MultiRequest() bool { - return p.Offset != nil || p.Token != nil -} - -// NamedIdMap returns name-to-id mapping retrieval definition for all -// entities of a type -func (m *Method) NamedIdMap() *NamedIdMap { - entity := m.paginationItem() - if entity == nil || !m.HasIdentifierField() || !m.HasNameField() { - return nil - } - namePath := m.NameFieldPath - nameParts := []string{entity.PascalName()} - for _, v := range namePath { - nameParts = append(nameParts, v.PascalName()) - } - nameParts = append(nameParts, "To") - nameParts = append(nameParts, m.IdentifierField().PascalName()) - nameParts = append(nameParts, "Map") - return &NamedIdMap{ - Named: Named{ - Name: strings.Join(nameParts, ""), - }, - IdPath: m.IdFieldPath, - NamePath: namePath, - Entity: entity, - Direct: m.Response.ArrayValue != nil, - } -} - -func (n *NamedIdMap) Id() *Field { - return n.IdPath[len(n.IdPath)-1] -} - -// GetByName returns entity from the same service with x-databricks-crud:read -func (m *Method) GetByName() *Entity { - n := m.NamedIdMap() - if n == nil { - return nil - } - potentialName := "GetBy" - for _, v := range n.NamePath { - potentialName += v.PascalName() - } - for _, other := range m.Service.methods { - shortcut := other.Shortcut() - if shortcut == nil { - continue - } - if shortcut.PascalName() == potentialName { - // we already have the shortcut - return nil - } - } - return n.Entity -} - -func (m *Method) CanHaveResponseBody() bool { - return m.TitleVerb() == "Get" || m.TitleVerb() == "Post" -} - -func (m *Method) TitleVerb() string { - return strings.Title(strings.ToLower(m.Verb)) -} - -// IsPrivatePreview flags object being in private preview. -func (m *Method) IsPrivatePreview() bool { - return isPrivatePreview(&m.Operation.Node) -} - -// IsPublicPreview flags object being in public preview. -func (m *Method) IsPublicPreview() bool { - return isPublicPreview(&m.Operation.Node) -} - -func (m *Method) AsFlat() *Named { - if m.PascalName() == "CreateOboToken" { - return &m.Named - } - methodWords := m.Named.splitASCII() - svc := m.Service.Named - - remap := map[string]string{ - "ModelRegistry": "Models", - "Libraries": "ClusterLibraries", - "PolicyFamilies": "ClusterPolicyFamilies", - "Workspace": "Notebooks", // or WorkspaceObjects - "OAuthEnrollment": "OauthEnrollment", - "CurrentUser": "", - } - if replace, ok := remap[svc.PascalName()]; ok { - svc = Named{ - Name: replace, - } - } - - serviceWords := svc.splitASCII() - serviceSingularWords := svc.Singular().splitASCII() - - words := []string{} - if len(methodWords) == 1 && strings.ToLower(methodWords[0]) == "list" { - words = append(words, "list") - words = append(words, serviceWords...) - } else if methodWords[0] == "execute" { - words = append(words, methodWords[0]) - // command_execution.execute -> execute-command-execution - words = append(words, serviceWords[0]) - } else { - words = append(words, methodWords[0]) - words = append(words, serviceSingularWords...) - } - words = append(words, methodWords[1:]...) - // warehouses.get_workspace_warehouse_config -> get-warehouse-workspace-config - seen := map[string]bool{} - tmp := []string{} - for _, w := range words { - if seen[w] { - continue - } - tmp = append(tmp, w) - seen[w] = true - } - - return &Named{ - Name: strings.Join(tmp, "_"), - } -} - -func (m *Method) CmdletName(prefix string) string { - words := m.AsFlat().splitASCII() - noun := &Named{ - Name: strings.Join(words[1:], "_"), - } - verb := strings.Title(words[0]) - prefix = strings.Title(prefix) - return fmt.Sprintf("%s-%s%s", verb, prefix, noun.PascalName()) -} - -func (m *Method) IsRequestByteStream() bool { - contentType, ok := m.FixedRequestHeaders["Content-Type"] - return m.Request != nil && ok && contentType != string(openapi.MimeTypeJson) -} - -func (m *Method) IsResponseByteStream() bool { - accept, ok := m.FixedRequestHeaders["Accept"] - return m.Response != nil && ok && accept != string(openapi.MimeTypeJson) -} diff --git a/openapi/code/method_test.go b/openapi/code/method_test.go deleted file mode 100644 index b04e0bd71..000000000 --- a/openapi/code/method_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package code - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestFlatNames(t *testing.T) { - for _, v := range []struct { - service, method, flat string - }{ - {"secrets", "delete_acl", "delete_secret_acl"}, - {"secrets", "list_scopes", "list_secret_scopes"}, - {"workspace_conf", "get_status", "get_workspace_conf_status"}, - {"statement_execution", "execute_statement", "execute_statement"}, - {"statement_execution", "get_statement_result_chunk_n", "get_statement_execution_result_chunk_n"}, - - // TBD: - {"current_user", "me", "me"}, - {"warehouses", "get_workspace_warehouse_config", "get_warehouse_workspace_config"}, - {"libraries", "install", "install_cluster_library"}, - {"policy_families", "get", "get_cluster_policy_family"}, - {"workspace", "get_status", "get_notebook_status"}, - {"model_registry", "create_comment", "create_model_comment"}, - {"token_management", "create_obo_token", "create_obo_token"}, - } { - m := &Method{ - Named: Named{ - Name: v.method, - }, - Service: &Service{ - Named: Named{ - Name: v.service, - }, - }, - } - assert.Equal(t, v.flat, m.AsFlat().SnakeName()) - } -} - -func TestCmdletNames(t *testing.T) { - for _, v := range []struct { - service, method, cmdlet string - }{ - {"secrets", "delete_acl", "Delete-DatabricksSecretAcl"}, - {"secrets", "list_scopes", "List-DatabricksSecretScopes"}, - {"workspace_conf", "get_status", "Get-DatabricksWorkspaceConfStatus"}, - - // TBD: - {"current_user", "me", "Me-Databricks"}, - {"warehouses", "get_workspace_warehouse_config", "Get-DatabricksWarehouseWorkspaceConfig"}, - {"libraries", "install", "Install-DatabricksClusterLibrary"}, - {"policy_families", "get", "Get-DatabricksClusterPolicyFamily"}, - {"workspace", "get_status", "Get-DatabricksNotebookStatus"}, - {"model_registry", "create_comment", "Create-DatabricksModelComment"}, - {"token_management", "create_obo_token", "Create-DatabricksOboToken"}, - } { - m := &Method{ - Named: Named{ - Name: v.method, - }, - Service: &Service{ - Named: Named{ - Name: v.service, - }, - }, - } - assert.Equal(t, v.cmdlet, m.CmdletName("Databricks")) - } -} diff --git a/openapi/code/named.go b/openapi/code/named.go deleted file mode 100644 index 53360a5f9..000000000 --- a/openapi/code/named.go +++ /dev/null @@ -1,347 +0,0 @@ -package code - -import ( - "fmt" - "regexp" - "sort" - "strings" - "unicode" -) - -var reservedWords = []string{ - "break", "default", "func", "interface", "select", "case", "defer", "go", - "map", "struct", "chan", "else", "goto", "switch", "const", "fallthrough", - "if", "range", "type", "continue", "for", "import", "return", "var", - "append", "bool", "byte", "iota", "len", "make", "new", "package", -} - -// Named holds common methods for identifying and describing things -type Named struct { - Name string - Description string -} - -func (n *Named) IsNameReserved() bool { - for _, v := range reservedWords { - if n.CamelName() == v { - return true - } - } - return false -} - -func (n *Named) isNamePlural() bool { - if n.Name == "" { - return false - } - return n.Name[len(n.Name)-1] == 's' -} - -// simplified ruleset for singularizing multiples -var singularizers = []*regexTransform{ - // branches -> branch - newRegexTransform("(s|ss|sh|ch|x|z)es$", "$1"), - - // policies -> policy - newRegexTransform("([bcdfghjklmnpqrstvwxz])ies$", "${1}y"), - - // permissions -> permission - newRegexTransform("([a-z])s$", "$1"), -} - -var singularExceptions = map[string]string{ - "dbfs": "dbfs", - "warehouses": "warehouse", - "databricks": "databricks", -} - -type regexTransform struct { - Search *regexp.Regexp - Replace string -} - -func newRegexTransform(search, replace string) *regexTransform { - return ®exTransform{ - Search: regexp.MustCompile(search), - Replace: replace, - } -} - -func (t *regexTransform) Transform(src string) string { - return t.Search.ReplaceAllString(src, t.Replace) -} - -func (n *Named) Singular() *Named { - if !n.isNamePlural() { - return n - } - exception, ok := singularExceptions[strings.ToLower(n.Name)] - if ok { - return &Named{ - Name: exception, - Description: n.Description, - } - } - for _, t := range singularizers { - after := t.Transform(n.Name) - if after == n.Name { - continue - } - return &Named{ - Name: after, - Description: n.Description, - } - } - return n -} - -// Return the value of cond evaluated at the nearest letter to index i in name. -// dir determines the direction of search: if true, search forwards, if false, -// search backwards. -func (n *Named) search(name string, cond func(rune) bool, dir bool, i int) bool { - nameLen := len(name) - incr := 1 - if !dir { - incr = -1 - } - for j := i; j >= 0 && j < nameLen; j += incr { - if unicode.IsLetter(rune(name[j])) { - return cond(rune(name[j])) - } - } - return false -} - -// Return the value of cond evaluated on the rune at index i in name. If that -// rune is not a letter, search in both directions for the nearest letter and -// return the result of cond on those letters. -func (n *Named) checkCondAtNearestLetters(name string, cond func(rune) bool, i int) bool { - r := rune(name[i]) - - if unicode.IsLetter(r) { - return cond(r) - } - return n.search(name, cond, true, i) && n.search(name, cond, false, i) -} - -// emulate positive lookaheads from JVM regex: -// (?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|([-_\s]) -// and convert all words to lower case - -func (n *Named) splitASCII() (w []string) { - var current []rune - var name = n.Name - nameLen := len(name) - var isPrevUpper, isCurrentUpper, isNextLower, isNextUpper, isNotLastChar bool - // we do assume here that all named entities are strictly ASCII - for i := 0; i < nameLen; i++ { - r := rune(name[i]) - if r == '$' { - // we're naming language literals, $ is usually not allowed - continue - } - // if the current rune is a digit, check the neighboring runes to - // determine whether to treat this one as upper-case. - isCurrentUpper = n.checkCondAtNearestLetters(name, unicode.IsUpper, i) - r = unicode.ToLower(r) - isNextLower = false - isNextUpper = false - isNotLastChar = i+1 < nameLen - if isNotLastChar { - isNextLower = n.checkCondAtNearestLetters(name, unicode.IsLower, i+1) - isNextUpper = n.checkCondAtNearestLetters(name, unicode.IsUpper, i+1) - } - split, before, after := false, false, true - // At the end of a string of capital letters (e.g. HTML[P]arser). - if isPrevUpper && isCurrentUpper && isNextLower && isNotLastChar { - // (?<=[A-Z])(?=[A-Z][a-z]) - split = true - before = false - after = true - } - // At the end of a camel- or pascal-case word (e.g. htm[l]Parser). - if !isCurrentUpper && isNextUpper { - // (?<=[a-z])(?=[A-Z]) - split = true - before = true - after = false - } - if !unicode.IsLetter(r) && !unicode.IsNumber(r) { - // ([-_\s]) - split = true - before = false - after = false - } - if before { - current = append(current, r) - } - if split && len(current) > 0 { - w = append(w, string(current)) - current = []rune{} - } - if after { - current = append(current, r) - } - isPrevUpper = isCurrentUpper - } - if len(current) > 0 { - w = append(w, string(current)) - } - return w -} - -// PascalName creates NamesLikesThis -func (n *Named) PascalName() string { - var sb strings.Builder - for _, w := range n.splitASCII() { - sb.WriteString(strings.Title(w)) - } - return sb.String() -} - -// TitleName creates Names Likes This -func (n *Named) TitleName() string { - return strings.Title(strings.Join(n.splitASCII(), " ")) -} - -// CamelName creates namesLikesThis -func (n *Named) CamelName() string { - if n.Name == "_" { - return "_" - } - cc := n.PascalName() - return strings.ToLower(cc[0:1]) + cc[1:] -} - -// SnakeName creates names_like_this -func (n *Named) SnakeName() string { - if n.Name == "_" { - return "_" - } - return strings.Join(n.splitASCII(), "_") -} - -// ConstantName creates NAMES_LIKE_THIS -func (n *Named) ConstantName() string { - return strings.ToUpper(n.SnakeName()) -} - -// KebabName creates names-like-this -func (n *Named) KebabName() string { - return strings.Join(n.splitASCII(), "-") -} - -// AbbrName returns `nlt` for `namesLikeThis` -func (n *Named) AbbrName() string { - var abbr []byte - for _, v := range n.splitASCII() { - abbr = append(abbr, v[0]) - } - return string(abbr) -} - -// TrimPrefix returns *Named, but with a prefix trimmed from CamelName() -// -// Example: -// -// (&Named{Name: "AccountMetastoreAssigment"}).TrimPrefix("account").CamelName() == "metastoreAssignment" -func (n *Named) TrimPrefix(prefix string) *Named { - return &Named{ - Name: strings.TrimPrefix(n.CamelName(), prefix), - Description: n.Description, - } -} - -func (n *Named) HasComment() bool { - return n.Description != "" -} - -func (n *Named) sentences() []string { - if n.Description == "" { - return []string{} - } - norm := whitespace.ReplaceAllString(n.Description, " ") - trimmed := strings.TrimSpace(norm) - return strings.Split(trimmed, ". ") -} - -// Summary gets the first sentence from the description. Always ends in a dot. -func (n *Named) Summary() string { - sentences := n.sentences() - if len(sentences) > 0 { - return strings.TrimSuffix(sentences[0], ".") + "." - } - return "" -} - -// match markdown links, ignoring new lines -var markdownLink = regexp.MustCompile(`\[([^\]]+)\]\(([^\)]+)\)`) - -func (n *Named) DescriptionWithoutSummary() string { - sentences := n.sentences() - if len(sentences) > 1 { - return strings.Join(sentences[1:], ". ") - } - return "" -} - -// Comment formats description into language-specific comment multi-line strings -func (n *Named) Comment(prefix string, maxLen int) string { - if n.Description == "" { - return "" - } - trimmed := strings.TrimSpace(n.Description) - // collect links, which later be sorted - links := map[string]string{} - // safe to iterate and update, as match slice is a snapshot - for _, m := range markdownLink.FindAllStringSubmatch(trimmed, -1) { - label := strings.TrimSpace(m[1]) - link := strings.TrimSpace(m[2]) - if !strings.HasPrefix(link, "http") { - // this condition is here until OpenAPI spec normalizes all links - continue - } - // simplify logic by overriding links in case of duplicates. - // this will also lead us to alphabetically sort links in the bottom, - // instead of always following the order they appear in the comment. - // luckily, this doesn't happen often. - links[label] = link - // replace [test](url) with [text] - trimmed = strings.ReplaceAll(trimmed, m[0], fmt.Sprintf("[%s]", label)) - } - linksInBottom := []string{} - for k, v := range links { - link := fmt.Sprintf("[%s]: %s", k, v) - linksInBottom = append(linksInBottom, link) - } - sort.Strings(linksInBottom) - // fix new-line characters - trimmed = strings.ReplaceAll(trimmed, "\\n", "\n") - description := strings.ReplaceAll(trimmed, "\n\n", " __BLANK__ ") - var lines []string - currentLine := strings.Builder{} - for _, v := range whitespace.Split(description, -1) { - if v == "__BLANK__" { - lines = append(lines, currentLine.String()) - lines = append(lines, "") - currentLine.Reset() - continue - } - if len(prefix)+currentLine.Len()+len(v)+1 > maxLen { - lines = append(lines, currentLine.String()) - currentLine.Reset() - } - if currentLine.Len() > 0 { - currentLine.WriteRune(' ') - } - currentLine.WriteString(v) - } - if currentLine.Len() > 0 { - lines = append(lines, currentLine.String()) - currentLine.Reset() - } - if len(linksInBottom) > 0 { - lines = append(append(lines, ""), linksInBottom...) - } - return strings.TrimLeft(prefix, "\t ") + strings.Join(lines, "\n"+prefix) -} diff --git a/openapi/code/named_sort.go b/openapi/code/named_sort.go deleted file mode 100644 index 2682cf6b8..000000000 --- a/openapi/code/named_sort.go +++ /dev/null @@ -1,25 +0,0 @@ -package code - -import "sort" - -// github.com/databricks/databricks-sdk-go/httpclient/fixtures stub generator uses Named.PascalName() method to come up with -// the best possible field name for generated copy-pastable stubs, though, when this library is attempted to be used together -// with github.com/spf13/viper, we immediately get the following error related to a change in -// golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e as: -// .../entity.go:185:32: type func(a *Field, b *Field) bool of func(a, b *Field) bool {…} does not match inferred type -// ... func(a *Field, b *Field) int for func(a E, b E) int, -// because github.com/spf13/viper v0.17+ transitively depends on golang.org/x/exp v0.0.0-20230905200255-921286631fa9 - -// sorts slice predictably by NamesLikeThis -func pascalNameSort[E interface{ PascalName() string }](things []E) { - sort.Slice(things, func(i, j int) bool { - return things[i].PascalName() < things[j].PascalName() - }) -} - -// sorts slice predictably by package_names_and.ClassNamesLikeThis -func fullNameSort[E interface{ FullName() string }](things []E) { - sort.Slice(things, func(i, j int) bool { - return things[i].FullName() < things[j].FullName() - }) -} diff --git a/openapi/code/named_test.go b/openapi/code/named_test.go deleted file mode 100644 index 8716fa0e0..000000000 --- a/openapi/code/named_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package code - -import ( - "strings" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestCommentFromDescription(t *testing.T) { - n := Named{Description: `A data lakehouse unifies the best of data - warehouses and data lakes in one simple platform to handle all your - data, analytics and AI use cases.\nIt's built on an open and reliable - data foundation that efficiently handles all data types and applies - one common security and governance approach across all of your data - and cloud platforms.`} - assert.Equal(t, strings.TrimLeft(` - // A data lakehouse unifies the best of data warehouses and data lakes in - // one simple platform to handle all your data, analytics and AI use cases. - // It's built on an open and reliable data foundation that efficiently - // handles all data types and applies one common security and governance - // approach across all of your data and cloud platforms.`, - "\n\t "), n.Comment(" // ", 80)) -} - -func TestCommentFromDescriptionWithSummaryAndBlankLines(t *testing.T) { - n := Named{Description: strings.Join([]string{ - "Databricks Lakehouse", - "", - `A data lakehouse unifies the best of data warehouses and data lakes - in one simple platform to handle all your data, analytics and AI use - cases.`, - "", - `It's built on an open and reliable data foundation that efficiently - handles all data types and applies one common security and governance - approach across all of your data and cloud platforms.`, - }, "\n")} - assert.Equal(t, strings.TrimLeft(` - // Databricks Lakehouse - // - // A data lakehouse unifies the best of data warehouses and data lakes in - // one simple platform to handle all your data, analytics and AI use cases. - // - // It's built on an open and reliable data foundation that efficiently - // handles all data types and applies one common security and governance - // approach across all of your data and cloud platforms.`, - "\n\t "), n.Comment(" // ", 80)) -} - -func TestSentencesFromDescription(t *testing.T) { - n := Named{Description: strings.Join([]string{ - "Databricks Lakehouse.", - "", - `A data lakehouse unifies the best of data warehouses and data lakes - in one simple platform to handle all your data, analytics and AI use - cases.`, - }, "\n")} - assert.Equal(t, "Databricks Lakehouse.", n.Summary()) - assert.Equal(t, "A data lakehouse unifies the best of data "+ - "warehouses and data lakes in one simple platform to "+ - "handle all your data, analytics and AI use cases.", - n.DescriptionWithoutSummary()) - - assert.Equal(t, "", (&Named{}).Summary()) - assert.Equal(t, "", (&Named{}).DescriptionWithoutSummary()) - assert.Equal(t, "Foo.", (&Named{Description: "Foo"}).Summary()) - assert.Equal(t, "", (&Named{Description: "Foo"}).DescriptionWithoutSummary()) -} - -func TestCommentWithLinks(t *testing.T) { - n := Named{Description: `This is an [example](https://example.com) of - linking to other web pages. Follows this - [convention](https://tip.golang.org/doc/comment#links).`} - assert.Equal(t, strings.TrimLeft(` - // This is an [example] of linking to other web pages. Follows this - // [convention]. - // - // [convention]: https://tip.golang.org/doc/comment#links - // [example]: https://example.com`, - "\n\t "), n.Comment(" // ", 80)) -} - -func TestNonConflictingCamelNames(t *testing.T) { - n := Named{Name: "Import"} - assert.True(t, n.IsNameReserved()) -} - -func TestNamedDecamel(t *testing.T) { - for in, out := range map[string][]string{ - "BigHTMLParser": {"big", "html", "parser"}, - "parseHTML": {"parse", "html"}, - "parse HTML": {"parse", "html"}, - "parse-HTML": {"parse", "html"}, - "parse--HTML": {"parse", "html"}, - "parse_HTML": {"parse", "html"}, - "parseHTMLNow": {"parse", "html", "now"}, - "parseHtml": {"parse", "html"}, - "ParseHtml": {"parse", "html"}, - "clusterID": {"cluster", "id"}, - "positionX": {"position", "x"}, - "parseHtmlNow": {"parse", "html", "now"}, - "HTMLParser": {"html", "parser"}, - "BigO": {"big", "o"}, - "OCaml": {"o", "caml"}, - "K8S_FAILURE": {"k8s", "failure"}, - "k8sFailure": {"k8s", "failure"}, - "i18nFailure": {"i18n", "failure"}, - "Patch:Request": {"patch", "request"}, - "urn:ietf:params:scim:api:messages:2.0:PatchOp": {"urn", "ietf", "params", "scim", "api", "messages", "2", "0", "patch", "op"}, - } { - assert.Equal(t, out, (&Named{Name: in}).splitASCII(), in) - } -} - -func TestNamedTransforms(t *testing.T) { - n := Named{Name: "bigBrownFOX"} - for actual, expected := range map[string]string{ - n.CamelName(): "bigBrownFox", - n.PascalName(): "BigBrownFox", - n.ConstantName(): "BIG_BROWN_FOX", - n.SnakeName(): "big_brown_fox", - n.KebabName(): "big-brown-fox", - n.TitleName(): "Big Brown Fox", - n.AbbrName(): "bbf", - } { - assert.Equal(t, expected, actual) - } -} - -func TestNamedSingular(t *testing.T) { - for in, out := range map[string]string{ - "buses": "bus", - "boxes": "box", - "branches": "branch", - "blitzes": "blitz", - "cluster-policies": "cluster-policy", - "clusters": "cluster", - "dbfs": "dbfs", - "alerts": "alert", - "dashboards": "dashboard", - "data-sources": "data-source", - "dbsql-permissions": "dbsql-permission", - "queries": "query", - "delta-pipelines": "delta-pipeline", - "repos": "repo", - "metastores": "metastore", - "tables": "table", - "workspace": "workspace", - "warehouses": "warehouse", - } { - n := &Named{Name: in} - assert.Equal(t, out, n.Singular().Name) - } -} diff --git a/openapi/code/package.go b/openapi/code/package.go deleted file mode 100644 index fb3dadc84..000000000 --- a/openapi/code/package.go +++ /dev/null @@ -1,460 +0,0 @@ -// Package holds higher-level abstractions on top of OpenAPI that are used -// to generate code via text/template for Databricks SDK in different languages. -package code - -import ( - "context" - "fmt" - "log" - "regexp" - "sort" - "strings" - - "github.com/databricks/databricks-sdk-go/logger" - "github.com/databricks/databricks-sdk-go/openapi" -) - -// Package represents a service package, which contains entities and interfaces -// that are relevant to a single service -type Package struct { - Named - Components *openapi.Components - services map[string]*Service - types map[string]*Entity - extImports map[string]*Entity -} - -// FullName just returns pacakge name -func (pkg *Package) FullName() string { - return pkg.CamelName() -} - -// Services returns sorted slice of services -func (pkg *Package) Services() (types []*Service) { - for _, v := range pkg.services { - types = append(types, v) - } - pascalNameSort(types) - return types -} - -func (pkg *Package) addRecursively(service *Service, result []*Service) []*Service { - result = append(result, service) - subservices := make([]*Service, 0, len(service.subservices)) - for _, v := range service.subservices { - subservices = append(subservices, v) - } - pascalNameSort(subservices) - for _, svc := range subservices { - result = pkg.addRecursively(svc, result) - } - return result -} - -// Returns the Services sorted such has parents always come before subservices. -func (pkg *Package) ServicesSortedByParent() []*Service { - allServices := pkg.Services() - resultServices := []*Service{} - for _, svc := range allServices { - if svc.ParentService != nil { - continue - } - resultServices = pkg.addRecursively(svc, resultServices) - } - - return resultServices -} - -// MainService returns a Service that matches Package name -func (pkg *Package) MainService() *Service { - for _, svc := range pkg.services { - if !svc.MatchesPackageName() { - continue - } - return svc - } - return nil -} - -// Types returns sorted slice of types -func (pkg *Package) Types() (types []*Entity) { - for _, v := range pkg.types { - types = append(types, v) - } - pascalNameSort(types) - return types -} - -// HasPagination returns try if any service within this package has result -// iteration -func (pkg *Package) HasPagination() bool { - for _, v := range pkg.services { - if v.HasPagination() { - return true - } - } - return false -} - -func (pkg *Package) ImportedEntities() (res []*Entity) { - for _, e := range pkg.extImports { - res = append(res, e) - } - fullNameSort(res) - return -} - -func (pkg *Package) ImportedPackages() (res []string) { - tmp := map[string]bool{} - for _, e := range pkg.extImports { - tmp[e.Package.Name] = true - } - for name := range tmp { - res = append(res, name) - } - sort.Strings(res) - return -} - -// schemaToEntity converts a schema into an Entity -// processedEntities keeps track of the entities that are being generated to avoid infinite recursion. -func (pkg *Package) schemaToEntity(s *openapi.Schema, path []string, hasName bool, processedEntities map[string]*Entity) *Entity { - if s.IsRef() { - return pkg.refEntity(s, processedEntities) - } - - e := &Entity{ - Named: Named{ - Description: s.Description, - }, - Schema: s, - Package: pkg, - enum: map[string]EnumEntry{}, - } - if s.JsonPath != "" { - processedEntities[s.JsonPath] = e - } - - // Some entities are declared anonymously as part of another entity (e.g. - // an object in an object). This is not a recommended pattern but we need - // to handle it. We do that by declaring the entity as if it was explicitly - // defined, using its path as name. - if (s.IsObject() || s.IsEnum()) && !hasName { - fieldType := "enum" - if s.IsObject() { - fieldType = "object" - } - name := strings.Join(path, "") - log.Printf("[WARN] Found anonymous %s %q. Please update your OpenAPI schema so that this entity is explicitly defined in components.", fieldType, name) - e.Named.Name = name - pkg.define(e) - } - - e.fields = map[string]*Field{} - e.IsAny = s.IsAny - e.IsComputed = s.IsComputed - e.RequiredOrder = s.Required - - if s.Terraform != nil { - e.Terraform = &Terraform{Alias: s.Terraform.Alias} - } - - switch { - case len(s.Enum) != 0: - return pkg.makeEnum(e, s, path) - case len(s.Properties) != 0: - return pkg.makeObject(e, s, path, processedEntities) - case s.ArrayValue != nil: - e.ArrayValue = pkg.schemaToEntity(s.ArrayValue, append(path, "Item"), false, processedEntities) - return e - case s.MapValue != nil: - e.MapValue = pkg.schemaToEntity(s.MapValue, path, hasName, processedEntities) - return e - default: - e.IsBool = s.Type == "boolean" || s.Type == "bool" - e.IsString = s.Type == "string" - e.IsInt64 = s.Type == "integer" && s.Format == "int64" - e.IsFloat64 = s.Type == "number" && s.Format == "double" - e.IsInt = s.Type == "integer" || s.Type == "int" - return e - } -} - -func (pkg *Package) refEntity(s *openapi.Schema, processedEntities map[string]*Entity) *Entity { - pair := strings.Split(s.Component(), ".") - if len(pair) == 2 && pair[0] != pkg.Name { - schemaPackage := pair[0] - schemaType := pair[1] - if pkg.extImports == nil { - pkg.extImports = map[string]*Entity{} - } - known, ok := pkg.extImports[s.Component()] - if ok { - return known - } - // referred entity is declared in another package - pkg.extImports[s.Component()] = &Entity{ - Named: Named{ - Name: schemaType, - }, - Package: &Package{ - Named: Named{ - Name: schemaPackage, - }, - }, - } - return pkg.extImports[s.Component()] - } - // if schema is src, load it to this package - src := pkg.Components.Schemas.Resolve(s) - if src == nil { - return nil - } - component := pkg.localComponent(&s.Node) - return pkg.definedEntity(component, *src, processedEntities) -} - -// makeObject converts OpenAPI Schema into type representation -// processedEntities keeps track of the entities that are being generated to avoid infinite recursion. -func (pkg *Package) makeObject(e *Entity, s *openapi.Schema, path []string, processedEntities map[string]*Entity) *Entity { - required := map[string]bool{} - for _, v := range s.Required { - required[v] = true - } - for k, v := range s.Properties { - if v.Description == "" && v.IsRef() { - vv := pkg.Components.Schemas.Resolve(v) - if vv != nil { - v.Description = (*vv).Description - } - } - named := Named{k, v.Description} - e.fields[k] = &Field{ - Named: named, - Entity: pkg.schemaToEntity(v, append(path, named.PascalName()), false, processedEntities), - Required: required[k], - Schema: v, - IsJson: true, - } - } - pkg.updateType(e) - return e -} - -var whitespace = regexp.MustCompile(`\s+`) - -func (pkg *Package) makeEnum(e *Entity, s *openapi.Schema, path []string) *Entity { - for idx, content := range s.Enum { - name := content - if len(s.AliasEnum) == len(s.Enum) { - name = s.AliasEnum[idx] - } - description := s.EnumDescriptions[content] - e.enum[content] = EnumEntry{ - Named: Named{name, description}, - Entity: e, - Content: content, - } - } - return e -} - -func (pkg *Package) localComponent(n *openapi.Node) string { - component := n.Component() - if strings.HasPrefix(component, pkg.Name+".") { - component = strings.ReplaceAll(component, pkg.Name+".", "") - } - return component -} - -// definedEntity defines and returns the requested entity based on the schema. -// processedEntities keeps track of the entities that are being generated to avoid infinite recursion. -func (pkg *Package) definedEntity(name string, s *openapi.Schema, processedEntities map[string]*Entity) *Entity { - if s == nil { - return pkg.define(&Entity{ - Named: Named{Name: name, Description: ""}, - fields: map[string]*Field{}, - }) - } - - // Return existing entity if it has already been generated. - if entity, ok := processedEntities[s.JsonPath]; ok { - return entity - } - - e := pkg.schemaToEntity(s, []string{name}, true, processedEntities) - if e == nil { // happens when responses have no properties - return nil - } - if e.ArrayValue != nil { - return e - } - if e.Name == "" { - e.Named = Named{name, s.Description} - } - - return pkg.define(e) -} - -func (pkg *Package) define(entity *Entity) *Entity { - k := entity.PascalName() - if _, ok := pkg.types[k]; ok { - return entity - } - if entity.Package == nil { - entity.Package = pkg - } - pkg.types[k] = entity - return entity -} - -func (pkg *Package) updateType(entity *Entity) { - e, defined := pkg.types[entity.PascalName()] - if !defined { - return - } - for k, v := range entity.fields { - e.fields[k] = v - } -} - -// HasPathParams returns true if any service has methods that rely on path params -func (pkg *Package) HasPathParams() bool { - for _, s := range pkg.services { - for _, m := range s.methods { - if len(m.PathParts) > 0 { - return true - } - } - } - return false -} - -// HasWaits returns true if any service has methods with long-running operations -func (pkg *Package) HasWaits() bool { - for _, s := range pkg.services { - for _, m := range s.methods { - if m.wait != nil { - return true - } - } - } - return false -} - -func (pkg *Package) getService(tag *openapi.Tag) *Service { - svc, ok := pkg.services[tag.Service] - if !ok { - svc = &Service{ - Package: pkg, - IsAccounts: tag.IsAccounts, - PathStyle: tag.PathStyle, - methods: map[string]*Method{}, - subservices: map[string]*Service{}, - Named: Named{ - Name: tag.Service, - Description: tag.Description, - }, - tag: tag, - } - pkg.services[tag.Service] = svc - } - return svc -} - -// Load takes OpenAPI specification and loads a service model -func (pkg *Package) Load(ctx context.Context, spec *openapi.Specification, tag openapi.Tag) error { - svc := pkg.getService(&tag) - - for k, v := range spec.Components.Schemas { - split := strings.Split(k, ".") - if split[0] != pkg.Name { - continue - } - pkg.definedEntity(split[1], *v, map[string]*Entity{}) - } - - // Fill in subservice information - if tag.ParentService != "" { - parentTag, err := spec.GetTagByServiceName(tag.ParentService) - if err != nil { - return err - } - parentSvc := pkg.getService(parentTag) - parentSvc.subservices[svc.Name] = svc - svc.ParentService = parentSvc - } - - // Link ControlPlane and DataPlane services - if tag.ControlPlaneService != "" { - controlPlaneTag, err := spec.GetTagByServiceName(tag.ControlPlaneService) - if err != nil { - return err - } - controlPlaneService := pkg.getService(controlPlaneTag) - svc.ControlPlaneService = controlPlaneService - controlPlaneService.DataPlaneServices = append(controlPlaneService.DataPlaneServices, svc) - } - - for prefix, path := range spec.Paths { - for verb, op := range path.Verbs() { - if op.OperationId == "Files.getStatusHead" { - // skip this method, it needs to be removed from the spec - continue - } - if !op.HasTag(tag.Name) { - continue - } - logger.Infof(ctx, "pkg.Load %s %s", verb, prefix) - params := []openapi.Parameter{} - seenParams := map[string]bool{} - for _, list := range [][]openapi.Parameter{path.Parameters, op.Parameters} { - for _, v := range list { - param, err := pkg.resolveParam(&v) - if err != nil { - return fmt.Errorf("could not resolve parameter %s for %s %s. This could be due to a problem in the definition of this parameter. If using $ref, ensure that $ref is used inside the 'schema' keyword", v.Name, verb, prefix) - } - if param == nil { - return nil - } - // We don't support headers in requests. - if param.In == "header" { - continue - } - // do not propagate common path parameter to account-level APIs - if svc.IsAccounts && param.In == "path" && param.Name == "account_id" { - continue - } - if seenParams[param.Name] { - continue - } - if prefix == "/api/2.0/workspace/export" && param.Name == "direct_download" { - // prevent changing the response content type via request parameter - // https://github.com/databricks/databricks-sdk-py/issues/104 - continue - } - params = append(params, *param) - seenParams[param.Name] = true - } - } - method, err := svc.newMethod(verb, prefix, params, op) - if err != nil { - return err - } - svc.methods[method.Name] = method - } - } - - return nil -} - -func (pkg *Package) resolveParam(v *openapi.Parameter) (param *openapi.Parameter, err error) { - defer func() { - r := recover() - if r != nil { - err = fmt.Errorf("panic: %v", r) - } - }() - param = *pkg.Components.Parameters.Resolve(v) - return -} diff --git a/openapi/code/preview.go b/openapi/code/preview.go deleted file mode 100644 index 0be333b36..000000000 --- a/openapi/code/preview.go +++ /dev/null @@ -1,15 +0,0 @@ -package code - -import ( - "strings" - - "github.com/databricks/databricks-sdk-go/openapi" -) - -func isPrivatePreview(n *openapi.Node) bool { - return strings.ToLower(n.Preview) == "private" -} - -func isPublicPreview(n *openapi.Node) bool { - return strings.ToLower(n.Preview) == "public" -} diff --git a/openapi/code/service.go b/openapi/code/service.go deleted file mode 100644 index c750cda91..000000000 --- a/openapi/code/service.go +++ /dev/null @@ -1,659 +0,0 @@ -package code - -import ( - "fmt" - "path/filepath" - "strings" - - "github.com/databricks/databricks-sdk-go/openapi" -) - -// The following headers should not be added added to the generated structs -var HIDDEN_HEADERS = map[string]struct{}{ - "X-Databricks-GCP-SA-Access-Token": {}, -} - -// When adding a new type, implement it in all SDKs -// GO: httpclient/response.go#injectHeaders -var SUPPORTED_HEADER_TYPES = map[string]struct{}{ - "string": {}, - "integer": {}, -} - -// Service represents specific Databricks API -type Service struct { - Named - PathStyle openapi.PathStyle - IsAccounts bool - Package *Package - methods map[string]*Method - subservices map[string]*Service - ByPathParamsMethods []*Shortcut - ParentService *Service - ControlPlaneService *Service - DataPlaneServices []*Service - tag *openapi.Tag -} - -// HasDataPlaneAPI returns whether this API has a DataPlane counterpart. -func (svc *Service) HasDataPlaneAPI() bool { - return len(svc.DataPlaneServices) > 0 -} - -// DataPlaneInfoMethod returns the method in the Control Plane which contains the DataInfo object -func (svc *Service) DataPlaneInfoMethod() *Method { - methodName := "" - for _, m := range svc.methods { - if m.DataPlane != nil { - methodName = m.DataPlane.ConfigMethod - if methodName == "" { - panic(fmt.Errorf("DataPlane config for method %q does not have a ConfigMethod", m.Name)) - } - } - } - return svc.ControlPlaneService.methods[methodName] -} - -// FullName holds package name and service name -func (svc *Service) FullName() string { - return fmt.Sprintf("%s.%s", svc.Package.FullName(), svc.PascalName()) -} - -// Returns whether the service has a parent service -func (svc *Service) HasParent() bool { - return svc.tag.ParentService != "" -} - -// IsDataPlane returns whether the service is a DataPlane service -// This is determined by the service having a matching control plane service -func (svc *Service) IsDataPlane() bool { - return svc.tag.ControlPlaneService != "" -} - -// Returns the list of subservices -func (svc *Service) Subservices() (services []*Service) { - for _, v := range svc.subservices { - services = append(services, v) - } - pascalNameSort(services) - return services -} - -// Returns whether the service has subservices -func (svc *Service) HasSubservices() bool { - return len(svc.subservices) > 0 -} - -// MatchesPackageName if package name and service name are the same, -// e.g. `clusters` package & `Clusters` service -func (svc *Service) MatchesPackageName() bool { - return strings.ToLower(svc.Name) == svc.Package.Name -} - -// Methods returns sorted slice of methods -func (svc *Service) Methods() (methods []*Method) { - for _, v := range svc.methods { - methods = append(methods, v) - } - pascalNameSort(methods) - return methods -} - -// NamedIdMap allows to retrieve a special NamedIdMap object from all methods -// in the service which returns name-to-id mapping retrieval definition for all -// entities of a type -// If there are multiple NamedIdMap for the service, it will panic, because this is not allowed. -func (svc *Service) NamedIdMap() *NamedIdMap { - entities := make([]*NamedIdMap, 0) - for _, v := range svc.Methods() { - // NamedIdMap is defined only for list operations - if v.Operation.Crud != "list" { - continue - } - - n := v.NamedIdMap() - if n != nil { - entities = append(entities, n) - } - } - - if len(entities) > 1 { - panic(fmt.Errorf("methods for service %s has more than one NamedIdMap operations", svc.Name)) - } - - if len(entities) == 0 { - return nil - } - - return entities[0] -} - -// List returns a method annotated with x-databricks-crud:list -func (svc *Service) List() *Method { - for _, v := range svc.Methods() { - if v.Operation.Crud == "list" { - return v - } - } - return nil -} - -// List returns a method annotated with x-databricks-crud:create -func (svc *Service) Create() *Method { - for _, v := range svc.Methods() { - if v.Operation.Crud == "create" { - return v - } - } - return nil -} - -// List returns a method annotated with x-databricks-crud:read -func (svc *Service) Read() *Method { - for _, v := range svc.Methods() { - if v.Operation.Crud == "read" { - return v - } - } - return nil -} - -// List returns a method annotated with x-databricks-crud:update -func (svc *Service) Update() *Method { - for _, v := range svc.Methods() { - if v.Operation.Crud == "update" { - return v - } - } - return nil -} - -// List returns a method annotated with x-databricks-crud:delete -func (svc *Service) Delete() *Method { - for _, v := range svc.Methods() { - if v.Operation.Crud == "delete" { - return v - } - } - return nil -} - -// HasPagination returns true if any method has result iteration -func (svc *Service) HasPagination() bool { - for _, v := range svc.methods { - p := v.pagination - if p == nil { - continue - } - if p.Offset != "" || p.Token != nil { - return true - } - } - return false -} - -func (svc *Service) getDescription(param openapi.Parameter) string { - if param.Description != "" { - return param.Description - } - if param.Schema != nil { - return param.Schema.Description - } - return "" -} - -func (svc *Service) paramToField(op *openapi.Operation, param openapi.Parameter) *Field { - named := Named{param.Name, svc.getDescription(param)} - return &Field{ - Named: named, - Required: param.Required, - IsPath: param.In == "path", - IsPathMultiSegment: param.MultiSegment, - IsQuery: param.In == "query", - IsHeader: param.In == "header", - Entity: svc.Package.schemaToEntity(param.Schema, []string{ - op.Name(), - named.PascalName(), - }, false, map[string]*Entity{}), - } -} - -var crudNames = map[string]bool{ - "create": true, - "read": true, - "get": true, - "head": true, - "update": true, - "replace": true, - "delete": true, - "list": true, - "restore": true, -} - -// Returns the schema representing a request body for a given operation, along with the mime type. -// For requests whose mime type is not application/json, the request body is always a byte stream. -func (svc *Service) getBaseSchemaAndMimeType(body *openapi.Body) (*openapi.Schema, openapi.MimeType) { - mimeType, mediaType := body.MimeTypeAndMediaType() - schema := mediaType.GetSchema() - if mimeType.IsByteStream() { - schema = &openapi.Schema{ - Type: "object", - Properties: map[string]*openapi.Schema{ - openapi.MediaTypeNonJsonBodyFieldName: schema, - }, - } - } - return schema, mimeType -} - -func (svc *Service) updateEntityTypeFromMimeType(entity *Entity, mimeType openapi.MimeType) { - if !mimeType.IsByteStream() { - return - } - // For request or response bodies that are not application/json, the body - // is modeled by a byte stream. - entity.IsByteStream = true - entity.IsAny = false -} - -// Construct the base request entity for a given operation. For requests whose -// mime type is not application/json, the request body is always a byte stream. -// For requests whose mime type is application/json, the request body consists -// of the top-level fields of the request object as defined in the OpenAPI spec. -// Additionally, for non-application/json requests, the request body is nested -// into a field named "contents". -func (svc *Service) newMethodEntity(op *openapi.Operation) (*Entity, openapi.MimeType, *Field) { - if op.RequestBody == nil { - return &Entity{fields: map[string]*Field{}, Package: svc.Package}, "", nil - } - requestSchema, mimeType := svc.getBaseSchemaAndMimeType(op.RequestBody) - res := svc.Package.schemaToEntity(requestSchema, []string{op.Name()}, true, map[string]*Entity{}) - if res == nil { - panic(fmt.Errorf("%s request body is nil", op.OperationId)) - } - - var bodyField *Field - if mimeType.IsByteStream() { - bodyField = res.fields[openapi.MediaTypeNonJsonBodyFieldName] - } - - // This next block of code is needed to make up for shortcomings in - // schemaToEntity. That function (and the Entity structure) assumes that all - // entities are modeled by JSON objects. Later, we should change Entity - // and schemaToEntity to be more tolerant of non-JSON entities; for now, we - // put this hack in place to make things work. - if mimeType.IsByteStream() { - for _, v := range res.fields { - v.IsJson = false - } - svc.updateEntityTypeFromMimeType(bodyField.Entity, mimeType) - } - - return res, mimeType, bodyField -} - -func (svc *Service) skipHeader(v openapi.Parameter, includeHeaders bool) bool { - _, hiddenHeader := HIDDEN_HEADERS[v.Name] - return v.In == "header" && (!includeHeaders || hiddenHeader) -} - -func (svc *Service) addParams(request *Entity, op *openapi.Operation, params []openapi.Parameter, includeHeaders bool) { - for _, v := range params { - if svc.skipHeader(v, includeHeaders) { - continue - } - param := svc.paramToField(op, v) - if param == nil { - continue - } - field, exists := request.fields[param.Name] - if !exists { - field = param - } - field.IsPath = param.IsPath - field.IsPathMultiSegment = param.IsPathMultiSegment - field.IsQuery = param.IsQuery - field.IsHeader = param.IsHeader - request.fields[param.Name] = field - if param.Required { - var alreadyRequired bool - for _, v := range request.RequiredOrder { - if v == param.Name { - alreadyRequired = true - break - } - } - if !alreadyRequired { - // TODO: figure out what to do with entity+param requests - request.RequiredOrder = append(request.RequiredOrder, param.Name) - } - } - if field.IsQuery { - // recursively update field entity and sub entities with IsQuery = true - // this should be safe as paramToField() should recursively create - // all needed sub-entities - field.Traverse( - func(f *Field) { - f.IsQuery = true - }) - } - } - // IsQuery may have been set on some fields, so the request entity and - // sub-entities need to be updated - request.Traverse( - func(e *Entity) { - svc.Package.updateType(e) - }) -} - -// The body param must be added after all other params so that it appears in the -// correct position in shortcut methods. -func (svc *Service) addBodyParamIfNeeded(request *Entity, mimeType openapi.MimeType) { - if mimeType.IsByteStream() { - request.RequiredOrder = append(request.RequiredOrder, openapi.MediaTypeNonJsonBodyFieldName) - } -} - -// Use heuristics to construct a "good" name for the request entity, as the name -// was not provided by the original OpenAPI spec. -func (svc *Service) nameAndDefineRequest(request *Entity, op *openapi.Operation) { - if request.Name != "" { - panic(fmt.Sprintf("request entity already has a name: %s", request.Name)) - } - - // If the operation defines a request type name, use it. - if op.RequestTypeName != "" { - request.Name = op.RequestTypeName - } else { - // Otherwise, synthesize a request type name. - singularServiceName := svc.Singular().PascalName() - notExplicit := !strings.Contains(op.Name(), singularServiceName) - if op.Name() == "list" && notExplicit { - request.Name = op.Name() + svc.Name + "Request" - } else if crudNames[strings.ToLower(op.Name())] { - request.Name = op.Name() + singularServiceName + "Request" - } else { - request.Name = op.Name() + "Request" - } - if svc.Package.Name == "scim" { - request.Name = strings.ReplaceAll(request.Name, "Account", "") - } - } - - request.Description = op.Summary - svc.Package.define(request) -} - -// Constructs the request object metadata for a method. This consists of -// -// 1. the request entity (i.e. the parameters and/or body) -// 2. the request MIME type -// 3. the field pointing to the request body (for non-JSON requests) -// -// The request entity includes fields for every parameter in the request (path, -// query, and body). If the request is defined anonymously (i.e. it is not -// refactored into a named type), the name for the request is constructed from -// the operation name and service name. -func (svc *Service) newRequest(params []openapi.Parameter, op *openapi.Operation) (*Entity, openapi.MimeType, *Field) { - if op.RequestBody == nil && len(params) == 0 { - return nil, "", nil - } - request, mimeType, bodyField := svc.newMethodEntity(op) - if request.fields == nil && request.MapValue == nil { - return nil, "", nil - } - svc.addParams(request, op, params, false) - svc.addBodyParamIfNeeded(request, mimeType) - if request.Name == "" { - svc.nameAndDefineRequest(request, op) - } - return request, mimeType, bodyField -} - -func (svc *Service) newResponse(op *openapi.Operation) (*Entity, openapi.MimeType, *Field, error) { - body := op.SuccessResponseBody(svc.Package.Components) - schema, mimeType := svc.getBaseSchemaAndMimeType(body) - name := op.Name() - response := svc.Package.definedEntity(name+"Response", schema, map[string]*Entity{}) - if op.Responses["200"] != nil { - svc.addHeaderParams(response, op, op.Responses["200"].Headers) - } - var bodyField *Field - if mimeType.IsByteStream() { - bodyField = response.fields[openapi.MediaTypeNonJsonBodyFieldName] - } - - // This next block of code is needed to make up for shortcomings in - // schemaToEntity. That function (and the Entity structure) assumes that all - // entities are modeled by JSON objects. Later, we should change Entity - // and schemaToEntity to be more tolerant of non-JSON entities; for now, we - // put this hack in place to make things work. - if mimeType.IsByteStream() { - svc.updateEntityTypeFromMimeType(bodyField.Entity, mimeType) - for _, v := range response.fields { - v.IsJson = false - } - } - - // We only support certain types of headers. Fail at build time if an unsupported type is found. - // We don't check this before because we need to ensure all referenced schemas have been defined. - if op.Responses["200"] != nil { - err := svc.validateHeaders(op.Responses["200"].Headers) - if err != nil { - return nil, "", nil, err - } - } - - return response, mimeType, bodyField, nil -} - -// ResponseHeaders are a map[string]*openapi.Parameter. The name is the key. This function converts -// the map to a slice of openapi.Parameter. -func (svc *Service) convertResponseHeaders(headers map[string]*openapi.Parameter) []openapi.Parameter { - headersList := make([]openapi.Parameter, 0, len(headers)) - for name, header := range headers { - header.Name = name - header.In = "header" - headersList = append(headersList, *header) - } - return headersList -} - -func (svc *Service) validateHeaders(headers map[string]*openapi.Parameter) error { - for _, header := range svc.convertResponseHeaders(headers) { - param := *svc.Package.Components.Schemas.Resolve(header.Schema) - if _, ok := SUPPORTED_HEADER_TYPES[param.Type]; !ok { - return fmt.Errorf("unsupported header type %q", param.Type) - } - } - return nil -} - -func (svc *Service) addHeaderParams(request *Entity, op *openapi.Operation, headers map[string]*openapi.Parameter) { - svc.addParams(request, op, svc.convertResponseHeaders(headers), true) -} - -func (svc *Service) paramPath(path string, request *Entity, params []openapi.Parameter) (parts []PathPart) { - var pathParams int - for _, v := range params { - if v.In == "path" { - pathParams++ - } - } - if svc.IsAccounts && pathParams == 0 { - // account-level services do always have `/accounts/2.0` in path - pathParams++ - } - if pathParams == 0 { - return - } - for _, v := range pathPairRE.FindAllStringSubmatch(path, -1) { - prefix := v[1] - name := v[3] - if svc.IsAccounts && name == "account_id" { - parts = append(parts, PathPart{prefix, nil, true}) - continue - } - if request == nil { - // e.g. POST /api/2.0/accounts/{account_id}/budget - parts = append(parts, PathPart{prefix, nil, false}) - continue - } - field, ok := request.fields[name] - if !ok { - parts = append(parts, PathPart{prefix, nil, false}) - continue - } - parts = append(parts, PathPart{prefix, field, false}) - } - return -} - -func (svc *Service) getPathStyle(op *openapi.Operation) openapi.PathStyle { - if op.PathStyle != "" { - return op.PathStyle - } - if svc.PathStyle != "" { - return svc.PathStyle - } - return openapi.PathStyleRest -} - -var jobs2Dot1Apis = map[string]struct{}{ - "/api/2.2/jobs/create": {}, - "/api/2.2/jobs/update": {}, - "/api/2.2/jobs/list": {}, - "/api/2.2/jobs/get": {}, - "/api/2.2/jobs/reset": {}, - "/api/2.2/jobs/runs/list": {}, -} - -func (svc *Service) pinJobsApisTo2Dot1(path string) string { - if _, ok := jobs2Dot1Apis[path]; ok { - return "/api/2.1" + path[8:] - } - return path -} - -func (svc *Service) newMethod(verb, path string, params []openapi.Parameter, op *openapi.Operation) (*Method, error) { - // Jobs is releasing the 2.2 API, but it is not yet supported fully in the - // SDKs due to new logic needed for creating, updating and getting jumbo - // jobs. For now, we pin the jobs API to 2.1, which is safe because those - // APIs are completely compatible in terms of structures and features. The - // only other difference is the default behavior for job creation, which - // skips triggered jobs in 2.1 by default, whereas they are queued by - // default in 2.2. - path = svc.pinJobsApisTo2Dot1(path) - methodName := op.Name() - request, reqMimeType, reqBodyField := svc.newRequest(params, op) - response, respMimeType, respBodyField, err := svc.newResponse(op) - if err != nil { - return nil, err - } - requestStyle := svc.getPathStyle(op) - if requestStyle == openapi.PathStyleRpc { - methodName = filepath.Base(path) - } - description := op.Description - summary := strings.TrimSpace(op.Summary) - // merge summary into description - if summary != "" { - // add a dot to the end of the summary, so that it could be extracted - // in templated with [*Named.Summary], separating from the rest of - // description. - if !strings.HasSuffix(summary, ".") { - summary += "." - } - description = fmt.Sprintf("%s\n\n%s", summary, description) - } - - var nameFieldPath, idFieldPath []*Field - respEntity := getPaginationEntity(response, op.Pagination) - if op.HasNameField() && respEntity != nil { - nameField, err := respEntity.GetUnderlyingFields(op.NameField) - if err != nil { - panic(fmt.Errorf("[%s] could not find name field %q: %w", op.OperationId, op.NameField, err)) - } - nameFieldPath = nameField - } - if op.HasIdentifierField() && respEntity != nil { - idField, err := respEntity.GetUnderlyingFields(op.IdField) - if err != nil { - panic(fmt.Errorf("[%s] could not find id field %q: %w", op.OperationId, op.IdField, err)) - } - idFieldPath = idField - } - headers := map[string]string{} - if reqMimeType != "" { - headers["Content-Type"] = string(reqMimeType) - } - if respMimeType != "" { - headers["Accept"] = string(respMimeType) - } - return &Method{ - Named: Named{methodName, description}, - Service: svc, - Verb: strings.ToUpper(verb), - Path: path, - Request: request, - PathParts: svc.paramPath(path, request, params), - Response: response, - PathStyle: requestStyle, - NameFieldPath: nameFieldPath, - IdFieldPath: idFieldPath, - RequestBodyField: reqBodyField, - ResponseBodyField: respBodyField, - FixedRequestHeaders: headers, - wait: op.Wait, - Operation: op, - pagination: op.Pagination, - shortcut: op.Shortcut, - DataPlane: op.DataPlane, - }, nil -} - -func (svc *Service) HasWaits() bool { - for _, v := range svc.methods { - if v.wait != nil { - return true - } - } - return false -} - -func (svc *Service) Waits() (waits []*Wait) { - seen := map[string]bool{} - for _, m := range svc.methods { - if m.wait == nil { - continue - } - wait := m.Wait() - if seen[wait.Name] { - continue - } - waits = append(waits, wait) - seen[wait.Name] = true - } - pascalNameSort(waits) - return waits -} - -// IsPrivatePreview flags object being in private preview. -func (svc *Service) IsPrivatePreview() bool { - return isPrivatePreview(&svc.tag.Node) -} - -// IsPublicPreview flags object being in public preview. -func (svc *Service) IsPublicPreview() bool { - return isPublicPreview(&svc.tag.Node) -} - -func getPaginationEntity(entity *Entity, pagination *openapi.Pagination) *Entity { - if pagination == nil { - return nil - } - if pagination.Inline { - return entity.ArrayValue - } - return entity.Field(pagination.Results).Entity.ArrayValue -} diff --git a/openapi/code/tmpl_util_funcs.go b/openapi/code/tmpl_util_funcs.go deleted file mode 100644 index 551d075ba..000000000 --- a/openapi/code/tmpl_util_funcs.go +++ /dev/null @@ -1,86 +0,0 @@ -package code - -import ( - "errors" - "fmt" - "reflect" - "regexp" - "strings" - "text/template" -) - -var ErrSkipThisFile = errors.New("skip generating this file") - -var alphanumRE = regexp.MustCompile(`^\w*$`) - -var HelperFuncs = template.FuncMap{ - "notLast": func(idx int, a interface{}) bool { - return idx+1 != reflect.ValueOf(a).Len() - }, - "contains": strings.Contains, - "lower": strings.ToLower, - "lowerFirst": func(s string) string { - return strings.ToLower(s[0:1]) + s[1:] - }, - "trimPrefix": func(right, left string) string { - return strings.TrimPrefix(left, right) - }, - "trimSuffix": func(right, left string) string { - return strings.TrimSuffix(left, right) - }, - "replaceAll": func(from, to, str string) string { - return strings.ReplaceAll(str, from, to) - }, - "without": func(left, right string) string { - return strings.ReplaceAll(right, left, "") - }, - "skipThisFile": func() error { - // error is rendered as string in the resulting file, so we must panic, - // so that we handle this error in [gen.Pass[T].File] gracefully - // via errors.Is(err, code.ErrSkipThisFile) - panic(ErrSkipThisFile) - }, - "alphanumOnly": func(in []*Field) (out []*Field) { - for _, v := range in { - if !alphanumRE.MatchString(v.Name) { - continue - } - out = append(out, v) - } - return out - }, - "list": func(l ...any) []any { - return l - }, - "in": func(haystack []any, needle string) bool { - for _, v := range haystack { - if needle == fmt.Sprint(v) { - return true - } - } - return false - }, - "dict": func(args ...any) map[string]any { - if len(args)%2 != 0 { - panic("number of arguments to dict is not even") - } - result := map[string]any{} - for i := 0; i < len(args); i += 2 { - k := fmt.Sprint(args[i]) - v := args[i+1] - result[k] = v - } - return result - }, - "getOrDefault": func(dict map[string]any, key string, def any) any { - v, ok := dict[key] - if ok { - return v - } - return def - }, - "fmt": fmt.Sprintf, - "concat": func(v ...string) string { - return strings.Join(v, "") - }, -} diff --git a/openapi/code/wait.go b/openapi/code/wait.go deleted file mode 100644 index 4fa2c8888..000000000 --- a/openapi/code/wait.go +++ /dev/null @@ -1,180 +0,0 @@ -package code - -import ( - "fmt" - "sort" -) - -// Wait represents a long-running operation, that requires multiple RPC calls -type Wait struct { - Named - // represents a method that triggers the start of the long-running operation - Method *Method -} - -// Binding connects fields in generated code across multiple requests -type Binding struct { - // Polling method request field - PollField *Field - - // Wrapped method either response or request body field - Bind *Field - - // Is wrapped method response used? - IsResponseBind bool -} - -// reasonable default timeout for the most of long-running operations -const defaultLongRunningTimeout = 20 - -// Timeout returns timeout in minutes, defaulting to 20 -func (w *Wait) Timeout() int { - t := w.Method.Operation.Wait.Timeout - if t == 0 { - return defaultLongRunningTimeout - } - return t -} - -// Binding returns a slice of request and response connections -func (w *Wait) Binding() (binding []Binding) { - poll := w.Poll() - if w.Method.wait.Binding != nil { - for pollRequestField, b := range w.Method.wait.Binding { - var bind *Field - if b.Response != "" { - bind = w.Method.Response.Field(b.Response) - } else { - bind = w.Method.Request.Field(b.Request) - } - binding = append(binding, Binding{ - PollField: poll.Request.Field(pollRequestField), - Bind: bind, - IsResponseBind: b.Response != "", - }) - } - // ensure generated code is deterministic - // Java SDK relies on bind parameter order. - sort.Slice(binding, func(a, b int) bool { - return binding[a].PollField.Name < binding[b].PollField.Name - }) - } else { - responseBind := true - bind := w.Method.wait.Bind - entity := w.Method.Response - if entity.IsEmpty() { - entity = w.Method.Request - responseBind = false - } - pollField := poll.Request.Field(bind) - if pollField == nil { - panic(fmt.Errorf("cannot bind response field: %s", bind)) - } - binding = append(binding, Binding{ - PollField: pollField, - Bind: entity.Field(bind), - IsResponseBind: responseBind, - }) - } - return binding -} - -// ForceBindRequest is a workaround for Jobs#RepairRun, -// that does not send run_id in response -func (w *Wait) ForceBindRequest() bool { - if w.Method.Response == nil { - return false - } - binding := w.Binding() - if len(binding) == 1 && !binding[0].IsResponseBind { - return true - } - return false -} - -// Poll returns method definition for checking the state of -// the long running operation -func (w *Wait) Poll() *Method { - getStatus, ok := w.Method.Service.methods[w.Method.wait.Poll] - if !ok { - return nil - } - return getStatus -} - -// Success holds the successful end-states of the operation -func (w *Wait) Success() (match []EnumEntry) { - enum := w.enum() - for _, v := range w.Method.wait.Success { - match = append(match, enum[v]) - } - return match -} - -// Failure holds the failed end-states of the operation -func (w *Wait) Failure() (match []EnumEntry) { - enum := w.enum() - for _, v := range w.Method.wait.Failure { - match = append(match, enum[v]) - } - return match -} - -func (w *Wait) enum() map[string]EnumEntry { - statusPath := w.StatusPath() - statusField := statusPath[len(statusPath)-1] - return statusField.Entity.enum -} - -// StatusPath holds the path to the field of polled entity, -// that holds current state of the long-running operation -func (w *Wait) StatusPath() (path []*Field) { - pollMethod := w.Poll() - pathToStatus := w.Method.wait.Field - current := pollMethod.Response - for { - fieldName := pathToStatus[0] - pathToStatus = pathToStatus[1:] - field := current.Field(fieldName) - path = append(path, field) - current = field.Entity - if len(pathToStatus) == 0 { - break - } - } - return path -} - -// MessagePath holds the path to the field of polled entity, -// that can tell about current inner status of the long-running operation -func (w *Wait) MessagePath() (path []*Field) { - pollMethod := w.Poll() - current := pollMethod.Response - for _, fieldName := range w.Method.wait.Message { - field := current.Field(fieldName) - path = append(path, field) - current = field.Entity - } - return path -} - -func (w *Wait) Status() *Field { - path := w.StatusPath() - if path == nil { - // unreachable - return nil - } - return path[len(path)-1] -} - -func (w *Wait) ComplexMessagePath() bool { - return len(w.Method.wait.Message) > 1 -} - -func (w *Wait) MessagePathHead() *Field { - path := w.MessagePath() - if len(path) == 0 { - panic("message path is empty for " + w.Method.Operation.OperationId) - } - return path[0] -} diff --git a/openapi/errors.go b/openapi/errors.go deleted file mode 100644 index c5362ea6f..000000000 --- a/openapi/errors.go +++ /dev/null @@ -1,117 +0,0 @@ -package openapi - -import "regexp" - -type ErrorMappingRule struct { - StatusCode int `json:"status_code"` - ErrorCode string `json:"error_code"` - Description string `json:"description"` -} - -// API error rules for the Databricks REST API based on HTTP status codes. -// -// The API responds with an error by setting the HTTP status code to 400 or -// higher and returning a JSON object with an error code and message. Error -// responses are hierarchical in nature, with the HTTP status code providing -// the highest level of categorization. The error_code field in the response -// provides a more granular categorization of the error. -// -// The SDK attempts to map these error responses to error objects based on this -// mapping by applying the following logic: -// -// 1. If the error matches an override defined in ErrorOverrides, return the -// override. -// 2. If the error_code field of the response matches a key in -// ErrorCodeMapping, return that error. -// 3. If the HTTP status code matches a rule in ErrorStatusCodeMapping, return -// that error. -var ErrorStatusCodeMapping = []ErrorMappingRule{ - {400, "BAD_REQUEST", "the request is invalid"}, - {401, "UNAUTHENTICATED", "the request does not have valid authentication (AuthN) credentials for the operation"}, - {403, "PERMISSION_DENIED", "the caller does not have permission to execute the specified operation"}, - {404, "NOT_FOUND", "the operation was performed on a resource that does not exist"}, - {409, "RESOURCE_CONFLICT", "maps to all HTTP 409 (Conflict) responses"}, - {429, "TOO_MANY_REQUESTS", "maps to HTTP code: 429 Too Many Requests"}, - {499, "CANCELLED", "the operation was explicitly canceled by the caller"}, - {500, "INTERNAL_ERROR", "some invariants expected by the underlying system have been broken"}, - {501, "NOT_IMPLEMENTED", "the operation is not implemented or is not supported/enabled in this service"}, - {503, "TEMPORARILY_UNAVAILABLE", "the service is currently unavailable"}, - {504, "DEADLINE_EXCEEDED", "the deadline expired before the operation could complete"}, -} - -// Specialized API error rules based on the error_code field in the error -// response. -// -// See the documentation on ErrorStatusCodeMapping for more information. -var ErrorCodeMapping = []ErrorMappingRule{ - {400, "INVALID_STATE", "unexpected state"}, - {400, INVALID_PARAMETER_VALUE, "supplied value for a parameter was invalid"}, - {404, RESOURCE_DOES_NOT_EXIST, "operation was performed on a resource that does not exist"}, - {409, "ABORTED", "the operation was aborted, typically due to a concurrency issue such as a sequencer check failure"}, - {409, "ALREADY_EXISTS", "operation was rejected due a conflict with an existing resource"}, - {409, "RESOURCE_ALREADY_EXISTS", "operation was rejected due a conflict with an existing resource"}, - {429, "RESOURCE_EXHAUSTED", "operation is rejected due to per-user rate limiting"}, - {429, "REQUEST_LIMIT_EXCEEDED", "cluster request was rejected because it would exceed a resource limit"}, - {500, "UNKNOWN", "this error is used as a fallback if the platform-side mapping is missing some reason"}, - {500, "DATA_LOSS", "unrecoverable data loss or corruption"}, -} - -type ErrorOverride struct { - Name string - PathRegex *regexp.Regexp - Verb string - StatusCodeMatcher *regexp.Regexp - ErrorCodeMatcher *regexp.Regexp - MessageMatcher *regexp.Regexp - OverrideErrorCode string -} - -const INVALID_PARAMETER_VALUE = "INVALID_PARAMETER_VALUE" -const RESOURCE_DOES_NOT_EXIST = "RESOURCE_DOES_NOT_EXIST" - -// Overrides in the SDK to remap specific error responses to other errors. -// -// When certain APIs return a non-standard or inconsistent error response, the -// SDK can be configured to remap these errors to a more appropriate error. -// For example, some APIs return a 400 error when a resource doesn't exist. In -// this case, the SDK can be configured to remap the error to a 404 error. -var ErrorOverrides = []ErrorOverride{ - { - Name: "Clusters InvalidParameterValue=>ResourceDoesNotExist", - PathRegex: regexp.MustCompile(`^/api/2\.\d/clusters/get`), - Verb: "GET", - StatusCodeMatcher: regexp.MustCompile(`^400$`), - MessageMatcher: regexp.MustCompile("Cluster .* does not exist"), - ErrorCodeMatcher: regexp.MustCompile(INVALID_PARAMETER_VALUE), - OverrideErrorCode: RESOURCE_DOES_NOT_EXIST, - }, - { - Name: "Jobs InvalidParameterValue=>ResourceDoesNotExist", - PathRegex: regexp.MustCompile(`^/api/2\.\d/jobs/get`), - Verb: "GET", - StatusCodeMatcher: regexp.MustCompile(`^400$`), - MessageMatcher: regexp.MustCompile("Job .* does not exist"), - ErrorCodeMatcher: regexp.MustCompile(INVALID_PARAMETER_VALUE), - OverrideErrorCode: RESOURCE_DOES_NOT_EXIST, - }, - { - Name: "Job Runs InvalidParameterValue=>ResourceDoesNotExist", - PathRegex: regexp.MustCompile(`^/api/2\.\d/jobs/runs/get`), - Verb: "GET", - StatusCodeMatcher: regexp.MustCompile(`^400$`), - MessageMatcher: regexp.MustCompile("(Run .* does not exist|Run: .* in job: .* doesn't exist)"), - ErrorCodeMatcher: regexp.MustCompile(INVALID_PARAMETER_VALUE), - OverrideErrorCode: RESOURCE_DOES_NOT_EXIST, - }, -} - -var TransientErrorRegexes = []*regexp.Regexp{ - regexp.MustCompile(`com\.databricks\.backend\.manager\.util\.UnknownWorkerEnvironmentException`), - regexp.MustCompile(`does not have any associated worker environments`), - regexp.MustCompile(`There is no worker environment with id`), - regexp.MustCompile(`Unknown worker environment`), - regexp.MustCompile(`ClusterNotReadyException`), - regexp.MustCompile(`worker env .* not found`), - regexp.MustCompile(`Timed out after `), - regexp.MustCompile(`deadline exceeded`), -} diff --git a/openapi/extensions.go b/openapi/extensions.go deleted file mode 100644 index 9e4d225c7..000000000 --- a/openapi/extensions.go +++ /dev/null @@ -1,37 +0,0 @@ -package openapi - -// Pagination is the Databricks OpenAPI Extension for retrieving -// lists of entities through multiple API calls -type Pagination struct { - Offset string `json:"offset,omitempty"` - Limit string `json:"limit,omitempty"` - Results string `json:"results,omitempty"` - Increment int `json:"increment,omitempty"` - Inline bool `json:"inline,omitempty"` - Token *Binding `json:"token,omitempty"` -} - -// Wait is the Databricks OpenAPI Extension for long-running result polling -type Wait struct { - Poll string `json:"poll"` - Bind string `json:"bind"` - BindResponse string `json:"bindResponse,omitempty"` - Binding map[string]Binding `json:"binding,omitempty"` - Field []string `json:"field"` - Message []string `json:"message"` - Success []string `json:"success"` - Failure []string `json:"failure"` - Timeout int `json:"timeout,omitempty"` -} - -// Binding is a relationship between request and/or response -type Binding struct { - Request string `json:"request,omitempty"` - Response string `json:"response,omitempty"` -} - -// DataPlane is the Databricks OpenAPI Extension for direct access to DataPlane APIs -type DataPlane struct { - ConfigMethod string `json:"configMethod"` - Fields []string `json:"field"` -} diff --git a/openapi/gen/main.go b/openapi/gen/main.go deleted file mode 100644 index b1a2233e1..000000000 --- a/openapi/gen/main.go +++ /dev/null @@ -1,67 +0,0 @@ -// Usage: openapi-codegen -package main - -import ( - "context" - "flag" - "fmt" - "os" - "path" - - "github.com/databricks/databricks-sdk-go/openapi/code" - "github.com/databricks/databricks-sdk-go/openapi/generator" - "github.com/databricks/databricks-sdk-go/openapi/render" - "github.com/databricks/databricks-sdk-go/openapi/roll" -) - -var c Context - -func main() { - ctx := context.Background() - cfg, err := render.Config() - if err != nil { - fmt.Printf("WARN: %s\n\n", err) - } - workDir, _ := os.Getwd() - flag.StringVar(&c.Spec, "spec", cfg.Spec, "location of the spec file") - flag.StringVar(&c.GoSDK, "gosdk", cfg.GoSDK, "location of the Go SDK") - flag.StringVar(&c.Target, "target", workDir, "path to directory with .codegen.json") - flag.BoolVar(&c.DryRun, "dry-run", false, "print to stdout instead of real files") - flag.Parse() - if c.Spec == "" { - println("USAGE: go run openapi/gen/main.go -spec /path/to/spec.json") - flag.PrintDefaults() - os.Exit(1) - } - err = c.Run(ctx) - if err != nil { - fmt.Printf("ERROR: %s\n\n", err) - os.Exit(1) - } -} - -type Context struct { - Spec string - GoSDK string - Target string - DryRun bool -} - -func (c *Context) Run(ctx context.Context) error { - spec, err := code.NewFromFile(ctx, c.Spec) - if err != nil { - return fmt.Errorf("spec: %w", err) - } - var suite *roll.Suite - if c.GoSDK != "" { - suite, err = roll.NewSuite(path.Join(c.GoSDK, "internal")) - if err != nil { - return fmt.Errorf("examples: %w", err) - } - } - gen, err := generator.NewGenerator(c.Target) - if err != nil { - return fmt.Errorf("config: %w", err) - } - return gen.Apply(ctx, spec, suite) -} diff --git a/openapi/generator/config.go b/openapi/generator/config.go deleted file mode 100644 index 6dcaae873..000000000 --- a/openapi/generator/config.go +++ /dev/null @@ -1,177 +0,0 @@ -package generator - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "os" - "path/filepath" - "sort" - - "github.com/databricks/databricks-sdk-go/openapi/code" - "github.com/databricks/databricks-sdk-go/openapi/render" - "github.com/databricks/databricks-sdk-go/openapi/roll" -) - -type Toolchain struct { - Required []string `json:"required"` - PreSetup []string `json:"pre_setup,omitempty"` - PrependPath string `json:"prepend_path,omitempty"` - Setup []string `json:"setup,omitempty"` - PostGenerate []string `json:"post_generate,omitempty"` -} - -type Generator struct { - Formatter string `json:"formatter"` - // Config for changelog generation. - ChangelogConfig string `json:"changelog_config,omitempty"` - // TemplateLibraries is a list of files containing go template definitions - // that are reused in different stages of codegen. E.g. the "type" template - // is needed in both the "types" and "services" stages. - TemplateLibraries []string `json:"template_libraries,omitempty"` - - // We can generate SDKs in three modes: Packages, Types, Services - // E.g. Go is Package-focused and Java is Types+Services - Packages map[string]string `json:"packages,omitempty"` - Types map[string]string `json:"types,omitempty"` - Services map[string]string `json:"services,omitempty"` - ExceptionTypes map[string]string `json:"exception_types,omitempty"` - Batch map[string]string `json:"batch,omitempty"` - - // special case for usage example templates, that are generated - // from Go SDK integration tests - Examples map[string]string `json:"examples,omitempty"` - Samples map[string]string `json:"samples,omitempty"` - - // version bumps - Version map[string]string `json:"version,omitempty"` - - // code generation toolchain configuration - Toolchain *Toolchain `json:"toolchain,omitempty"` - - dir string -} - -func NewGenerator(target string) (*Generator, error) { - f, err := os.Open(fmt.Sprintf("%s/.codegen.json", target)) - if err != nil { - return nil, fmt.Errorf("no .codegen.json file in %s: %w", target, err) - } - defer f.Close() - raw, err := io.ReadAll(f) - if err != nil { - return nil, fmt.Errorf("read all: %w", err) - } - var c Generator - err = json.Unmarshal(raw, &c) - if err != nil { - return nil, fmt.Errorf(".codegen.json: %w", err) - } - c.dir = target - return &c, nil -} - -func (c *Generator) Apply(ctx context.Context, batch *code.Batch, suite *roll.Suite) error { - if suite != nil { - err := suite.OptimizeWithApiSpec(batch) - if err != nil { - return fmt.Errorf("optimize examples: %w", err) - } - } - var filenames []string - if c.Batch != nil { - pass := render.NewPass(c.dir, []render.Named{batch}, c.Batch, c.TemplateLibraries) - err := pass.Run(ctx) - if err != nil { - return fmt.Errorf("batch: %w", err) - } - filenames = append(filenames, pass.Filenames...) - } - if c.Packages != nil { - pass := render.NewPass(c.dir, batch.Packages(), c.Packages, c.TemplateLibraries) - err := pass.Run(ctx) - if err != nil { - return fmt.Errorf("packages: %w", err) - } - filenames = append(filenames, pass.Filenames...) - } - if c.Services != nil { - pass := render.NewPass(c.dir, batch.Services(), c.Services, c.TemplateLibraries) - err := pass.Run(ctx) - if err != nil { - return fmt.Errorf("services: %w", err) - } - filenames = append(filenames, pass.Filenames...) - } - if c.Types != nil { - pass := render.NewPass(c.dir, batch.Types(), c.Types, c.TemplateLibraries) - err := pass.Run(ctx) - if err != nil { - return fmt.Errorf("types: %w", err) - } - filenames = append(filenames, pass.Filenames...) - } - if c.ExceptionTypes != nil { - pass := render.NewPass(c.dir, batch.ExceptionTypes(), c.ExceptionTypes, c.TemplateLibraries) - err := pass.Run(ctx) - if err != nil { - return fmt.Errorf("exception types: %w", err) - } - filenames = append(filenames, pass.Filenames...) - } - if c.Examples != nil && suite != nil { - pass := render.NewPass(c.dir, suite.ServicesExamples(), c.Examples, c.TemplateLibraries) - err := pass.Run(ctx) - if err != nil { - return fmt.Errorf("examples: %w", err) - } - filenames = append(filenames, pass.Filenames...) - } - if c.Samples != nil && suite != nil { - pass := render.NewPass(c.dir, suite.Samples(), c.Samples, c.TemplateLibraries) - err := pass.Run(ctx) - if err != nil { - return fmt.Errorf("examples: %w", err) - } - filenames = append(filenames, pass.Filenames...) - } - - mockDir := filepath.Join(c.dir, "experimental", "mocks", "service") - mockFilenames := []string{} - info, err := os.Stat(mockDir) - if err == nil && info.IsDir() { - err := filepath.Walk(mockDir, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if !info.IsDir() { - relPath, err := filepath.Rel(c.dir, path) - if err != nil { - return err - } - mockFilenames = append(mockFilenames, relPath) - } - return nil - }) - if err != nil { - return fmt.Errorf("mocks: %w", err) - } - filenames = append(filenames, mockFilenames...) - } - - err = render.Formatter(ctx, c.dir, filenames, c.Formatter) - if err != nil { - return err - } - sort.Strings(filenames) - sb := bytes.NewBuffer([]byte{}) - for _, v := range filenames { - // service/*/api.go linguist-generated=true - sb.WriteString(v) - sb.WriteString(" linguist-generated=true\n") - } - genMetaFile := fmt.Sprintf("%s/.gitattributes", c.dir) - return os.WriteFile(genMetaFile, sb.Bytes(), 0o755) -} diff --git a/openapi/model.go b/openapi/model.go deleted file mode 100644 index e9cb5862e..000000000 --- a/openapi/model.go +++ /dev/null @@ -1,349 +0,0 @@ -package openapi - -import ( - "encoding/json" - "fmt" - "io" - "reflect" - "strings" -) - -type Node struct { - Description string `json:"description,omitempty"` - Preview string `json:"x-databricks-preview,omitempty"` - Ref string `json:"$ref,omitempty"` - // Currently it is only defined for top level schemas - JsonPath string `json:"-"` -} - -// IsRef flags object being a reference to a component -func (n *Node) IsRef() bool { - return n.Ref != "" -} - -// Components is the basename of the reference path. Usually a class name -func (n *Node) Component() string { - s := strings.Split(n.Ref, "/") - return s[len(s)-1] -} - -func NewFromReader(r io.Reader) (*Specification, error) { - raw, err := io.ReadAll(r) - if err != nil { - return nil, fmt.Errorf("cannot read openapi spec: %w", err) - } - var spec Specification - err = json.Unmarshal(raw, &spec) - if err != nil { - return nil, fmt.Errorf("cannot parse openapi spec: %w", err) - } - setJsonPaths(spec) - return &spec, nil -} - -func setJsonPaths(spec Specification) { - for name, schema := range spec.Components.Schemas { - deref := *schema - deref.JsonPath = fmt.Sprintf("%s,%s", "#/components/schemas/", name) - } -} - -type Specification struct { - Node - Paths map[string]Path `json:"paths"` - Components *Components `json:"components"` - Tags []Tag `json:"tags"` -} - -func (s *Specification) GetTagByServiceName(name string) (*Tag, error) { - for _, tag := range s.Tags { - if tag.Service == name { - return &tag, nil - } - } - return nil, fmt.Errorf("tag %s not found", name) -} - -type PathStyle string - -const ( - // PathStyleRpc indicates that the endpoint is an RPC-style endpoint. - // The endpoint path is an action, and the entity to act on is specified - // in the request body. - PathStyleRpc PathStyle = "rpc" - - // PathStyleRest indicates that the endpoint is a REST-style endpoint. - // The endpoint path is a resource, and the operation to perform on the - // resource is specified in the HTTP method. - PathStyleRest PathStyle = "rest" -) - -func (r *PathStyle) UnmarshalJSON(data []byte) error { - var s string - err := json.Unmarshal(data, &s) - if err != nil { - return fmt.Errorf("cannot unmarshal RequestStyle: %w", err) - } - switch s { - case "rpc", "rest": - *r = PathStyle(s) - default: - return fmt.Errorf("invalid RequestStyle: %s", s) - } - return nil -} - -type Tag struct { - Node - Package string `json:"x-databricks-package"` - PathStyle PathStyle `json:"x-databricks-path-style"` - Service string `json:"x-databricks-service"` - ParentService string `json:"x-databricks-parent-service"` - ControlPlaneService string `json:"x-databricks-controlplane"` - IsAccounts bool `json:"x-databricks-is-accounts"` - Name string `json:"name"` -} - -type Path struct { - Node - Parameters []Parameter `json:"parameters,omitempty"` - Get *Operation `json:"get,omitempty"` - Head *Operation `json:"head,omitempty"` - Post *Operation `json:"post,omitempty"` - Put *Operation `json:"put,omitempty"` - Patch *Operation `json:"patch,omitempty"` - Delete *Operation `json:"delete,omitempty"` -} - -// Verbs returns a map of HTTP methods for a Path -func (path *Path) Verbs() map[string]*Operation { - m := map[string]*Operation{} - if path.Get != nil { - m["GET"] = path.Get - } - if path.Head != nil { - m["HEAD"] = path.Head - } - if path.Post != nil { - m["POST"] = path.Post - } - if path.Put != nil { - m["PUT"] = path.Put - } - if path.Patch != nil { - m["PATCH"] = path.Patch - } - if path.Delete != nil { - m["DELETE"] = path.Delete - } - return m -} - -type fieldPath []string - -func (fp fieldPath) String() string { - return strings.Join(fp, ".") -} - -// Operation is the equivalent of method -type Operation struct { - Node - Wait *Wait `json:"x-databricks-wait,omitempty"` - Pagination *Pagination `json:"x-databricks-pagination,omitempty"` - DataPlane *DataPlane `json:"x-databricks-dataplane,omitempty"` - Shortcut bool `json:"x-databricks-shortcut,omitempty"` - Crud string `json:"x-databricks-crud,omitempty"` - JsonOnly bool `json:"x-databricks-cli-json-only,omitempty"` - - // The x-databricks-path-style field indicates whether the operation has a - // RESTful path style or a RPC style. When specified, this overrides the - // service-level setting. Valid values are "rest" and "rpc". "rest" means - // that the operation has a RESTful path style, i.e. the path represents - // a resource and the HTTP method represents an action on the resource. - // "rpc" means that the operation has a RPC style, i.e. the path represents - // an action and the request body represents the resource. - PathStyle PathStyle `json:"x-databricks-path-style,omitempty"` - - // The x-databricks-request-type-name field defines the name to use for - // the request type in the generated client. This may be specified only - // if the operation does NOT have a request body, thus only uses a request - // type to encapsulate path and query parameters. - RequestTypeName string `json:"x-databricks-request-type-name,omitempty"` - - // For list APIs, the path to the field in the response entity that contains - // the resource ID. - IdField fieldPath `json:"x-databricks-id,omitempty"` - - // For list APIs, the path to the field in the response entity that contains - // the user-friendly name of the resource. - NameField fieldPath `json:"x-databricks-name,omitempty"` - - Summary string `json:"summary,omitempty"` - OperationId string `json:"operationId"` - Tags []string `json:"tags"` - Parameters []Parameter `json:"parameters,omitempty"` - Responses map[string]*Body `json:"responses"` - RequestBody *Body `json:"requestBody,omitempty"` -} - -// Name is picking the last element of. string, -// that is coming in as part of Databricks OpenAPI spec. -func (o *Operation) Name() string { - split := strings.Split(o.OperationId, ".") - if len(split) == 2 { - return split[1] - } - return o.OperationId -} - -func (o *Operation) HasTag(tag string) bool { - for _, v := range o.Tags { - if v == tag { - return true - } - } - return false -} - -func (o *Operation) SuccessResponseBody(c *Components) *Body { - for _, v := range []string{"200", "201"} { - response, ok := o.Responses[v] - if ok { - return (*c.Responses.Resolve(response)) - } - } - return nil -} - -func (o *Operation) HasNameField() bool { - return len(o.NameField) > 0 -} - -func (o *Operation) HasIdentifierField() bool { - return len(o.IdField) > 0 -} - -type node interface { - IsRef() bool - Component() string -} - -type refs[T node] map[string]*T - -func (c refs[T]) Resolve(item T) *T { - if reflect.ValueOf(item).IsNil() { - return nil - } - if !item.IsRef() { - return &item - } - return c[item.Component()] -} - -type Components struct { - Node - Parameters refs[*Parameter] `json:"parameters,omitempty"` - Responses refs[*Body] `json:"responses,omitempty"` - Schemas refs[*Schema] `json:"schemas,omitempty"` -} - -type Schema struct { - Node - IsComputed bool `json:"x-databricks-computed,omitempty"` - IsAny bool `json:"x-databricks-any,omitempty"` - Type string `json:"type,omitempty"` - Enum []string `json:"enum,omitempty"` - AliasEnum []string `json:"x-databricks-alias-enum,omitempty"` - EnumDescriptions map[string]string `json:"x-databricks-enum-descriptions,omitempty"` - Default any `json:"default,omitempty"` - Example any `json:"example,omitempty"` - Format string `json:"format,omitempty"` - Required []string `json:"required,omitempty"` - Properties map[string]*Schema `json:"properties,omitempty"` - ArrayValue *Schema `json:"items,omitempty"` - MapValue *Schema `json:"additionalProperties,omitempty"` - Terraform *Terraform `json:"x-databricks-terraform,omitempty"` -} - -type Terraform struct { - Alias string `json:"alias,omitempty"` -} - -func (s *Schema) IsEnum() bool { - return len(s.Enum) != 0 -} - -func (s *Schema) IsObject() bool { - return len(s.Properties) != 0 -} - -func (s *Schema) IsMap() bool { - return s.MapValue != nil -} - -func (s *Schema) IsArray() bool { - return s.ArrayValue != nil -} - -type Parameter struct { - Node - Required bool `json:"required,omitempty"` - In string `json:"in,omitempty"` - Name string `json:"name,omitempty"` - MultiSegment bool `json:"x-databricks-multi-segment,omitempty"` - Schema *Schema `json:"schema,omitempty"` -} - -type Body struct { - Node - Required bool `json:"required,omitempty"` - Content map[string]MediaType `json:"content,omitempty"` - Headers map[string]*Parameter `json:"headers,omitempty"` -} - -type MimeType string - -const ( - MimeTypeJson MimeType = "application/json" - MimeTypeOctetStream MimeType = "application/octet-stream" - MimeTypeTextPlain MimeType = "text/plain" -) - -// IsByteStream returns true if the body should be modeled as a byte stream. -// Today, we only support application/json and application/octet-stream, and non -// application/json entities are all modeled as byte streams. -func (m MimeType) IsByteStream() bool { - return m != "" && m != MimeTypeJson -} - -var allowedMimeTypes = []MimeType{ - MimeTypeJson, - MimeTypeOctetStream, - MimeTypeTextPlain, -} - -func (b *Body) MimeTypeAndMediaType() (MimeType, *MediaType) { - if b == nil || b.Content == nil { - return "", nil - } - for _, m := range allowedMimeTypes { - if mediaType, ok := b.Content[string(m)]; ok { - return m, &mediaType - } - } - return "", nil -} - -type MediaType struct { - Node - Schema *Schema `json:"schema,omitempty"` -} - -const MediaTypeNonJsonBodyFieldName = "contents" - -func (m *MediaType) GetSchema() *Schema { - if m == nil { - return nil - } - return m.Schema -} diff --git a/openapi/model_test.go b/openapi/model_test.go deleted file mode 100644 index e4b7d9b31..000000000 --- a/openapi/model_test.go +++ /dev/null @@ -1,16 +0,0 @@ -package openapi - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestLoadFromJson(t *testing.T) { - f, err := os.Open("testdata/spec.json") - assert.NoError(t, err) - spec, err := NewFromReader(f) - assert.NoError(t, err) - assert.Equal(t, "Command Execution", spec.Tags[0].Name) -} diff --git a/openapi/render/render.go b/openapi/render/render.go deleted file mode 100644 index 950fd7c55..000000000 --- a/openapi/render/render.go +++ /dev/null @@ -1,172 +0,0 @@ -package render - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "io/fs" - "os" - "os/exec" - "path" - "path/filepath" - "strings" - "text/template" - - "github.com/databricks/databricks-sdk-go/logger" - "github.com/databricks/databricks-sdk-go/openapi/code" -) - -type toolConfig struct { - Spec string `json:"spec"` - GoSDK string `json:"gosdk,omitempty"` -} - -func Config() (toolConfig, error) { - home, err := os.UserHomeDir() - if err != nil { - return toolConfig{}, fmt.Errorf("home: %w", err) - } - loc := filepath.Join(home, ".openapi-codegen.json") - f, err := os.Open(loc) - if err != nil { - return toolConfig{}, fmt.Errorf("open %s: %w", loc, err) - } - raw, err := io.ReadAll(f) - if err != nil { - return toolConfig{}, fmt.Errorf("read all: %w", err) - } - var cfg toolConfig - err = json.Unmarshal(raw, &cfg) - if err != nil { - return cfg, fmt.Errorf("parse %s: %w", loc, err) - } - return cfg, nil -} - -func NewPass[T Named](target string, items []T, fileset map[string]string, libs []string) *pass[T] { - var tmpls []string - newFileset := map[string]string{} - for filename, v := range fileset { - filename = filepath.Join(target, filename) - tmpls = append(tmpls, filename) - newFileset[filepath.Base(filename)] = v - } - for _, lib := range libs { - tmpls = append(tmpls, filepath.Join(target, lib)) - } - t := template.New("codegen").Funcs(code.HelperFuncs) - t = t.Funcs(template.FuncMap{ - "load": func(tmpl string) (string, error) { - _, err := t.ParseFiles(tmpl) - return "", err - }, - }) - return &pass[T]{ - Items: items, - target: target, - fileset: newFileset, - tmpl: template.Must(t.ParseFiles(tmpls...)), - } -} - -type Named interface { - FullName() string -} - -type pass[T Named] struct { - Items []T - target string - tmpl *template.Template - fileset map[string]string - Filenames []string -} - -func (p *pass[T]) Run(ctx context.Context) error { - for _, item := range p.Items { - name := item.FullName() - logger.Infof(ctx, "Processing: %s\n", name) - for k, v := range p.fileset { - err := p.File(item, k, v) - if err != nil { - return fmt.Errorf("%s: %w", item.FullName(), err) - } - } - } - return nil -} - -func (p *pass[T]) File(item T, contentTRef, nameT string) error { - nt, err := template.New("filename").Parse(nameT) - if err != nil { - return fmt.Errorf("parse %s: %w", nameT, err) - } - var contents strings.Builder - err = p.tmpl.ExecuteTemplate(&contents, contentTRef, &item) - if errors.Is(err, code.ErrSkipThisFile) { - // special case for CLI generation with `{{skipThisFile}}` - return nil - } - if err != nil { - return fmt.Errorf("exec %s: %w", contentTRef, err) - } - var childFilename strings.Builder - err = nt.Execute(&childFilename, item) - if err != nil { - return fmt.Errorf("exec %s: %w", nameT, err) - } - p.Filenames = append(p.Filenames, childFilename.String()) - if nameT == "stdout" { - // print something, usually instructions for any manual work - println(contents.String()) - return nil - } - targetFilename := filepath.Join(p.target, childFilename.String()) - _, err = os.Stat(targetFilename) - if errors.Is(err, fs.ErrNotExist) { - err = os.MkdirAll(path.Dir(targetFilename), 0o755) - if err != nil { - return fmt.Errorf("cannot create parent folders: %w", err) - } - } - file, err := os.OpenFile(targetFilename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0755) - if err != nil { - return fmt.Errorf("open %s: %w", targetFilename, err) - } - _, err = file.WriteString(contents.String()) - if err != nil { - return fmt.Errorf("write %s: %w", targetFilename, err) - } - return file.Close() -} - -func Formatter(ctx context.Context, target string, filenames []string, formatSpec string) error { - for _, formatter := range strings.Split(formatSpec, "&&") { - formatter = strings.TrimSpace(formatter) - logger.Infof(ctx, "Formatting: %s\n", formatter) - - formatter = strings.ReplaceAll(formatter, "$FILENAMES", - strings.Join(filenames, " ")) - split := strings.Split(formatter, " ") - - // create pipe to forward stdout and stderr to same fd, - // so that it's clear why formatter failed. - reader, writer := io.Pipe() - out := bytes.NewBuffer([]byte{}) - go io.Copy(out, reader) - defer reader.Close() - defer writer.Close() - - cmd := exec.Command(split[0], split[1:]...) - cmd.Dir = target - cmd.Stdout = writer - cmd.Stderr = writer - err := cmd.Run() - if err != nil { - return fmt.Errorf("%s:\n%s", formatter, out.Bytes()) - } - } - return nil -} diff --git a/openapi/roll/ast.go b/openapi/roll/ast.go deleted file mode 100644 index 07f326a71..000000000 --- a/openapi/roll/ast.go +++ /dev/null @@ -1,339 +0,0 @@ -package roll - -import ( - "strings" - - "github.com/databricks/databricks-sdk-go/openapi/code" -) - -type expression interface { - Type() string -} - -type traversable interface { - Traverse(func(expression)) -} - -type binaryExpr struct { - Left, Right expression - Op string -} - -func (b *binaryExpr) Traverse(cb func(expression)) { - cb(b.Left) - if t, ok := b.Left.(traversable); ok { - t.Traverse(cb) - } - cb(b.Right) - if t, ok := b.Right.(traversable); ok { - t.Traverse(cb) - } -} - -func (b *binaryExpr) Type() string { - return "binary" -} - -type indexExpr struct { - Left, Right expression -} - -func (i *indexExpr) Traverse(cb func(expression)) { - cb(i.Left) - if t, ok := i.Left.(traversable); ok { - t.Traverse(cb) - } - cb(i.Right) - if t, ok := i.Right.(traversable); ok { - t.Traverse(cb) - } -} - -func (i *indexExpr) Type() string { - return "index" -} - -// type boolean struct { -// Value bool -// } - -// func (b *boolean) Type() string { -// return "boolean" -// } - -type literal struct { - Value string -} - -func (l *literal) Type() string { - return "literal" -} - -type heredoc struct { - Value string -} - -func (l *heredoc) Type() string { - return "heredoc" -} - -type lookup struct { - X expression - Field *code.Named -} - -func (l *lookup) Variable() string { - switch x := l.X.(type) { - case *variable: - return x.Name - default: - return "" - } -} - -func (l *lookup) Traverse(cb func(expression)) { - cb(l.X) - if t, ok := l.X.(traversable); ok { - t.Traverse(cb) - } -} - -func (l *lookup) Type() string { - return "lookup" -} - -type variable struct { - code.Named -} - -func (v *variable) Type() string { - return "variable" -} - -type entity struct { - code.Named - Package string - FieldValues []*fieldValue - IsPointer bool -} - -func (e *entity) Traverse(cb func(expression)) { - for _, v := range e.FieldValues { - cb(v.Value) - if t, ok := v.Value.(traversable); ok { - t.Traverse(cb) - } - } -} - -func (e *entity) Type() string { - return "entity" -} - -type mapKV struct { - Key expression - Value expression -} - -type mapLiteral struct { - KeyType string - ValueType string - Pairs []mapKV -} - -func (e *mapLiteral) Type() string { - return "map" -} - -func (e *mapLiteral) Traverse(cb func(expression)) { - for _, v := range e.Pairs { - if t, ok := v.Key.(traversable); ok { - t.Traverse(cb) - } - if t, ok := v.Value.(traversable); ok { - t.Traverse(cb) - } - } -} - -type array struct { - code.Named - Package string - Values []expression -} - -func (a *array) Traverse(cb func(expression)) { - for _, v := range a.Values { - cb(v) - if t, ok := v.(traversable); ok { - t.Traverse(cb) - } - } -} - -func (a *array) Type() string { - return "array" -} - -type fieldValue struct { - code.Named - Value expression -} - -type call struct { - code.Named - IsAccount bool - Service *code.Named - Assign *code.Named - Args []expression - - // ID to avoid duplicates. alternative could be hashing, - // but implementation would grow more complex than needed. - id int - - // hint about the call creating an entity behind the variable - creates string -} - -func (c *call) IsDependentOn(other *call) bool { - if other.Assign == nil { - return false - } - result := []bool{false} - c.Traverse(func(e expression) { - v, ok := e.(*variable) - if !ok { - return - } - if other.Assign.CamelName() == v.CamelName() { - result[0] = true - return - } - }) - return result[0] -} - -func (c *call) IsWait() bool { - return strings.HasSuffix(c.Name, "AndWait") -} - -func (c *call) Request() (fv []*fieldValue) { - if strings.Contains(c.Name, "By") { - // E.g. DeleteByJobId, DeleteByClusterIdAndWait - firstSplit := strings.SplitN(c.Name, "By", 2) - // And is used to separate field names, but some methods end with AndWait - joinedFields := strings.TrimSuffix(firstSplit[1], "AndWait") - fields := strings.Split(joinedFields, "And") - for i, name := range fields { - fv = append(fv, &fieldValue{ - Named: code.Named{ - Name: name, - }, - Value: c.Args[i], - }) - } - return fv - } - if len(c.Args) == 0 { - return fv - } - e, ok := c.Args[0].(*entity) - if !ok { - return fv - } - return e.FieldValues -} - -func (c *call) Original() *code.Named { - name := c.CamelName() - name = strings.Split(name, "By")[0] - name = strings.TrimSuffix(name, "AndWait") - name = strings.TrimSuffix(name, "All") - return &code.Named{ - Name: name, - } -} - -func (c *call) OriginalName() string { - camel := c.CamelName() - camel = strings.Split(camel, "By")[0] - camel = strings.TrimSuffix(camel, "AndWait") - camel = strings.TrimSuffix(camel, "All") - return camel -} - -func (c *call) HasVariable(camelName string) bool { - // this assumes that v is already camelCased - tmp := []int{0} - c.Traverse(func(e expression) { - v, ok := e.(*variable) - if !ok { - return - } - if v.CamelName() == camelName { - tmp[0]++ - } - }) - return tmp[0] > 0 -} - -func (c *call) Traverse(cb func(expression)) { - for _, v := range c.Args { - cb(v) - if t, ok := v.(traversable); ok { - t.Traverse(cb) - } - } -} - -func (c *call) Type() string { - return "call" -} - -type initVar struct { - code.Named - Value expression -} - -type example struct { - code.Named - // TODO: add Method and Service - IsAccount bool - Calls []*call - Cleanup []*call - Asserts []expression - Init []*initVar - scope map[string]expression -} - -func (ex *example) FullName() string { - return ex.Name -} - -func (ex *example) findCall(svcCamelName, methodCamelName string) *call { - for _, v := range ex.Calls { - if v.Service == nil { - continue - } - if v.Service.CamelName() != svcCamelName { - continue - } - if v.OriginalName() != methodCamelName { - continue - } - return v - } - for _, v := range ex.Cleanup { - if v.Service == nil { - continue - } - if v.Service.CamelName() != svcCamelName { - continue - } - if v.OriginalName() != methodCamelName { - continue - } - return v - } - return nil -} diff --git a/openapi/roll/compare.go b/openapi/roll/compare.go deleted file mode 100644 index 90a8d7b09..000000000 --- a/openapi/roll/compare.go +++ /dev/null @@ -1,29 +0,0 @@ -package roll - -// This inlines the cmp package from Go 1.21 while we still support Go 1.19 and 1.20. -// Once we drop support for Go 1.19 and 1.20, we can remove this file and use the cmp package directly. - -type Ordered interface { - ~int | ~int8 | ~int16 | ~int32 | ~int64 | - ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | - ~float32 | ~float64 | - ~string -} - -func isNaN[T Ordered](x T) bool { - return x != x -} -func Compare[T Ordered](x, y T) int { - xNaN := isNaN(x) - yNaN := isNaN(y) - if xNaN && yNaN { - return 0 - } - if xNaN || x < y { - return -1 - } - if yNaN || x > y { - return +1 - } - return 0 -} diff --git a/openapi/roll/optimize.go b/openapi/roll/optimize.go deleted file mode 100644 index 64083519d..000000000 --- a/openapi/roll/optimize.go +++ /dev/null @@ -1,155 +0,0 @@ -package roll - -import ( - "strings" - - "github.com/databricks/databricks-sdk-go/openapi/code" -) - -type enum struct { - code.Named - Package string - Entity *code.Named - Content string -} - -func (e *enum) Type() string { - return "enum" -} - -func (s *Suite) OptimizeWithApiSpec(b *code.Batch) error { - o := &suiteOptimizer{b} - for _, e := range s.examples { - err := o.optimizeExample(e) - if err != nil { - return err - } - } - return nil -} - -type suiteOptimizer struct { - *code.Batch -} - -func (s *suiteOptimizer) optimizeExample(e *example) error { - for _, c := range e.Calls { - err := s.optimizeCall(c) - if err != nil { - return err - } - } - for _, c := range e.Cleanup { - err := s.optimizeCall(c) - if err != nil { - return err - } - } - return nil -} - -func (s *suiteOptimizer) optimizeCall(c *call) error { - for i := range c.Args { - err := s.optimizeExpression(&c.Args[i]) - if err != nil { - return err - } - } - return nil -} - -func (s *suiteOptimizer) enumConstant(l *lookup) expression { - potentialPackage := l.Variable() - potentialEnumValue := l.Field.PascalName() - for _, pkg := range s.Packages() { - if pkg.Name != potentialPackage { - continue - } - for _, v := range pkg.Types() { - if v.Schema != nil && !v.Schema.IsEnum() { - continue - } - prefix := v.PascalName() - if !strings.HasPrefix(potentialEnumValue, prefix) { - continue - } - value := strings.TrimPrefix(potentialEnumValue, prefix) - for _, e := range v.Enum() { - if e.PascalName() != value { - continue - } - return &enum{ - Package: potentialPackage, - Entity: &code.Named{ - Name: prefix, - }, - Named: code.Named{ - Name: e.Content, - }, - Content: e.Content, - } - } - } - } - return nil -} - -func (s *suiteOptimizer) optimizeExpression(e *expression) (err error) { - switch x := (*e).(type) { - case *call: - return s.optimizeCall(x) - case *lookup: - enumConstant := s.enumConstant(x) - if enumConstant != nil { - *e = enumConstant - return - } - return s.optimizeExpression(&x.X) - case *binaryExpr: - err = s.optimizeExpression(&x.Left) - if err != nil { - return err - } - err = s.optimizeExpression(&x.Right) - if err != nil { - return err - } - case *indexExpr: - err = s.optimizeExpression(&x.Left) - if err != nil { - return err - } - err = s.optimizeExpression(&x.Right) - if err != nil { - return err - } - case *entity: - for i := range x.FieldValues { - err = s.optimizeExpression(&x.FieldValues[i].Value) - if err != nil { - return err - } - } - case *mapLiteral: - for i := range x.Pairs { - err = s.optimizeExpression(&x.Pairs[i].Key) - if err != nil { - return err - } - err = s.optimizeExpression(&x.Pairs[i].Value) - if err != nil { - return err - } - } - case *array: - for i := range x.Values { - err = s.optimizeExpression(&x.Values[i]) - if err != nil { - return err - } - } - default: - return nil - } - return nil -} diff --git a/openapi/roll/tool.go b/openapi/roll/tool.go deleted file mode 100644 index 9acf159bb..000000000 --- a/openapi/roll/tool.go +++ /dev/null @@ -1,845 +0,0 @@ -package roll - -import ( - "fmt" - "go/ast" - "go/parser" - "go/token" - "os" - "path/filepath" - "strings" - - "github.com/databricks/databricks-sdk-go/openapi/code" - "github.com/databricks/databricks-sdk-go/service/compute" - "golang.org/x/exp/slices" -) - -func NewSuite(dirname string) (*Suite, error) { - fset := token.NewFileSet() - s := &Suite{ - fset: fset, - ServiceToPackage: map[string]string{}, - } - err := filepath.WalkDir(dirname, func(path string, info os.DirEntry, err error) error { - if err != nil { - return err - } - if info.IsDir() { - return nil - } - if strings.HasSuffix(path, "acceptance_test.go") { - // not transpilable - return nil - } - if strings.HasSuffix(path, "files_test.go") { - // not transpilable - return nil - } - if strings.HasSuffix(path, "workspaceconf_test.go") { - // not transpilable - return nil - } - file, err := parser.ParseFile(fset, path, nil, parser.ParseComments) - if err != nil { - return err - } - s.expectExamples(file) - return nil - }) - if err != nil { - return nil, err - } - err = s.parsePackages(dirname+"/../workspace_client.go", "WorkspaceClient") - if err != nil { - return nil, err - } - err = s.parsePackages(dirname+"/../account_client.go", "AccountClient") - if err != nil { - return nil, err - } - return s, nil -} - -type Suite struct { - fset *token.FileSet - ServiceToPackage map[string]string - examples []*example - counter int -} - -func (s *Suite) parsePackages(filename, client string) error { - file, err := parser.ParseFile(s.fset, filename, nil, 0) - if err != nil { - return err - } - spec, ok := file.Scope.Objects[client].Decl.(*ast.TypeSpec) - if !ok { - s.explainAndPanic("type spec", file.Scope.Objects[client].Decl) - } - structType, ok := spec.Type.(*ast.StructType) - if !ok { - s.explainAndPanic("struct type", spec.Type) - } - for _, f := range structType.Fields.List { - fieldName := f.Names[0].Name - selectorExpr, ok := f.Type.(*ast.SelectorExpr) - if !ok { - continue - } - apiName := selectorExpr.Sel.Name - if !strings.HasSuffix(apiName, "Interface") { - continue - } - s.ServiceToPackage[fieldName] = s.expectIdent(selectorExpr.X) - } - return nil -} - -func (s *Suite) FullName() string { - return "suite" -} - -type methodRef struct { - Pacakge, Service, Method string -} - -func (s *Suite) Methods() []methodRef { - found := map[methodRef]bool{} - for _, ex := range s.examples { - for _, v := range ex.Calls { - if v.Service == nil { - continue - } - if strings.HasSuffix(v.PascalName(), "IdMap") { - continue - } - found[methodRef{ - Pacakge: s.ServiceToPackage[v.Service.PascalName()], - Service: v.Service.CamelName(), - Method: v.OriginalName(), - }] = true - } - } - methods := []methodRef{} - for k := range found { - methods = append(methods, k) - } - slices.SortFunc(methods, func(a, b methodRef) int { - service := Compare(a.Service, b.Service) - if service != 0 { - return service - } - return Compare(a.Method, b.Method) - }) - return methods -} - -func (s *Suite) Samples() (out []*sample) { - for _, v := range s.Methods() { - out = append(out, s.usageSamples(v.Service, v.Method)...) - } - return out -} - -type serviceExample struct { - code.Named - Suite *Suite - Package string - Samples []*sample -} - -func (s *serviceExample) FullName() string { - return fmt.Sprintf("%s.%s", s.Package, s.PascalName()) -} - -func (s *Suite) ServicesExamples() (out []*serviceExample) { - samples := s.Samples() - for svc, pkg := range s.ServiceToPackage { - se := &serviceExample{ - Named: code.Named{ - Name: svc, - }, - Package: pkg, - Suite: s, - } - for _, v := range samples { - if v.Service.PascalName() != se.PascalName() { - continue - } - se.Samples = append(se.Samples, v) - } - slices.SortFunc(se.Samples, func(a, b *sample) int { - return Compare(a.FullName(), b.FullName()) - }) - out = append(out, se) - } - return out -} - -type sample struct { - example - Package string - Service *code.Named - Method *code.Named - Suite *Suite -} - -func (sa *sample) FullName() string { - return fmt.Sprintf("%s.%s", sa.Service.PascalName(), sa.Method.CamelName()) -} - -func (s *Suite) usageSamples(svc, mth string) (out []*sample) { - svcName := &code.Named{ - Name: svc, - } - methodName := &code.Named{ - Name: mth, - } - for _, ex := range s.examples { - c := ex.findCall(svcName.CamelName(), methodName.CamelName()) - if c == nil { - continue - } - sa := &sample{ - example: example{ - Named: ex.Named, - IsAccount: ex.IsAccount, - }, - Service: svcName, - Method: methodName, - Package: s.ServiceToPackage[svcName.PascalName()], - Suite: s, - } - out = append(out, sa) - variablesUsed := []string{} - queue := []expression{c} - added := map[string]bool{} - callIds := map[int]bool{} - for len(queue) > 0 { - current := queue[0] - queue = queue[1:] - switch x := current.(type) { - case *call: - if callIds[x.id] { - continue - } - if x.Assign != nil && x.Assign.Name != "_" { - variablesUsed = append(variablesUsed, x.Assign.CamelName()) - // call methods that may actually create an entity. - // executed before we append to sa.Calls, as we reverse - // the slice in the end - for _, v := range ex.Calls { - if v.creates != x.Assign.CamelName() { - continue - } - if callIds[v.id] { - continue - } - // put at the front of the queue - queue = append([]expression{v}, queue...) - } - } - x.IsAccount = ex.IsAccount - sa.Calls = append(sa.Calls, x) - callIds[x.id] = true - x.Traverse(func(e expression) { - v, ok := e.(*variable) - if !ok { - return - } - if added[v.CamelName()] { - // don't add the same variable twice - return - } - found, ok := ex.scope[v.CamelName()] - if ok { - queue = append(queue, found) - added[v.CamelName()] = true - return - } - for _, iv := range ex.Init { - if iv.CamelName() != v.CamelName() { - continue - } - sa.Init = append(sa.Init, iv) - return - } - }) - default: - panic("unsupported") - } - } - for _, v := range variablesUsed { - // TODO: also include ex.Asserts - for _, c := range ex.Cleanup { - if !c.HasVariable(v) { - continue - } - if callIds[c.id] { - continue - } - c.Traverse(func(e expression) { - v, ok := e.(*variable) - if !ok { - return - } - if added[v.CamelName()] { - // don't add the same variable twice - return - } - found, ok := ex.scope[v.CamelName()] - if !ok { - return - } - assignCall, ok := found.(*call) - if !ok { - // ideally, we could do multiple optimization passes - // to discover used variables also in cleanups, but - // we're not doing it for now. - return - } - if callIds[assignCall.id] { - return - } - sa.Calls = append(sa.Calls, assignCall) - callIds[assignCall.id] = true - }) - c.IsAccount = ex.IsAccount - sa.Cleanup = append(sa.Cleanup, c) - callIds[c.id] = true - } - } - slices.SortFunc(sa.Calls, func(a, b *call) int { - if a == b { - return 0 - } else if a.IsDependentOn(b) { - return -1 - } else { - return 1 - } - }) - reverse(sa.Calls) - reverse(sa.Cleanup) - } - return out -} - -func reverse[T any](s []T) { - for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { - s[i], s[j] = s[j], s[i] - } -} - -func (s *Suite) assignedNames(a *ast.AssignStmt) (names []string) { - for _, v := range a.Lhs { - ident, ok := v.(*ast.Ident) - if !ok { - continue - } - names = append(names, ident.Name) - } - return -} - -func (s *Suite) expectExamples(file *ast.File) { - for _, v := range file.Decls { - fn, ok := v.(*ast.FuncDecl) - if !ok { - continue - } - fnName := fn.Name.Name - if !strings.HasPrefix(fnName, "TestAcc") && - !strings.HasPrefix(fnName, "TestMws") && - !strings.HasPrefix(fnName, "TestUc") { - continue - } - if strings.HasSuffix(fnName, "NoTranspile") { - // Tests with NoTranspile suffix are too expensive to automatically - // translate, we just ignore them. - continue - } - s.examples = append(s.examples, s.expectFn(fn, file)) - } -} - -// Given a function declaration, return a map of statement index to comment -// immediately preceding the statement. -// -// Example: -// -// func foo() { -// // comment 1 -// bar() -// baz() -// // comment 2 -// baz() -// } -// -// Returns: -// -// map[int]string{ -// 0: "comment 1", -// 2: "comment 2", -// } -func (s *Suite) getCommentPrecedingStatementMap(fn *ast.FuncDecl, file *ast.File) map[int]string { - res := map[int]string{} - commentIndex := 0 - for _, cg := range file.Comments { - if cg.End() >= fn.Pos() { - break - } - commentIndex += 1 - } - for i, stmt := range fn.Body.List { - if commentIndex >= len(file.Comments) { - return res - } - commentGroup := file.Comments[commentIndex] - if stmt.Pos() > commentGroup.End() { - res[i] = strings.TrimSpace(commentGroup.Text()) - commentIndex += 1 - } - } - return res -} - -func (s *Suite) expectFn(fn *ast.FuncDecl, file *ast.File) *example { - testName := fn.Name.Name - testName = strings.TrimPrefix(testName, "TestAcc") - testName = strings.TrimPrefix(testName, "TestUcAcc") - testName = strings.TrimPrefix(testName, "TestMwsAcc") - ex := &example{ - Named: code.Named{ - Name: testName, - }, - scope: map[string]expression{}, - } - commentMap := s.getCommentPrecedingStatementMap(fn, file) - for i, v := range fn.Body.List { - hint := commentMap[i] - if hint == "skip-next-line-roll" { - switch node := v.(type) { - case *ast.ExprStmt: - if _, ok := node.X.(*ast.CallExpr); !ok { - buf := &strings.Builder{} - ast.Fprint(buf, s.fset, node, nil) - panic(fmt.Errorf("skip-next-line-roll can only be used immediately before plain function call with no LHS, found %s", buf.String())) - } - continue - default: - buf := &strings.Builder{} - ast.Fprint(buf, s.fset, node, nil) - panic(fmt.Errorf("skip-next-line-roll can only be used immediately before plain function call with no LHS, found %s", buf.String())) - } - } - switch stmt := v.(type) { - case *ast.AssignStmt: - s.expectAssign(ex, stmt, hint) - case *ast.DeferStmt: - ex.Cleanup = append(ex.Cleanup, s.expectCall(stmt.Call)) - case *ast.ExprStmt: - s.expectExprStmt(ex, stmt) - } - } - return ex -} - -var ignoreFns = map[string]bool{ - "SkipNow": true, - "NoError": true, - "Lock": true, - "Errorf": true, - "Skipf": true, - "Log": true, -} - -func (s *Suite) expectCleanup(ex *example, ce *ast.CallExpr) bool { - se, ok := ce.Fun.(*ast.SelectorExpr) - if !ok || se.Sel.Name != "Cleanup" { - return false - } - if len(ce.Args) == 0 { - return false - } - inlineFn, ok := ce.Args[0].(*ast.FuncLit) - if !ok { - return false - } - for _, v := range inlineFn.Body.List { - assign, ok := v.(*ast.AssignStmt) - if !ok { - continue - } - c := s.expectAssignCall(assign) - if c == nil { - continue - } - ex.Cleanup = append(ex.Cleanup, c) - } - return true -} - -func (s *Suite) expectExprStmt(ex *example, stmt *ast.ExprStmt) { - ce, ok := stmt.X.(*ast.CallExpr) - if !ok { - return - } - if s.expectCleanup(ex, ce) { - return - } - c := s.expectCall(stmt.X) - if ignoreFns[c.Name] { - return - } - assertions := map[string]string{ - "EqualError": "equalError", - "Contains": "contains", - "GreaterOrEqual": ">=", - "Greater": ">", - "Equal": "==", - "NotEqual": "!=", - } - op, ok := assertions[c.Name] - if ok { - ex.Asserts = append(ex.Asserts, &binaryExpr{ - Left: c.Args[0], - Op: op, - Right: c.Args[1], - }) - } else if c.Name == "NotEmpty" { - // TODO: replace code occurences with assert.True - ex.Asserts = append(ex.Asserts, &binaryExpr{ - Left: c.Args[0], - Op: "notEmpty", - Right: nil, - }) - } else if c.Name == "True" { - ex.Asserts = append(ex.Asserts, c.Args[0]) - } else { - s.explainAndPanic("known assertion", c) - } -} - -func (s *Suite) expectAssign(ex *example, stmt *ast.AssignStmt, hint string) { - names := s.assignedNames(stmt) - if len(names) == 2 && names[0] == "ctx" { - // w - workspace, a - account - ex.IsAccount = names[1] == "a" - return - } - switch x := stmt.Rhs[0].(type) { - case *ast.CallExpr: - c := s.expectAssignCall(stmt) - if c == nil { - return - } - if c.Assign != nil && c.Assign.Name != "_" { - ex.scope[c.Assign.CamelName()] = c - } - if strings.HasPrefix(hint, "creates ") { - c.creates = strings.TrimPrefix(hint, "creates ") - } - ex.Calls = append(ex.Calls, c) - case *ast.BasicLit: - lit := s.expectPrimitive(x) - ex.Init = append(ex.Init, &initVar{ - Named: code.Named{ - Name: names[0], - }, - Value: lit, - }) - } -} - -func (s *Suite) expectAssignCall(stmt *ast.AssignStmt) *call { - names := s.assignedNames(stmt) - c := s.expectCall(stmt.Rhs[0]) - if len(names) == 1 && names[0] != "err" { - c.Assign = &code.Named{ - Name: names[0], - } - } - if len(names) == 2 && names[1] == "err" { - c.Assign = &code.Named{ - Name: names[0], - } - } - return c -} - -func (s *Suite) expectIdent(e ast.Expr) string { - ident, ok := e.(*ast.Ident) - if !ok { - s.explainAndPanic("ident", e) - return "" - } - return ident.Name -} - -func (s *Suite) expectEntity(t *ast.SelectorExpr, cl *ast.CompositeLit) *entity { - ent := &entity{} - ent.Name = t.Sel.Name - ent.Package = s.expectIdent(t.X) - ent.FieldValues = s.expectFieldValues(cl.Elts) - return ent -} - -func (s *Suite) expectFieldValues(exprs []ast.Expr) (fvs []*fieldValue) { - for _, v := range exprs { - switch kv := v.(type) { - case *ast.KeyValueExpr: - fvs = append(fvs, &fieldValue{ - Named: code.Named{ - Name: s.expectIdent(kv.Key), - }, - Value: s.expectExpr(kv.Value), - }) - default: - s.explainAndPanic("field value", v) - return - } - } - return fvs -} - -func (s *Suite) expectArray(t *ast.ArrayType, cl *ast.CompositeLit) *array { - arr := &array{} - switch elt := t.Elt.(type) { - case *ast.SelectorExpr: - arr.Package = s.expectIdent(elt.X) - arr.Name = s.expectIdent(elt.Sel) - case *ast.Ident: - arr.Name = s.expectIdent(elt) - default: - s.explainAndPanic("array element", elt) - return nil - } - for _, v := range cl.Elts { - switch item := v.(type) { - case *ast.CompositeLit: - arr.Values = append(arr.Values, &entity{ - Named: code.Named{ - Name: arr.Name, - }, - Package: arr.Package, - FieldValues: s.expectFieldValues(item.Elts), - }) - default: - arr.Values = append(arr.Values, s.expectExpr(v)) - } - } - return arr -} - -func (s *Suite) expectMap(t *ast.MapType, cl *ast.CompositeLit) *mapLiteral { - m := &mapLiteral{ - KeyType: s.expectIdent(t.Key), - ValueType: s.expectIdent(t.Value), - } - for _, v := range cl.Elts { - kv, ok := v.(*ast.KeyValueExpr) - if !ok { - s.explainAndPanic("key value expr", v) - } - m.Pairs = append(m.Pairs, mapKV{ - Key: s.expectExpr(kv.Key), - Value: s.expectExpr(kv.Value), - }) - } - return m -} - -func (s *Suite) expectPrimitive(x *ast.BasicLit) expression { - // we directly translate literal values - if x.Value[0] == '`' { - txt := x.Value[1 : len(x.Value)-1] - return &heredoc{ - Value: compute.TrimLeadingWhitespace(txt), - } - } - return &literal{x.Value} -} - -func (s *Suite) expectCompositeLiteral(x *ast.CompositeLit) expression { - switch t := x.Type.(type) { - case *ast.SelectorExpr: - return s.expectEntity(t, x) - case *ast.ArrayType: - return s.expectArray(t, x) - case *ast.MapType: - return s.expectMap(t, x) - default: - s.explainAndPanic("composite lit type", t) - return nil - } -} - -func (s *Suite) expectExpr(e ast.Expr) expression { - switch x := e.(type) { - case *ast.BasicLit: - return s.expectPrimitive(x) - case *ast.CompositeLit: - return s.expectCompositeLiteral(x) - case *ast.UnaryExpr: - if x.Op != token.AND { - s.explainAndPanic("only references to composite literals are supported", x) - } - y, ok := x.X.(*ast.CompositeLit) - if !ok { - s.explainAndPanic("composite lit", x.X) - } - e, ok := s.expectCompositeLiteral(y).(*entity) - if !ok { - s.explainAndPanic("entity", x) - } - e.IsPointer = true - return e - case *ast.SelectorExpr: - return s.expectLookup(x) - case *ast.Ident: - return &variable{ - Named: code.Named{ - Name: x.Name, - }, - } - case *ast.CallExpr: - return s.expectCall(x) - case *ast.BinaryExpr: - return &binaryExpr{ - Left: s.expectExpr(x.X), - Right: s.expectExpr(x.Y), - Op: x.Op.String(), - } - case *ast.IndexExpr: - return &indexExpr{ - Left: s.expectExpr(x.X), - Right: s.expectExpr(x.Index), - } - default: - s.explainAndPanic("expr", e) - return nil - } -} - -func (s *Suite) explainAndPanic(expected string, x any) any { - ast.Print(s.fset, x) - panic("expected " + expected) -} - -func (s *Suite) expectLookup(se *ast.SelectorExpr) *lookup { - return &lookup{ - X: s.expectExpr(se.X), - Field: &code.Named{ - Name: s.expectIdent(se.Sel), - }, - } -} - -func (s *Suite) failOnBareRetrier(e *ast.CallExpr) { - t, ok := e.Fun.(*ast.IndexExpr) - if !ok { - return - } - t2, ok := t.X.(*ast.SelectorExpr) - if !ok { - return - } - if t2.X.(*ast.Ident).Name != "retries" { - return - } - if t2.Sel.Name == "New" { - s.explainAndPanic("cannot call retrier.New() without immediately calling Run() or Wait()", e) - } -} - -func (s *Suite) inlineRetryExpression(e *ast.CallExpr) *ast.CallExpr { - // TODO: support reusable Retriers in integration tests. - s.failOnBareRetrier(e) - t, ok := e.Fun.(*ast.SelectorExpr) - if !ok { - return e - } - name := t.Sel.Name - if name != "Run" && name != "Wait" { - return e - } - retryConstructor, ok := t.X.(*ast.CallExpr) - if !ok { - return e - } - retryIndexExpr, ok := retryConstructor.Fun.(*ast.IndexExpr) - if !ok { - return e - } - retrySelector, ok := retryIndexExpr.X.(*ast.SelectorExpr) - if !ok { - return e - } - if retrySelector.X.(*ast.Ident).Name != "retries" { - return e - } - - // inline the retry expression - retryFunc, ok := e.Args[1].(*ast.FuncLit) - if !ok { - s.explainAndPanic("function literal", e.Args[1]) - } - if len(retryFunc.Body.List) != 1 { - s.explainAndPanic(fmt.Sprintf("retry func provided to (*Retrier[T]) %s() must contain only a single return statement", name), retryFunc.Body) - } - retStmt, ok := retryFunc.Body.List[len(retryFunc.Body.List)-1].(*ast.ReturnStmt) - if !ok { - s.explainAndPanic("return statement", retryFunc.Body.List[len(retryFunc.Body.List)-1]) - } - inlinedCallExpr, ok := retStmt.Results[0].(*ast.CallExpr) - if !ok { - s.explainAndPanic("call expression", retStmt.Results[0]) - } - return inlinedCallExpr -} - -func (s *Suite) expectCall(e ast.Expr) *call { - ce, ok := e.(*ast.CallExpr) - if !ok { - s.explainAndPanic("call expr", e) - return nil - } - s.counter++ - c := &call{ - id: s.counter, - } - // If the call is actually a retry, we inline the returned value here - ce = s.inlineRetryExpression(ce) - switch t := ce.Fun.(type) { - case *ast.Ident: - c.Name = t.Name - case *ast.SelectorExpr: - c.Name = t.Sel.Name - switch se := t.X.(type) { - case *ast.SelectorExpr: - c.Service = &code.Named{ - Name: se.Sel.Name, - } - case *ast.Ident: - c.Service = &code.Named{ - Name: se.Name, - } - default: - s.explainAndPanic("selector expr", se) - return nil - } - } - if c.Service != nil && c.Service.Name == "fmt" { - // fmt.Sprintf is not a service - c.Service = nil - } - for _, v := range ce.Args { - arg := s.expectExpr(v) - if x, ok := arg.(*variable); ok && (x.Name == "ctx" || x.Name == "t") { - // context.Context is irrelevant in other languages than Go - continue - } - c.Args = append(c.Args, arg) - } - return c -} diff --git a/openapi/roll/tool_test.go b/openapi/roll/tool_test.go deleted file mode 100644 index fb7f97356..000000000 --- a/openapi/roll/tool_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package roll - -import ( - "context" - "os" - "path/filepath" - "testing" - - "github.com/databricks/databricks-sdk-go/openapi/code" - "github.com/databricks/databricks-sdk-go/openapi/render" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestLoadsFolder(t *testing.T) { - // ../../internal is the folder with integration tests - s, err := NewSuite("../../internal") - require.NoError(t, err) - - methods := s.Methods() - assert.True(t, len(methods) > 1) - - examples := s.ServicesExamples() - assert.True(t, len(examples) > 1) - - for _, v := range examples { - for _, sa := range v.Samples { - for _, ca := range sa.Calls { - // verify no panic - _ = ca.Original() - - // verify no panic - _ = ca.Request() - } - } - } -} - -func TestOptimize(t *testing.T) { - t.Skip() - ctx := context.Background() - home, _ := os.UserHomeDir() - batch, err := code.NewFromFile(ctx, filepath.Join(home, - "universe/bazel-bin/openapi/all-internal.json")) - require.NoError(t, err) - - s, err := NewSuite("../../internal") - require.NoError(t, err) - - err = s.OptimizeWithApiSpec(batch) - require.NoError(t, err) -} - -func TestRegenerateExamples(t *testing.T) { - t.Skip() // temporary measure - ctx := context.Background() - s, err := NewSuite("../../internal") - require.NoError(t, err) - - target := "../.." - pass := render.NewPass(target, s.ServicesExamples(), map[string]string{ - ".codegen/examples_test.go.tmpl": "service/{{.Package}}/{{.SnakeName}}_usage_test.go", - }, []string{}) - err = pass.Run(ctx) - assert.NoError(t, err) - - err = render.Formatter(ctx, target, pass.Filenames, "go fmt ./... && go run golang.org/x/tools/cmd/goimports@latest -w $FILENAMES") - assert.NoError(t, err) -} - -func TestRegeneratePythonExamples(t *testing.T) { - t.Skip() - ctx := context.Background() - s, err := NewSuite("../../internal") - require.NoError(t, err) - - target := "../../../databricks-sdk-py" - pass := render.NewPass(target, s.Samples(), map[string]string{ - ".codegen/example.py.tmpl": "examples/{{.Service.SnakeName}}/{{.Method.SnakeName}}_{{.SnakeName}}.py", - }, []string{}) - err = pass.Run(ctx) - assert.NoError(t, err) - - err = render.Formatter(ctx, target, pass.Filenames, "yapf -pri $FILENAMES && autoflake -i $FILENAMES && isort $FILENAMES") - assert.NoError(t, err) -} diff --git a/openapi/testdata/spec.json b/openapi/testdata/spec.json deleted file mode 100644 index 1c7ebd0c4..000000000 --- a/openapi/testdata/spec.json +++ /dev/null @@ -1,517 +0,0 @@ -{ - "openapi": "3.0.0", - "tags": [ - { - "name": "Command Execution", - "x-databricks-package": "commands", - "x-databricks-service": "CommandExecution" - } - ], - "paths": { - "/api/1.2/commands/cancel": { - "post": { - "operationId": "CommandExecution.cancel", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CancelCommand" - } - } - }, - "required": true - }, - "responses": { - "200": { - "headers": { - "content-type": { - "schema": { - "type": "string" - }, - "description": "The content type of the response." - }, - "last-modified": { - "schema": { "$ref": "#/components/schemas/ModificationTime" } - } - }, - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Status was returned successfully." - } - }, - "summary": "Cancel a command", - "tags": [ - "Command Execution" - ], - "x-databricks-wait": { - "bind": "commandId", - "failure": [ - "Error" - ], - "field": [ - "status" - ], - "message": [ - "results", - "cause" - ], - "poll": "commandStatus", - "success": [ - "Cancelled" - ] - } - } - }, - "/api/1.2/commands/execute": { - "post": { - "operationId": "CommandExecution.execute", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Command" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Created" - } - } - }, - "description": "Status was returned successfully." - } - }, - "summary": "Run a command", - "tags": [ - "Command Execution" - ], - "x-databricks-wait": { - "binding": { - "clusterId": { - "request": "clusterId" - }, - "commandId": { - "response": "id" - }, - "contextId": { - "request": "contextId" - } - }, - "failure": [ - "Cancelled", - "Cancelling" - ], - "field": [ - "status" - ], - "poll": "commandStatus", - "success": [ - "Finished", - "Error" - ] - } - } - }, - "/api/1.2/commands/status": { - "get": { - "operationId": "CommandExecution.commandStatus", - "parameters": [ - { - "in": "query", - "name": "clusterId", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "contextId", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "commandId", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CommandStatusResponse" - } - } - }, - "description": "Status was returned successfully." - } - }, - "summary": "Get information about a command", - "tags": [ - "Command Execution" - ] - } - }, - "/api/1.2/contexts/create": { - "post": { - "operationId": "CommandExecution.create", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateContext" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Created" - } - } - }, - "description": "Status was returned successfully." - } - }, - "summary": "Create an execution context", - "tags": [ - "Command Execution" - ], - "x-databricks-wait": { - "binding": { - "clusterId": { - "request": "clusterId" - }, - "contextId": { - "response": "id" - } - }, - "failure": [ - "Error" - ], - "field": [ - "status" - ], - "poll": "contextStatus", - "success": [ - "Running" - ] - } - } - }, - "/api/1.2/contexts/destroy": { - "post": { - "operationId": "CommandExecution.destroy", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/DestroyContext" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Status was returned successfully." - } - }, - "summary": "Delete an execution context", - "tags": [ - "Command Execution" - ] - } - }, - "/api/1.2/contexts/status": { - "get": { - "operationId": "CommandExecution.contextStatus", - "parameters": [ - { - "in": "query", - "name": "clusterId", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "contextId", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ContextStatusResponse" - } - } - }, - "description": "Status was returned successfully." - } - }, - "summary": "Get information about an execution context", - "tags": [ - "Command Execution" - ] - }, - "head": { - "operationId": "CommandExecution.headContextStatus", - "parameters": [ - { - "in": "query", - "name": "clusterId", - "required": true, - "schema": { - "type": "string" - } - }, - { - "in": "query", - "name": "contextId", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": {} - }, - "description": "Head returned succesfully" - } - }, - "summary": "Get head information about the context status", - "tags": [ - "Command Execution" - ] - } - } - }, - "components": { - "schemas": { - "CancelCommand": { - "properties": { - "clusterId": { - "type": "string" - }, - "commandId": { - "type": "string" - }, - "contextId": { - "type": "string" - } - }, - "type": "object" - }, - "Command": { - "properties": { - "clusterId": { - "description": "Running cluster id", - "type": "string" - }, - "command": { - "description": "Executable code", - "type": "string" - }, - "contextId": { - "description": "Running context id", - "type": "string" - }, - "language": { - "$ref": "#/components/schemas/Language" - } - }, - "type": "object" - }, - "CommandStatus": { - "enum": [ - "Cancelled", - "Cancelling", - "Error", - "Finished", - "Queued", - "Running" - ], - "type": "string" - }, - "CommandStatusResponse": { - "properties": { - "id": { - "type": "string" - }, - "results": { - "$ref": "#/components/schemas/Results" - }, - "status": { - "$ref": "#/components/schemas/CommandStatus" - } - }, - "type": "object" - }, - "ContextStatus": { - "enum": [ - "Running", - "Pending", - "Error" - ], - "type": "string" - }, - "ContextStatusResponse": { - "properties": { - "id": { - "type": "string" - }, - "status": { - "$ref": "#/components/schemas/ContextStatus" - } - }, - "type": "object" - }, - "CreateContext": { - "properties": { - "clusterId": { - "description": "Running cluster id", - "type": "string" - }, - "language": { - "$ref": "#/components/schemas/Language" - } - }, - "type": "object" - }, - "Created": { - "properties": { - "id": { - "type": "string" - } - }, - "type": "object" - }, - "DestroyContext": { - "properties": { - "clusterId": { - "type": "string" - }, - "contextId": { - "type": "string" - } - }, - "required": [ - "clusterId", - "contextId" - ], - "type": "object" - }, - "Language": { - "enum": [ - "python", - "scala", - "sql" - ], - "type": "string" - }, - "ModificationTime": { - "description": "Last modification time of given file in milliseconds since unix epoch.", - "type": "integer", - "format": "int64" - }, - "ResultType": { - "enum": [ - "error", - "image", - "images", - "table", - "text" - ], - "type": "string" - }, - "Results": { - "properties": { - "cause": { - "description": "The cause of the error", - "type": "string" - }, - "data": { - "type": "object", - "x-databricks-any": true - }, - "fileName": { - "description": "The image filename", - "type": "string" - }, - "fileNames": { - "items": { - "type": "string" - }, - "type": "array" - }, - "isJsonSchema": { - "description": "true if a JSON schema is returned instead of a string representation of the Hive type.", - "type": "boolean" - }, - "pos": { - "description": "internal field used by SDK", - "type": "integer" - }, - "resultType": { - "$ref": "#/components/schemas/ResultType" - }, - "schema": { - "description": "The table schema", - "items": { - "items": { - "type": "object", - "x-databricks-any": true - }, - "type": "array" - }, - "type": "array" - }, - "summary": { - "description": "The summary of the error", - "type": "string" - }, - "truncated": { - "description": "true if partial results are returned.", - "type": "boolean" - } - }, - "type": "object" - } - } - } -} \ No newline at end of file diff --git a/openapi/testdata/spec_dataplane.json b/openapi/testdata/spec_dataplane.json deleted file mode 100644 index c1e2594eb..000000000 --- a/openapi/testdata/spec_dataplane.json +++ /dev/null @@ -1,121 +0,0 @@ -{ - "openapi":"3.0.0", - "tags":[ - { - "name":"Model", - "x-databricks-package":"model", - "x-databricks-service":"Model" - } - ], - "paths":{ - "/api/1.2/model/{name}":{ - "get":{ - "operationId":"Model.get", - "parameters":[ - { - "name":"name", - "in":"path", - "required":true, - "schema":{ - "type":"string" - } - } - ], - "responses":{ - "200":{ - "content":{ - "application/json":{ - "schema":{ - "$ref":"#/components/schemas/Model" - } - } - }, - "description":"Model was returned successfully." - } - }, - "summary":"Get the model", - "tags":[ - "Model" - ] - } - }, - "/api/1.2/model-query/{name}":{ - "get":{ - "operationId":"Model.query", - "parameters":[ - { - "name":"name", - "in":"path", - "required":true, - "schema":{ - "type":"string" - } - } - ], - "responses":{ - "200":{ - "content":{ - "application/json":{ - - } - }, - "description":"Model was queried successfully." - } - }, - "summary":"Query the model", - "tags":[ - "Model" - ], - "x-databricks-dataplane":{ - "configMethod":"get", - "field":[ - "dataplaneInfo" - ] - }, - "x-databricks-wait":{ - "bind":"commandId", - "failure":[ - "Error" - ], - "field":[ - "status" - ], - "message":[ - "results", - "cause" - ], - "poll":"commandStatus", - "success":[ - "Cancelled" - ] - } - } - } - }, - "components":{ - "schemas":{ - "Model":{ - "type":"object", - "properties":{ - "name":{ - "type":"string" - }, - "dataplaneInfo":{ - "$ref":"#/components/schemas/DataPlaneInfo" - } - } - }, - "DataPlaneInfo":{ - "type":"object", - "properties":{ - "endpointUrl":{ - "type":"string" - }, - "authorizationDetails":{ - "type":"string" - } - } - } - } - } -} \ No newline at end of file diff --git a/openapi/testdata/spec_jobs_2.2.json b/openapi/testdata/spec_jobs_2.2.json deleted file mode 100644 index ff4d15035..000000000 --- a/openapi/testdata/spec_jobs_2.2.json +++ /dev/null @@ -1,90 +0,0 @@ -{ - "openapi": "3.0.0", - "tags": [ - { - "name": "Jobs", - "x-databricks-package": "jobs", - "x-databricks-service": "Jobs" - } - ], - "paths": { - "/api/2.2/jobs/get": { - "post": { - "operationId": "Jobs.get", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GetJobRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Status was returned successfully." - } - }, - "summary": "Get a job", - "tags": [ - "Jobs" - ] - } - }, - "/api/2.2/jobs/runs/submit": { - "post": { - "operationId": "Jobs.submitRun", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SubmitRunRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Status was returned successfully." - } - }, - "summary": "Submit a run", - "tags": [ - "Jobs" - ] - } - } - }, - "components": { - "schemas": { - "GetJobRequest": { - "properties": { - "jobId": { - "type": "string" - } - }, - "type": "object" - }, - "SubmitRunRequest": { - "properties": { - "jobId": { - "type": "string" - } - }, - "type": "object" - } - } - } -} \ No newline at end of file diff --git a/openapi/testdata/spec_subservices.json b/openapi/testdata/spec_subservices.json deleted file mode 100644 index 40866cbf3..000000000 --- a/openapi/testdata/spec_subservices.json +++ /dev/null @@ -1,271 +0,0 @@ -{ - "openapi": "3.0.0", - "tags": [ - { - "name": "Settings", - "x-databricks-package": "settings", - "x-databricks-service": "Settings" - }, - { - "name": "Default Namespace", - "x-databricks-package": "settings", - "x-databricks-service": "DefaultNamespace", - "x-databricks-parent-service": "Settings" - } - ], - "paths": { - "/api/1.2/commands/cancel": { - "post": { - "operationId": "DefaultNamespace.cancel", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CancelCommand" - } - } - }, - "required": true - }, - "responses": { - "200": { - "headers": { - "content-type": { - "schema": { - "type": "string" - }, - "description": "The content type of the response." - }, - "last-modified": { - "schema": { "$ref": "#/components/schemas/ModificationTime" } - } - }, - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Status was returned successfully." - } - }, - "summary": "Cancel a command", - "tags": [ - "Default Namespace" - ], - "x-databricks-wait": { - "bind": "commandId", - "failure": [ - "Error" - ], - "field": [ - "status" - ], - "message": [ - "results", - "cause" - ], - "poll": "commandStatus", - "success": [ - "Cancelled" - ] - } - } - } - }, - "components": { - "schemas": { - "CancelCommand": { - "properties": { - "clusterId": { - "type": "string" - }, - "commandId": { - "type": "string" - }, - "contextId": { - "type": "string" - } - }, - "type": "object" - }, - "Command": { - "properties": { - "clusterId": { - "description": "Running cluster id", - "type": "string" - }, - "command": { - "description": "Executable code", - "type": "string" - }, - "contextId": { - "description": "Running context id", - "type": "string" - }, - "language": { - "$ref": "#/components/schemas/Language" - } - }, - "type": "object" - }, - "CommandStatus": { - "enum": [ - "Cancelled", - "Cancelling", - "Error", - "Finished", - "Queued", - "Running" - ], - "type": "string" - }, - "CommandStatusResponse": { - "properties": { - "id": { - "type": "string" - }, - "results": { - "$ref": "#/components/schemas/Results" - }, - "status": { - "$ref": "#/components/schemas/CommandStatus" - } - }, - "type": "object" - }, - "ContextStatus": { - "enum": [ - "Running", - "Pending", - "Error" - ], - "type": "string" - }, - "ContextStatusResponse": { - "properties": { - "id": { - "type": "string" - }, - "status": { - "$ref": "#/components/schemas/ContextStatus" - } - }, - "type": "object" - }, - "CreateContext": { - "properties": { - "clusterId": { - "description": "Running cluster id", - "type": "string" - }, - "language": { - "$ref": "#/components/schemas/Language" - } - }, - "type": "object" - }, - "Created": { - "properties": { - "id": { - "type": "string" - } - }, - "type": "object" - }, - "DestroyContext": { - "properties": { - "clusterId": { - "type": "string" - }, - "contextId": { - "type": "string" - } - }, - "required": [ - "clusterId", - "contextId" - ], - "type": "object" - }, - "Language": { - "enum": [ - "python", - "scala", - "sql" - ], - "type": "string" - }, - "ModificationTime": { - "description": "Last modification time of given file in milliseconds since unix epoch.", - "type": "integer", - "format": "int64", - "x-databricks-terraform":{ - "alias": "new_name" - } - }, - "ResultType": { - "enum": [ - "error", - "image", - "images", - "table", - "text" - ], - "type": "string" - }, - "Results": { - "properties": { - "cause": { - "description": "The cause of the error", - "type": "string" - }, - "data": { - "type": "object", - "x-databricks-any": true - }, - "fileName": { - "description": "The image filename", - "type": "string" - }, - "fileNames": { - "items": { - "type": "string" - }, - "type": "array" - }, - "isJsonSchema": { - "description": "true if a JSON schema is returned instead of a string representation of the Hive type.", - "type": "boolean" - }, - "pos": { - "description": "internal field used by SDK", - "type": "integer" - }, - "resultType": { - "$ref": "#/components/schemas/ResultType" - }, - "schema": { - "description": "The table schema", - "items": { - "items": { - "type": "object", - "x-databricks-any": true - }, - "type": "array" - }, - "type": "array" - }, - "summary": { - "description": "The summary of the error", - "type": "string" - }, - "truncated": { - "description": "true if partial results are returned.", - "type": "boolean" - } - }, - "type": "object" - } - } - } -} \ No newline at end of file diff --git a/retries/retries.go b/retries/retries.go index a0ce9354b..100ac017d 100644 --- a/retries/retries.go +++ b/retries/retries.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" ) // Deprecated: use return types from non-*AndWait methods @@ -210,13 +210,13 @@ func (r Retrier[T]) Run(ctx context.Context, fn func(context.Context) (*T, error return entity, nil } if !r.config.ShouldRetry(err) { - logger.Debugf(ctx, "non-retriable error: %s", err) + log.DebugContext(ctx, "non-retriable error: %s", err) return nil, err } lastErr = err wait := r.config.Backoff(attempt) timer := time.NewTimer(wait) - logger.Tracef(ctx, "%s. Sleeping %s", + log.TraceContext(ctx, "%s. Sleeping %s", strings.TrimSuffix(err.Error(), "."), wait.Round(time.Millisecond)) select { diff --git a/service/billing/billable_usage_usage_test.go b/service/billing/billable_usage_usage_test.go index c5691bda9..7aec1e650 100755 --- a/service/billing/billable_usage_usage_test.go +++ b/service/billing/billable_usage_usage_test.go @@ -6,7 +6,7 @@ import ( "context" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/billing" ) @@ -25,6 +25,6 @@ func ExampleBillableUsageAPI_Download_usageDownload() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", resp) + log.InfoContext(ctx, "found %v", resp) } diff --git a/service/billing/budgets_usage_test.go b/service/billing/budgets_usage_test.go index da7b6cd8e..539c2984c 100755 --- a/service/billing/budgets_usage_test.go +++ b/service/billing/budgets_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/billing" ) @@ -47,7 +47,7 @@ func ExampleBudgetsAPI_Create_budgets() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -92,13 +92,13 @@ func ExampleBudgetsAPI_Get_budgets() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := a.Budgets.GetByBudgetId(ctx, created.Budget.BudgetConfigurationId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -120,7 +120,7 @@ func ExampleBudgetsAPI_ListAll_budgets() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -158,7 +158,7 @@ func ExampleBudgetsAPI_Update_budgets() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = a.Budgets.Update(ctx, billing.UpdateBudgetConfigurationRequest{ BudgetId: created.Budget.BudgetConfigurationId, diff --git a/service/billing/log_delivery_usage_test.go b/service/billing/log_delivery_usage_test.go index c5e9719f2..998316895 100755 --- a/service/billing/log_delivery_usage_test.go +++ b/service/billing/log_delivery_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/billing" "github.com/databricks/databricks-sdk-go/service/provisioning" @@ -31,7 +31,7 @@ func ExampleLogDeliveryAPI_Create_logDelivery() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", bucket) + log.InfoContext(ctx, "found %v", bucket) creds, err := a.Credentials.Create(ctx, provisioning.CreateCredentialRequest{ CredentialsName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -44,7 +44,7 @@ func ExampleLogDeliveryAPI_Create_logDelivery() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", creds) + log.InfoContext(ctx, "found %v", creds) created, err := a.LogDelivery.Create(ctx, billing.WrappedCreateLogDeliveryConfiguration{ LogDeliveryConfiguration: &billing.CreateLogDeliveryConfigurationParams{ @@ -58,7 +58,7 @@ func ExampleLogDeliveryAPI_Create_logDelivery() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -96,7 +96,7 @@ func ExampleLogDeliveryAPI_Get_logDelivery() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", bucket) + log.InfoContext(ctx, "found %v", bucket) creds, err := a.Credentials.Create(ctx, provisioning.CreateCredentialRequest{ CredentialsName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -109,7 +109,7 @@ func ExampleLogDeliveryAPI_Get_logDelivery() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", creds) + log.InfoContext(ctx, "found %v", creds) created, err := a.LogDelivery.Create(ctx, billing.WrappedCreateLogDeliveryConfiguration{ LogDeliveryConfiguration: &billing.CreateLogDeliveryConfigurationParams{ @@ -123,13 +123,13 @@ func ExampleLogDeliveryAPI_Get_logDelivery() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := a.LogDelivery.GetByLogDeliveryConfigurationId(ctx, created.LogDeliveryConfiguration.ConfigId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -162,6 +162,6 @@ func ExampleLogDeliveryAPI_ListAll_logDelivery() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } diff --git a/service/catalog/catalogs_usage_test.go b/service/catalog/catalogs_usage_test.go index ba634b8de..0734beba8 100755 --- a/service/catalog/catalogs_usage_test.go +++ b/service/catalog/catalogs_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" ) @@ -26,7 +26,7 @@ func ExampleCatalogsAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) // cleanup @@ -53,7 +53,7 @@ func ExampleCatalogsAPI_Create_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) // cleanup @@ -80,7 +80,7 @@ func ExampleCatalogsAPI_Create_catalogs() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -107,7 +107,7 @@ func ExampleCatalogsAPI_Create_catalogWorkspaceBindings() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -134,7 +134,7 @@ func ExampleCatalogsAPI_Create_schemas() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", newCatalog) + log.InfoContext(ctx, "found %v", newCatalog) // cleanup @@ -161,7 +161,7 @@ func ExampleCatalogsAPI_Create_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) // cleanup @@ -188,7 +188,7 @@ func ExampleCatalogsAPI_Get_catalogs() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Catalogs.GetByName(ctx, created.Name) if err != nil { @@ -218,7 +218,7 @@ func ExampleCatalogsAPI_ListAll_catalogs() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -235,7 +235,7 @@ func ExampleCatalogsAPI_Update_catalogs() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Catalogs.Update(ctx, catalog.UpdateCatalog{ Name: created.Name, @@ -270,7 +270,7 @@ func ExampleCatalogsAPI_Update_catalogWorkspaceBindings() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Catalogs.Update(ctx, catalog.UpdateCatalog{ Name: created.Name, diff --git a/service/catalog/connections_usage_test.go b/service/catalog/connections_usage_test.go index 0dbe892ff..1f19c096c 100755 --- a/service/catalog/connections_usage_test.go +++ b/service/catalog/connections_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" ) @@ -29,7 +29,7 @@ func ExampleConnectionsAPI_Create_connections() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", connCreate) + log.InfoContext(ctx, "found %v", connCreate) // cleanup @@ -58,7 +58,7 @@ func ExampleConnectionsAPI_Get_connections() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", connCreate) + log.InfoContext(ctx, "found %v", connCreate) connUpdate, err := w.Connections.Update(ctx, catalog.UpdateConnection{ Name: connCreate.Name, @@ -67,7 +67,7 @@ func ExampleConnectionsAPI_Get_connections() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", connUpdate) + log.InfoContext(ctx, "found %v", connUpdate) conn, err := w.Connections.Get(ctx, catalog.GetConnectionRequest{ Name: connUpdate.Name, @@ -75,7 +75,7 @@ func ExampleConnectionsAPI_Get_connections() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", conn) + log.InfoContext(ctx, "found %v", conn) // cleanup @@ -99,7 +99,7 @@ func ExampleConnectionsAPI_ListAll_connections() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", connList) + log.InfoContext(ctx, "found %v", connList) } @@ -119,7 +119,7 @@ func ExampleConnectionsAPI_Update_connections() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", connCreate) + log.InfoContext(ctx, "found %v", connCreate) connUpdate, err := w.Connections.Update(ctx, catalog.UpdateConnection{ Name: connCreate.Name, @@ -128,7 +128,7 @@ func ExampleConnectionsAPI_Update_connections() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", connUpdate) + log.InfoContext(ctx, "found %v", connUpdate) // cleanup diff --git a/service/catalog/external_locations_usage_test.go b/service/catalog/external_locations_usage_test.go index abfaddb64..40bf4df50 100755 --- a/service/catalog/external_locations_usage_test.go +++ b/service/catalog/external_locations_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" ) @@ -31,7 +31,7 @@ func ExampleExternalLocationsAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storageCredential) + log.InfoContext(ctx, "found %v", storageCredential) externalLocation, err := w.ExternalLocations.Create(ctx, catalog.CreateExternalLocation{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -42,7 +42,7 @@ func ExampleExternalLocationsAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", externalLocation) + log.InfoContext(ctx, "found %v", externalLocation) // cleanup @@ -73,7 +73,7 @@ func ExampleExternalLocationsAPI_Create_externalLocationsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", credential) + log.InfoContext(ctx, "found %v", credential) created, err := w.ExternalLocations.Create(ctx, catalog.CreateExternalLocation{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -83,7 +83,7 @@ func ExampleExternalLocationsAPI_Create_externalLocationsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -114,7 +114,7 @@ func ExampleExternalLocationsAPI_Get_externalLocationsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", credential) + log.InfoContext(ctx, "found %v", credential) created, err := w.ExternalLocations.Create(ctx, catalog.CreateExternalLocation{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -124,7 +124,7 @@ func ExampleExternalLocationsAPI_Get_externalLocationsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.ExternalLocations.GetByName(ctx, created.Name) if err != nil { @@ -155,7 +155,7 @@ func ExampleExternalLocationsAPI_ListAll_externalLocationsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -175,7 +175,7 @@ func ExampleExternalLocationsAPI_Update_externalLocationsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", credential) + log.InfoContext(ctx, "found %v", credential) created, err := w.ExternalLocations.Create(ctx, catalog.CreateExternalLocation{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -185,7 +185,7 @@ func ExampleExternalLocationsAPI_Update_externalLocationsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.ExternalLocations.Update(ctx, catalog.UpdateExternalLocation{ Name: created.Name, diff --git a/service/catalog/grants_usage_test.go b/service/catalog/grants_usage_test.go index b6b1fc19e..e5a778113 100755 --- a/service/catalog/grants_usage_test.go +++ b/service/catalog/grants_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" "github.com/databricks/databricks-sdk-go/service/sql" @@ -30,7 +30,7 @@ func ExampleGrantsAPI_GetEffective_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -39,7 +39,7 @@ func ExampleGrantsAPI_GetEffective_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) _, err = w.StatementExecution.ExecuteAndWait(ctx, sql.ExecuteStatementRequest{ WarehouseId: os.Getenv("TEST_DEFAULT_WAREHOUSE_ID"), @@ -57,13 +57,13 @@ func ExampleGrantsAPI_GetEffective_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdTable) + log.InfoContext(ctx, "found %v", createdTable) grants, err := w.Grants.GetEffectiveBySecurableTypeAndFullName(ctx, catalog.SecurableTypeTable, createdTable.FullName) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", grants) + log.InfoContext(ctx, "found %v", grants) // cleanup @@ -100,7 +100,7 @@ func ExampleGrantsAPI_Update_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -109,7 +109,7 @@ func ExampleGrantsAPI_Update_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) _, err = w.StatementExecution.ExecuteAndWait(ctx, sql.ExecuteStatementRequest{ WarehouseId: os.Getenv("TEST_DEFAULT_WAREHOUSE_ID"), @@ -129,7 +129,7 @@ func ExampleGrantsAPI_Update_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdTable) + log.InfoContext(ctx, "found %v", createdTable) x, err := w.Grants.Update(ctx, catalog.UpdatePermissions{ FullName: createdTable.FullName, @@ -142,7 +142,7 @@ func ExampleGrantsAPI_Update_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", x) + log.InfoContext(ctx, "found %v", x) // cleanup diff --git a/service/catalog/metastore_assignments_usage_test.go b/service/catalog/metastore_assignments_usage_test.go index b3c5b85c4..6c9abe26d 100755 --- a/service/catalog/metastore_assignments_usage_test.go +++ b/service/catalog/metastore_assignments_usage_test.go @@ -7,7 +7,7 @@ import ( "os" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" ) @@ -25,6 +25,6 @@ func ExampleMetastoreAssignmentsAPI_ListAll_metastoreAssignments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", ws) + log.InfoContext(ctx, "found %v", ws) } diff --git a/service/catalog/metastores_usage_test.go b/service/catalog/metastores_usage_test.go index 4c3752dfe..1c9e2b6aa 100755 --- a/service/catalog/metastores_usage_test.go +++ b/service/catalog/metastores_usage_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" ) @@ -37,7 +37,7 @@ func ExampleMetastoresAPI_Assign_metastores() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.Metastores.Assign(ctx, catalog.CreateMetastoreAssignment{ MetastoreId: created.MetastoreId, @@ -73,7 +73,7 @@ func ExampleMetastoresAPI_Create_metastores() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -98,7 +98,7 @@ func ExampleMetastoresAPI_Current_metastores() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", currentMetastore) + log.InfoContext(ctx, "found %v", currentMetastore) } @@ -116,7 +116,7 @@ func ExampleMetastoresAPI_Get_metastores() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Metastores.GetById(ctx, created.MetastoreId) if err != nil { @@ -146,7 +146,7 @@ func ExampleMetastoresAPI_ListAll_metastores() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -161,7 +161,7 @@ func ExampleMetastoresAPI_Summary_metastores() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", summary) + log.InfoContext(ctx, "found %v", summary) } @@ -187,7 +187,7 @@ func ExampleMetastoresAPI_Unassign_metastores() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.Metastores.Unassign(ctx, catalog.UnassignRequest{ MetastoreId: created.MetastoreId, @@ -223,7 +223,7 @@ func ExampleMetastoresAPI_Update_metastores() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Metastores.Update(ctx, catalog.UpdateMetastore{ Id: created.MetastoreId, diff --git a/service/catalog/schemas_usage_test.go b/service/catalog/schemas_usage_test.go index 4807b237b..28de74cd1 100755 --- a/service/catalog/schemas_usage_test.go +++ b/service/catalog/schemas_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" ) @@ -26,7 +26,7 @@ func ExampleSchemasAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -35,7 +35,7 @@ func ExampleSchemasAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) // cleanup @@ -66,7 +66,7 @@ func ExampleSchemasAPI_Create_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -75,7 +75,7 @@ func ExampleSchemasAPI_Create_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) // cleanup @@ -106,7 +106,7 @@ func ExampleSchemasAPI_Create_schemas() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", newCatalog) + log.InfoContext(ctx, "found %v", newCatalog) created, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -115,7 +115,7 @@ func ExampleSchemasAPI_Create_schemas() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -146,7 +146,7 @@ func ExampleSchemasAPI_Create_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -155,7 +155,7 @@ func ExampleSchemasAPI_Create_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) // cleanup @@ -186,7 +186,7 @@ func ExampleSchemasAPI_Get_schemas() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", newCatalog) + log.InfoContext(ctx, "found %v", newCatalog) created, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -195,7 +195,7 @@ func ExampleSchemasAPI_Get_schemas() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Schemas.GetByFullName(ctx, created.FullName) if err != nil { @@ -231,7 +231,7 @@ func ExampleSchemasAPI_ListAll_schemas() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", newCatalog) + log.InfoContext(ctx, "found %v", newCatalog) all, err := w.Schemas.ListAll(ctx, catalog.ListSchemasRequest{ CatalogName: newCatalog.Name, @@ -239,7 +239,7 @@ func ExampleSchemasAPI_ListAll_schemas() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) // cleanup @@ -266,7 +266,7 @@ func ExampleSchemasAPI_Update_schemas() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", newCatalog) + log.InfoContext(ctx, "found %v", newCatalog) created, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -275,7 +275,7 @@ func ExampleSchemasAPI_Update_schemas() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Schemas.Update(ctx, catalog.UpdateSchema{ FullName: created.FullName, diff --git a/service/catalog/storage_credentials_usage_test.go b/service/catalog/storage_credentials_usage_test.go index 132ff8c65..95c95aaf9 100755 --- a/service/catalog/storage_credentials_usage_test.go +++ b/service/catalog/storage_credentials_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" ) @@ -31,7 +31,7 @@ func ExampleStorageCredentialsAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storageCredential) + log.InfoContext(ctx, "found %v", storageCredential) // cleanup @@ -58,7 +58,7 @@ func ExampleStorageCredentialsAPI_Create_storageCredentialsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -85,7 +85,7 @@ func ExampleStorageCredentialsAPI_Create_externalLocationsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", credential) + log.InfoContext(ctx, "found %v", credential) // cleanup @@ -112,13 +112,13 @@ func ExampleStorageCredentialsAPI_Get_storageCredentialsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byName, err := w.StorageCredentials.GetByName(ctx, created.Name) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byName) + log.InfoContext(ctx, "found %v", byName) // cleanup @@ -140,7 +140,7 @@ func ExampleStorageCredentialsAPI_ListAll_storageCredentialsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -160,7 +160,7 @@ func ExampleStorageCredentialsAPI_Update_storageCredentialsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.StorageCredentials.Update(ctx, catalog.UpdateStorageCredential{ Name: created.Name, diff --git a/service/catalog/tables_usage_test.go b/service/catalog/tables_usage_test.go index 6bfc77296..9df52329d 100755 --- a/service/catalog/tables_usage_test.go +++ b/service/catalog/tables_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" "github.com/databricks/databricks-sdk-go/service/sql" @@ -30,7 +30,7 @@ func ExampleTablesAPI_Get_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -39,7 +39,7 @@ func ExampleTablesAPI_Get_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) _, err = w.StatementExecution.ExecuteAndWait(ctx, sql.ExecuteStatementRequest{ WarehouseId: os.Getenv("TEST_DEFAULT_WAREHOUSE_ID"), @@ -57,7 +57,7 @@ func ExampleTablesAPI_Get_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdTable) + log.InfoContext(ctx, "found %v", createdTable) // cleanup @@ -92,7 +92,7 @@ func ExampleTablesAPI_ListAll_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -101,7 +101,7 @@ func ExampleTablesAPI_ListAll_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) allTables, err := w.Tables.ListAll(ctx, catalog.ListTablesRequest{ CatalogName: createdCatalog.Name, @@ -110,7 +110,7 @@ func ExampleTablesAPI_ListAll_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", allTables) + log.InfoContext(ctx, "found %v", allTables) // cleanup @@ -141,7 +141,7 @@ func ExampleTablesAPI_ListSummaries_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -150,7 +150,7 @@ func ExampleTablesAPI_ListSummaries_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) summaries, err := w.Tables.ListSummariesAll(ctx, catalog.ListSummariesRequest{ CatalogName: createdCatalog.Name, @@ -159,7 +159,7 @@ func ExampleTablesAPI_ListSummaries_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", summaries) + log.InfoContext(ctx, "found %v", summaries) // cleanup diff --git a/service/catalog/volumes_usage_test.go b/service/catalog/volumes_usage_test.go index ddbfdce42..7722d0572 100755 --- a/service/catalog/volumes_usage_test.go +++ b/service/catalog/volumes_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" ) @@ -31,7 +31,7 @@ func ExampleVolumesAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storageCredential) + log.InfoContext(ctx, "found %v", storageCredential) externalLocation, err := w.ExternalLocations.Create(ctx, catalog.CreateExternalLocation{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -42,7 +42,7 @@ func ExampleVolumesAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", externalLocation) + log.InfoContext(ctx, "found %v", externalLocation) createdCatalog, err := w.Catalogs.Create(ctx, catalog.CreateCatalog{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -50,7 +50,7 @@ func ExampleVolumesAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -59,7 +59,7 @@ func ExampleVolumesAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) createdVolume, err := w.Volumes.Create(ctx, catalog.CreateVolumeRequestContent{ CatalogName: createdCatalog.Name, @@ -71,7 +71,7 @@ func ExampleVolumesAPI_Create_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdVolume) + log.InfoContext(ctx, "found %v", createdVolume) // cleanup @@ -114,7 +114,7 @@ func ExampleVolumesAPI_ListAll_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -123,7 +123,7 @@ func ExampleVolumesAPI_ListAll_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) allVolumes, err := w.Volumes.ListAll(ctx, catalog.ListVolumesRequest{ CatalogName: createdCatalog.Name, @@ -132,7 +132,7 @@ func ExampleVolumesAPI_ListAll_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", allVolumes) + log.InfoContext(ctx, "found %v", allVolumes) // cleanup @@ -167,7 +167,7 @@ func ExampleVolumesAPI_Read_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storageCredential) + log.InfoContext(ctx, "found %v", storageCredential) externalLocation, err := w.ExternalLocations.Create(ctx, catalog.CreateExternalLocation{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -178,7 +178,7 @@ func ExampleVolumesAPI_Read_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", externalLocation) + log.InfoContext(ctx, "found %v", externalLocation) createdCatalog, err := w.Catalogs.Create(ctx, catalog.CreateCatalog{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -186,7 +186,7 @@ func ExampleVolumesAPI_Read_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -195,7 +195,7 @@ func ExampleVolumesAPI_Read_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) createdVolume, err := w.Volumes.Create(ctx, catalog.CreateVolumeRequestContent{ CatalogName: createdCatalog.Name, @@ -207,13 +207,13 @@ func ExampleVolumesAPI_Read_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdVolume) + log.InfoContext(ctx, "found %v", createdVolume) loadedVolume, err := w.Volumes.ReadByName(ctx, createdVolume.FullName) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", loadedVolume) + log.InfoContext(ctx, "found %v", loadedVolume) // cleanup @@ -260,7 +260,7 @@ func ExampleVolumesAPI_Update_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storageCredential) + log.InfoContext(ctx, "found %v", storageCredential) externalLocation, err := w.ExternalLocations.Create(ctx, catalog.CreateExternalLocation{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -271,7 +271,7 @@ func ExampleVolumesAPI_Update_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", externalLocation) + log.InfoContext(ctx, "found %v", externalLocation) createdCatalog, err := w.Catalogs.Create(ctx, catalog.CreateCatalog{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -279,7 +279,7 @@ func ExampleVolumesAPI_Update_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -288,7 +288,7 @@ func ExampleVolumesAPI_Update_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) createdVolume, err := w.Volumes.Create(ctx, catalog.CreateVolumeRequestContent{ CatalogName: createdCatalog.Name, @@ -300,13 +300,13 @@ func ExampleVolumesAPI_Update_volumes() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdVolume) + log.InfoContext(ctx, "found %v", createdVolume) loadedVolume, err := w.Volumes.ReadByName(ctx, createdVolume.FullName) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", loadedVolume) + log.InfoContext(ctx, "found %v", loadedVolume) _, err = w.Volumes.Update(ctx, catalog.UpdateVolumeRequestContent{ Name: loadedVolume.FullName, diff --git a/service/catalog/workspace_bindings_usage_test.go b/service/catalog/workspace_bindings_usage_test.go index aab4999b2..1cbbf5aaa 100755 --- a/service/catalog/workspace_bindings_usage_test.go +++ b/service/catalog/workspace_bindings_usage_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" ) @@ -28,13 +28,13 @@ func ExampleWorkspaceBindingsAPI_Get_catalogWorkspaceBindings() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) bindings, err := w.WorkspaceBindings.GetByName(ctx, created.Name) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", bindings) + log.InfoContext(ctx, "found %v", bindings) // cleanup @@ -69,7 +69,7 @@ func ExampleWorkspaceBindingsAPI_Update_catalogWorkspaceBindings() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.WorkspaceBindings.Update(ctx, catalog.UpdateWorkspaceBindings{ Name: created.Name, diff --git a/service/compute/cluster_policies_usage_test.go b/service/compute/cluster_policies_usage_test.go index 207077560..049830eb1 100755 --- a/service/compute/cluster_policies_usage_test.go +++ b/service/compute/cluster_policies_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/compute" ) @@ -33,7 +33,7 @@ func ExampleClusterPoliciesAPI_Create_clusterPolicies() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -64,13 +64,13 @@ func ExampleClusterPoliciesAPI_Edit_clusterPolicies() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) policy, err := w.ClusterPolicies.GetByPolicyId(ctx, created.PolicyId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", policy) + log.InfoContext(ctx, "found %v", policy) err = w.ClusterPolicies.Edit(ctx, compute.EditPolicy{ PolicyId: policy.PolicyId, @@ -116,13 +116,13 @@ func ExampleClusterPoliciesAPI_Get_clusterPolicies() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) policy, err := w.ClusterPolicies.GetByPolicyId(ctx, created.PolicyId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", policy) + log.InfoContext(ctx, "found %v", policy) // cleanup @@ -144,6 +144,6 @@ func ExampleClusterPoliciesAPI_ListAll_clusterPolicies() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } diff --git a/service/compute/clusters_usage_test.go b/service/compute/clusters_usage_test.go index d2b1e6aed..4f6ee0b1a 100755 --- a/service/compute/clusters_usage_test.go +++ b/service/compute/clusters_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/compute" "github.com/databricks/databricks-sdk-go/service/iam" @@ -29,7 +29,7 @@ func ExampleClustersAPI_ChangeOwner_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clusterName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -39,7 +39,7 @@ func ExampleClustersAPI_ChangeOwner_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", otherOwner) + log.InfoContext(ctx, "found %v", otherOwner) clstr, err := w.Clusters.CreateAndWait(ctx, compute.CreateCluster{ ClusterName: clusterName, @@ -51,7 +51,7 @@ func ExampleClustersAPI_ChangeOwner_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) err = w.Clusters.ChangeOwner(ctx, compute.ChangeClusterOwner{ ClusterId: clstr.ClusterId, @@ -88,7 +88,7 @@ func ExampleClustersAPI_Create_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clusterName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -102,7 +102,7 @@ func ExampleClustersAPI_Create_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) // cleanup @@ -127,7 +127,7 @@ func ExampleClustersAPI_Delete_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clusterName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -141,7 +141,7 @@ func ExampleClustersAPI_Delete_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) _, err = w.Clusters.DeleteByClusterIdAndWait(ctx, clstr.ClusterId) if err != nil { @@ -173,7 +173,7 @@ func ExampleClustersAPI_Edit_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clstr, err := w.Clusters.CreateAndWait(ctx, compute.CreateCluster{ ClusterName: clusterName, @@ -185,7 +185,7 @@ func ExampleClustersAPI_Edit_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) _, err = w.Clusters.EditAndWait(ctx, compute.EditCluster{ ClusterId: clstr.ClusterId, @@ -224,7 +224,7 @@ func ExampleClustersAPI_EnsureClusterIsRunning_commandsDirectUsage() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", context) + log.InfoContext(ctx, "found %v", context) err = w.Clusters.EnsureClusterIsRunning(ctx, clusterId) if err != nil { @@ -257,7 +257,7 @@ func ExampleClustersAPI_Events_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clusterName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -271,7 +271,7 @@ func ExampleClustersAPI_Events_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) events, err := w.Clusters.EventsAll(ctx, compute.GetEvents{ ClusterId: clstr.ClusterId, @@ -279,7 +279,7 @@ func ExampleClustersAPI_Events_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", events) + log.InfoContext(ctx, "found %v", events) // cleanup @@ -304,7 +304,7 @@ func ExampleClustersAPI_Get_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clusterName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -318,13 +318,13 @@ func ExampleClustersAPI_Get_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) byId, err := w.Clusters.GetByClusterId(ctx, clstr.ClusterId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -346,7 +346,7 @@ func ExampleClustersAPI_ListAll_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -361,7 +361,7 @@ func ExampleClustersAPI_ListNodeTypes_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", nodes) + log.InfoContext(ctx, "found %v", nodes) } @@ -379,7 +379,7 @@ func ExampleClustersAPI_Pin_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clusterName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -393,7 +393,7 @@ func ExampleClustersAPI_Pin_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) err = w.Clusters.PinByClusterId(ctx, clstr.ClusterId) if err != nil { @@ -423,7 +423,7 @@ func ExampleClustersAPI_Resize_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clusterName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -437,7 +437,7 @@ func ExampleClustersAPI_Resize_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) byId, err := w.Clusters.ResizeAndWait(ctx, compute.ResizeCluster{ ClusterId: clstr.ClusterId, @@ -446,7 +446,7 @@ func ExampleClustersAPI_Resize_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -471,7 +471,7 @@ func ExampleClustersAPI_Restart_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clusterName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -485,7 +485,7 @@ func ExampleClustersAPI_Restart_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) _, err = w.Clusters.RestartAndWait(ctx, compute.RestartCluster{ ClusterId: clstr.ClusterId, @@ -516,7 +516,7 @@ func ExampleClustersAPI_SelectNodeType_instancePools() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", smallest) + log.InfoContext(ctx, "found %v", smallest) } @@ -534,7 +534,7 @@ func ExampleClustersAPI_SelectSparkVersion_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) } @@ -552,7 +552,7 @@ func ExampleClustersAPI_Start_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clusterName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -566,7 +566,7 @@ func ExampleClustersAPI_Start_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) _, err = w.Clusters.StartByClusterIdAndWait(ctx, clstr.ClusterId) if err != nil { @@ -596,7 +596,7 @@ func ExampleClustersAPI_Unpin_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", latest) + log.InfoContext(ctx, "found %v", latest) clusterName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -610,7 +610,7 @@ func ExampleClustersAPI_Unpin_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", clstr) + log.InfoContext(ctx, "found %v", clstr) err = w.Clusters.UnpinByClusterId(ctx, clstr.ClusterId) if err != nil { diff --git a/service/compute/command_execution_usage_test.go b/service/compute/command_execution_usage_test.go index e2fa0916a..be86e25d6 100755 --- a/service/compute/command_execution_usage_test.go +++ b/service/compute/command_execution_usage_test.go @@ -7,7 +7,7 @@ import ( "os" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/compute" ) @@ -28,7 +28,7 @@ func ExampleCommandExecutionAPI_Create_commandsDirectUsage() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", context) + log.InfoContext(ctx, "found %v", context) // cleanup @@ -58,7 +58,7 @@ func ExampleCommandExecutionAPI_Execute_commandsDirectUsage() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", context) + log.InfoContext(ctx, "found %v", context) textResults, err := w.CommandExecution.ExecuteAndWait(ctx, compute.Command{ ClusterId: clusterId, @@ -69,7 +69,7 @@ func ExampleCommandExecutionAPI_Execute_commandsDirectUsage() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", textResults) + log.InfoContext(ctx, "found %v", textResults) // cleanup @@ -96,6 +96,6 @@ func ExampleCommandExecutionAPI_Start_commands() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", commandContext) + log.InfoContext(ctx, "found %v", commandContext) } diff --git a/service/compute/ext_commands.go b/service/compute/ext_commands.go index 2acfcd15e..af3fb4934 100644 --- a/service/compute/ext_commands.go +++ b/service/compute/ext_commands.go @@ -5,7 +5,7 @@ import ( "fmt" "github.com/databricks/databricks-sdk-go/client" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/useragent" ) @@ -121,7 +121,7 @@ func (a *CommandsHighLevelAPI) Execute(ctx context.Context, clusterID, language, } } commandStr = TrimLeadingWhitespace(commandStr) - logger.Debugf(ctx, "Executing %s command on %s:\n%s", language, clusterID, commandStr) + log.DebugContext(ctx, "Executing %s command on %s:\n%s", language, clusterID, commandStr) context, err := a.execution.CreateAndWait(ctx, CreateContext{ ClusterId: clusterID, Language: Language(language), @@ -149,7 +149,7 @@ func (a *CommandsHighLevelAPI) Execute(ctx context.Context, clusterID, language, } } if command.Results == nil { - logger.Warnf(ctx, "Command has no results: %#v", command) + log.WarningContext(ctx, "Command has no results: %#v", command) return Results{ ResultType: "error", Summary: "Command has no results", diff --git a/service/compute/ext_library_utilities.go b/service/compute/ext_library_utilities.go index 702cd115f..98c97b70e 100644 --- a/service/compute/ext_library_utilities.go +++ b/service/compute/ext_library_utilities.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go/databricks/apierr" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/retries" "github.com/databricks/databricks-sdk-go/useragent" ) @@ -198,7 +198,7 @@ func (a *LibrariesAPI) Wait(ctx context.Context, wait Wait, return nil, retries.Halt(err) } if !wait.IsRunning { - logger.Infof(ctx, "Cluster %s is currently not running, so just returning list of %d libraries", + log.InfoContext(ctx, "Cluster %s is currently not running, so just returning list of %d libraries", wait.ClusterID, len(status.LibraryStatuses)) return status, nil } @@ -223,7 +223,7 @@ func (a *LibrariesAPI) Wait(ctx context.Context, wait Wait, // cleanup libraries that failed to install for _, v := range result.LibraryStatuses { if v.Status == "FAILED" { - logger.Warnf(ctx, "Removing failed library %s from %s", + log.WarningContext(ctx, "Removing failed library %s from %s", v.Library, wait.ClusterID) cleanup.Libraries = append(cleanup.Libraries, *v.Library) continue diff --git a/service/compute/ext_utilities.go b/service/compute/ext_utilities.go index ecb3c8542..740c56203 100644 --- a/service/compute/ext_utilities.go +++ b/service/compute/ext_utilities.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go/databricks/apierr" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/retries" ) @@ -83,7 +83,7 @@ func (a *ClustersAPI) EnsureClusterIsRunning(ctx context.Context, clusterId stri err := a.startClusterIfNeeded(ctx, clusterId, timeout) var apiErr *apierr.APIError if errors.As(err, &apiErr) && apiErr.ErrorCode == "INVALID_STATE" { - logger.Debugf(ctx, "Cluster was started by other process: %s Retrying.", apiErr.Message) + log.DebugContext(ctx, "Cluster was started by other process: %s Retrying.", apiErr.Message) return retries.Continue(apiErr) } if a.isErrFailedToReach(err) { @@ -112,13 +112,13 @@ func (a *ClustersAPI) GetOrCreateRunningCluster(ctx context.Context, name string if cl.ClusterName != name { continue } - logger.Infof(ctx, "Found reusable cluster '%s'", name) + log.InfoContext(ctx, "Found reusable cluster '%s'", name) if cl.IsRunningOrResizing() { return &cl, nil } started, err := a.StartByClusterIdAndWait(ctx, cl.ClusterId) if err != nil { - logger.Infof(ctx, "Cluster %s cannot be started, creating an autoterminating cluster: %s", name, err) + log.InfoContext(ctx, "Cluster %s cannot be started, creating an autoterminating cluster: %s", name, err) break } return started, nil @@ -133,7 +133,7 @@ func (a *ClustersAPI) GetOrCreateRunningCluster(ctx context.Context, name string if err != nil { return nil, err } - logger.Infof(ctx, "Creating an autoterminating cluster with node type %s", smallestNodeType) + log.InfoContext(ctx, "Creating an autoterminating cluster with node type %s", smallestNodeType) versions, err := a.SparkVersions(ctx) if err != nil { return nil, fmt.Errorf("list spark versions: %w", err) diff --git a/service/compute/global_init_scripts_usage_test.go b/service/compute/global_init_scripts_usage_test.go index 01f1b79af..e6a533c88 100755 --- a/service/compute/global_init_scripts_usage_test.go +++ b/service/compute/global_init_scripts_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/compute" ) @@ -30,7 +30,7 @@ func ExampleGlobalInitScriptsAPI_Create_globalInitScripts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -57,13 +57,13 @@ func ExampleGlobalInitScriptsAPI_Get_globalInitScripts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := w.GlobalInitScripts.GetByScriptId(ctx, created.ScriptId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -85,7 +85,7 @@ func ExampleGlobalInitScriptsAPI_ListAll_globalInitScripts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -105,7 +105,7 @@ func ExampleGlobalInitScriptsAPI_Update_globalInitScripts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.GlobalInitScripts.Update(ctx, compute.GlobalInitScriptUpdateRequest{ ScriptId: created.ScriptId, diff --git a/service/compute/instance_pools_usage_test.go b/service/compute/instance_pools_usage_test.go index e2dfe9ba1..19995054e 100755 --- a/service/compute/instance_pools_usage_test.go +++ b/service/compute/instance_pools_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/compute" ) @@ -26,7 +26,7 @@ func ExampleInstancePoolsAPI_Create_instancePools() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", smallest) + log.InfoContext(ctx, "found %v", smallest) created, err := w.InstancePools.Create(ctx, compute.CreateInstancePool{ InstancePoolName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -35,7 +35,7 @@ func ExampleInstancePoolsAPI_Create_instancePools() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -59,7 +59,7 @@ func ExampleInstancePoolsAPI_Edit_instancePools() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", smallest) + log.InfoContext(ctx, "found %v", smallest) created, err := w.InstancePools.Create(ctx, compute.CreateInstancePool{ InstancePoolName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -68,7 +68,7 @@ func ExampleInstancePoolsAPI_Edit_instancePools() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.InstancePools.Edit(ctx, compute.EditInstancePool{ InstancePoolId: created.InstancePoolId, @@ -101,7 +101,7 @@ func ExampleInstancePoolsAPI_Get_instancePools() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", smallest) + log.InfoContext(ctx, "found %v", smallest) created, err := w.InstancePools.Create(ctx, compute.CreateInstancePool{ InstancePoolName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -110,13 +110,13 @@ func ExampleInstancePoolsAPI_Get_instancePools() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := w.InstancePools.GetByInstancePoolId(ctx, created.InstancePoolId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -138,6 +138,6 @@ func ExampleInstancePoolsAPI_ListAll_instancePools() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } diff --git a/service/compute/instance_profiles_usage_test.go b/service/compute/instance_profiles_usage_test.go index d85aa3ab9..be11f1918 100755 --- a/service/compute/instance_profiles_usage_test.go +++ b/service/compute/instance_profiles_usage_test.go @@ -6,7 +6,7 @@ import ( "context" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/compute" ) @@ -61,6 +61,6 @@ func ExampleInstanceProfilesAPI_ListAll_awsInstanceProfiles() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } diff --git a/service/compute/policy_families_usage_test.go b/service/compute/policy_families_usage_test.go index 761fd125f..191e9428b 100755 --- a/service/compute/policy_families_usage_test.go +++ b/service/compute/policy_families_usage_test.go @@ -6,7 +6,7 @@ import ( "context" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/compute" ) @@ -22,7 +22,7 @@ func ExamplePolicyFamiliesAPI_Get_clusterPolicyFamilies() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) firstFamily, err := w.PolicyFamilies.Get(ctx, compute.GetPolicyFamilyRequest{ PolicyFamilyId: all[0].PolicyFamilyId, @@ -30,7 +30,7 @@ func ExamplePolicyFamiliesAPI_Get_clusterPolicyFamilies() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", firstFamily) + log.InfoContext(ctx, "found %v", firstFamily) } @@ -45,6 +45,6 @@ func ExamplePolicyFamiliesAPI_ListAll_clusterPolicyFamilies() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } diff --git a/service/iam/current_user_usage_test.go b/service/iam/current_user_usage_test.go index 273234ab9..16a5cf9a7 100755 --- a/service/iam/current_user_usage_test.go +++ b/service/iam/current_user_usage_test.go @@ -6,7 +6,7 @@ import ( "context" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" ) func ExampleCurrentUserAPI_Me_currentUser() { @@ -20,7 +20,7 @@ func ExampleCurrentUserAPI_Me_currentUser() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", me) + log.InfoContext(ctx, "found %v", me) } @@ -35,6 +35,6 @@ func ExampleCurrentUserAPI_Me_tokens() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", me2) + log.InfoContext(ctx, "found %v", me2) } diff --git a/service/iam/groups_usage_test.go b/service/iam/groups_usage_test.go index 72f52641d..90239ece3 100755 --- a/service/iam/groups_usage_test.go +++ b/service/iam/groups_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/iam" ) @@ -26,7 +26,7 @@ func ExampleGroupsAPI_Create_genericPermissions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", group) + log.InfoContext(ctx, "found %v", group) // cleanup @@ -50,7 +50,7 @@ func ExampleGroupsAPI_Create_groups() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", group) + log.InfoContext(ctx, "found %v", group) // cleanup @@ -74,7 +74,7 @@ func ExampleGroupsAPI_Create_secrets() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", group) + log.InfoContext(ctx, "found %v", group) // cleanup @@ -98,7 +98,7 @@ func ExampleGroupsAPI_Delete_genericPermissions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", group) + log.InfoContext(ctx, "found %v", group) err = w.Groups.DeleteById(ctx, group.Id) if err != nil { @@ -120,7 +120,7 @@ func ExampleGroupsAPI_Delete_groups() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", group) + log.InfoContext(ctx, "found %v", group) err = w.Groups.DeleteById(ctx, group.Id) if err != nil { @@ -149,7 +149,7 @@ func ExampleGroupsAPI_Delete_secrets() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", group) + log.InfoContext(ctx, "found %v", group) err = w.Groups.DeleteById(ctx, group.Id) if err != nil { @@ -171,13 +171,13 @@ func ExampleGroupsAPI_Get_groups() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", group) + log.InfoContext(ctx, "found %v", group) fetch, err := w.Groups.GetById(ctx, group.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", fetch) + log.InfoContext(ctx, "found %v", fetch) // cleanup diff --git a/service/iam/permissions_usage_test.go b/service/iam/permissions_usage_test.go index d0c490b81..1f14abd9a 100755 --- a/service/iam/permissions_usage_test.go +++ b/service/iam/permissions_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/iam" ) @@ -33,7 +33,7 @@ func ExamplePermissionsAPI_Get_genericPermissions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", obj) + log.InfoContext(ctx, "found %v", obj) _, err = w.Permissions.Get(ctx, iam.GetPermissionRequest{ RequestObjectType: "notebooks", @@ -64,7 +64,7 @@ func ExamplePermissionsAPI_GetPermissionLevels_genericPermissions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", obj) + log.InfoContext(ctx, "found %v", obj) levels, err := w.Permissions.GetPermissionLevels(ctx, iam.GetPermissionLevelsRequest{ RequestObjectType: "notebooks", @@ -73,7 +73,7 @@ func ExamplePermissionsAPI_GetPermissionLevels_genericPermissions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", levels) + log.InfoContext(ctx, "found %v", levels) } @@ -98,13 +98,13 @@ func ExamplePermissionsAPI_Set_genericPermissions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", group) + log.InfoContext(ctx, "found %v", group) obj, err := w.Workspace.GetStatusByPath(ctx, notebookPath) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", obj) + log.InfoContext(ctx, "found %v", obj) _, err = w.Permissions.Set(ctx, iam.PermissionsRequest{ RequestObjectType: "notebooks", diff --git a/service/iam/service_principals_usage_test.go b/service/iam/service_principals_usage_test.go index 159ecfc91..d8a05a385 100755 --- a/service/iam/service_principals_usage_test.go +++ b/service/iam/service_principals_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/iam" ) @@ -27,7 +27,7 @@ func ExampleServicePrincipalsAPI_Create_accountServicePrincipal() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spCreate) + log.InfoContext(ctx, "found %v", spCreate) // cleanup @@ -53,7 +53,7 @@ func ExampleServicePrincipalsAPI_Create_workspaceAssignmentOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spn) + log.InfoContext(ctx, "found %v", spn) } @@ -70,7 +70,7 @@ func ExampleServicePrincipalsAPI_Create_servicePrincipalsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -92,7 +92,7 @@ func ExampleServicePrincipalsAPI_Create_createOboTokenOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", groups) + log.InfoContext(ctx, "found %v", groups) spn, err := w.ServicePrincipals.Create(ctx, iam.ServicePrincipal{ DisplayName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -103,7 +103,7 @@ func ExampleServicePrincipalsAPI_Create_createOboTokenOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spn) + log.InfoContext(ctx, "found %v", spn) // cleanup @@ -128,13 +128,13 @@ func ExampleServicePrincipalsAPI_Get_accountServicePrincipal() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spCreate) + log.InfoContext(ctx, "found %v", spCreate) sp, err := a.ServicePrincipals.GetById(ctx, spCreate.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", sp) + log.InfoContext(ctx, "found %v", sp) // cleanup @@ -160,13 +160,13 @@ func ExampleServicePrincipalsAPI_Get_servicePrincipalsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := w.ServicePrincipals.GetById(ctx, created.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -191,13 +191,13 @@ func ExampleServicePrincipalsAPI_ListAll_accountServicePrincipal() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spCreate) + log.InfoContext(ctx, "found %v", spCreate) sp, err := a.ServicePrincipals.GetById(ctx, spCreate.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", sp) + log.InfoContext(ctx, "found %v", sp) spList, err := a.ServicePrincipals.ListAll(ctx, iam.ListAccountServicePrincipalsRequest{ Filter: fmt.Sprintf("displayName eq %v", sp.DisplayName), @@ -205,7 +205,7 @@ func ExampleServicePrincipalsAPI_ListAll_accountServicePrincipal() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spList) + log.InfoContext(ctx, "found %v", spList) // cleanup @@ -229,7 +229,7 @@ func ExampleServicePrincipalsAPI_ListAll_servicePrincipalsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -247,13 +247,13 @@ func ExampleServicePrincipalsAPI_Patch_accountServicePrincipal() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spCreate) + log.InfoContext(ctx, "found %v", spCreate) sp, err := a.ServicePrincipals.GetById(ctx, spCreate.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", sp) + log.InfoContext(ctx, "found %v", sp) err = a.ServicePrincipals.Patch(ctx, iam.PartialUpdate{ Id: sp.Id, @@ -292,13 +292,13 @@ func ExampleServicePrincipalsAPI_Patch_servicePrincipalsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := w.ServicePrincipals.GetById(ctx, created.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) err = w.ServicePrincipals.Patch(ctx, iam.PartialUpdate{ Id: byId.Id, @@ -336,13 +336,13 @@ func ExampleServicePrincipalsAPI_Update_accountServicePrincipal() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spCreate) + log.InfoContext(ctx, "found %v", spCreate) sp, err := a.ServicePrincipals.GetById(ctx, spCreate.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", sp) + log.InfoContext(ctx, "found %v", sp) err = a.ServicePrincipals.Update(ctx, iam.ServicePrincipal{ Active: true, @@ -377,7 +377,7 @@ func ExampleServicePrincipalsAPI_Update_servicePrincipalsOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.ServicePrincipals.Update(ctx, iam.ServicePrincipal{ Id: created.Id, diff --git a/service/iam/users_usage_test.go b/service/iam/users_usage_test.go index c1326b45e..ec80f4fbe 100755 --- a/service/iam/users_usage_test.go +++ b/service/iam/users_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/iam" ) @@ -26,7 +26,7 @@ func ExampleUsersAPI_Create_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", otherOwner) + log.InfoContext(ctx, "found %v", otherOwner) // cleanup @@ -51,7 +51,7 @@ func ExampleUsersAPI_Create_workspaceUsers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", user) + log.InfoContext(ctx, "found %v", user) } @@ -69,7 +69,7 @@ func ExampleUsersAPI_Create_accountUsers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", user) + log.InfoContext(ctx, "found %v", user) // cleanup @@ -93,7 +93,7 @@ func ExampleUsersAPI_Delete_clustersApiIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", otherOwner) + log.InfoContext(ctx, "found %v", otherOwner) err = w.Users.DeleteById(ctx, otherOwner.Id) if err != nil { @@ -116,7 +116,7 @@ func ExampleUsersAPI_Delete_workspaceUsers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", user) + log.InfoContext(ctx, "found %v", user) err = w.Users.DeleteById(ctx, user.Id) if err != nil { @@ -139,7 +139,7 @@ func ExampleUsersAPI_Delete_accountUsers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", user) + log.InfoContext(ctx, "found %v", user) err = a.Users.DeleteById(ctx, user.Id) if err != nil { @@ -162,13 +162,13 @@ func ExampleUsersAPI_Get_workspaceUsers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", user) + log.InfoContext(ctx, "found %v", user) fetch, err := w.Users.GetById(ctx, user.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", fetch) + log.InfoContext(ctx, "found %v", fetch) } @@ -186,13 +186,13 @@ func ExampleUsersAPI_Get_accountUsers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", user) + log.InfoContext(ctx, "found %v", user) byId, err := a.Users.GetById(ctx, user.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -218,7 +218,7 @@ func ExampleUsersAPI_ListAll_workspaceUsers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", allUsers) + log.InfoContext(ctx, "found %v", allUsers) } @@ -236,7 +236,7 @@ func ExampleUsersAPI_Patch_workspaceUsers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", user) + log.InfoContext(ctx, "found %v", user) err = w.Users.Patch(ctx, iam.PartialUpdate{ Id: user.Id, @@ -267,7 +267,7 @@ func ExampleUsersAPI_Patch_accountUsers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", user) + log.InfoContext(ctx, "found %v", user) err = a.Users.Patch(ctx, iam.PartialUpdate{ Id: user.Id, @@ -308,7 +308,7 @@ func ExampleUsersAPI_Update_workspaceUsers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", user) + log.InfoContext(ctx, "found %v", user) err = w.Users.Update(ctx, iam.User{ Id: user.Id, diff --git a/service/iam/workspace_assignment_usage_test.go b/service/iam/workspace_assignment_usage_test.go index 3ea024d3f..8fb18a1b9 100755 --- a/service/iam/workspace_assignment_usage_test.go +++ b/service/iam/workspace_assignment_usage_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/iam" ) @@ -34,7 +34,7 @@ func ExampleWorkspaceAssignmentAPI_ListAll_workspaceAssignmentOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -51,7 +51,7 @@ func ExampleWorkspaceAssignmentAPI_Update_workspaceAssignmentOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spn) + log.InfoContext(ctx, "found %v", spn) spnId := func(v string) int64 { i, err := strconv.ParseInt(v, 10, 64) diff --git a/service/jobs/jobs_usage_test.go b/service/jobs/jobs_usage_test.go index d05292d5b..80b3119b4 100755 --- a/service/jobs/jobs_usage_test.go +++ b/service/jobs/jobs_usage_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/jobs" ) @@ -54,7 +54,7 @@ func ExampleJobsAPI_CancelAllRuns_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdJob) + log.InfoContext(ctx, "found %v", createdJob) err = w.Jobs.CancelAllRuns(ctx, jobs.CancelAllRuns{ JobId: createdJob.JobId, @@ -111,7 +111,7 @@ func ExampleJobsAPI_CancelRun_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdJob) + log.InfoContext(ctx, "found %v", createdJob) runNowResponse, err := w.Jobs.RunNow(ctx, jobs.RunNow{ JobId: createdJob.JobId, @@ -119,7 +119,7 @@ func ExampleJobsAPI_CancelRun_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", runNowResponse) + log.InfoContext(ctx, "found %v", runNowResponse) cancelledRun, err := w.Jobs.CancelRunAndWait(ctx, jobs.CancelRun{ RunId: runNowResponse.Response.RunId, @@ -127,7 +127,7 @@ func ExampleJobsAPI_CancelRun_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", cancelledRun) + log.InfoContext(ctx, "found %v", cancelledRun) // cleanup @@ -177,7 +177,7 @@ func ExampleJobsAPI_Create_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdJob) + log.InfoContext(ctx, "found %v", createdJob) // cleanup @@ -227,7 +227,7 @@ func ExampleJobsAPI_ExportRun_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdJob) + log.InfoContext(ctx, "found %v", createdJob) runById, err := w.Jobs.RunNowAndWait(ctx, jobs.RunNow{ JobId: createdJob.JobId, @@ -235,7 +235,7 @@ func ExampleJobsAPI_ExportRun_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", runById) + log.InfoContext(ctx, "found %v", runById) exportedView, err := w.Jobs.ExportRun(ctx, jobs.ExportRunRequest{ RunId: runById.Tasks[0].RunId, @@ -244,7 +244,7 @@ func ExampleJobsAPI_ExportRun_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", exportedView) + log.InfoContext(ctx, "found %v", exportedView) // cleanup @@ -294,13 +294,13 @@ func ExampleJobsAPI_Get_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdJob) + log.InfoContext(ctx, "found %v", createdJob) byId, err := w.Jobs.GetByJobId(ctx, createdJob.JobId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -348,13 +348,13 @@ func ExampleJobsAPI_GetRunOutput_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", run) + log.InfoContext(ctx, "found %v", run) output, err := w.Jobs.GetRunOutputByRunId(ctx, run.Tasks[0].RunId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", output) + log.InfoContext(ctx, "found %v", output) // cleanup @@ -378,7 +378,7 @@ func ExampleJobsAPI_ListAll_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", jobList) + log.InfoContext(ctx, "found %v", jobList) } @@ -421,7 +421,7 @@ func ExampleJobsAPI_ListRuns_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdJob) + log.InfoContext(ctx, "found %v", createdJob) runList, err := w.Jobs.ListRunsAll(ctx, jobs.ListRunsRequest{ JobId: createdJob.JobId, @@ -429,7 +429,7 @@ func ExampleJobsAPI_ListRuns_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", runList) + log.InfoContext(ctx, "found %v", runList) // cleanup @@ -479,7 +479,7 @@ func ExampleJobsAPI_RepairRun_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdJob) + log.InfoContext(ctx, "found %v", createdJob) runNowResponse, err := w.Jobs.RunNow(ctx, jobs.RunNow{ JobId: createdJob.JobId, @@ -487,7 +487,7 @@ func ExampleJobsAPI_RepairRun_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", runNowResponse) + log.InfoContext(ctx, "found %v", runNowResponse) cancelledRun, err := w.Jobs.CancelRunAndWait(ctx, jobs.CancelRun{ RunId: runNowResponse.Response.RunId, @@ -495,7 +495,7 @@ func ExampleJobsAPI_RepairRun_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", cancelledRun) + log.InfoContext(ctx, "found %v", cancelledRun) repairedRun, err := w.Jobs.RepairRunAndWait(ctx, jobs.RepairRun{ RerunTasks: []string{cancelledRun.Tasks[0].TaskKey}, @@ -504,7 +504,7 @@ func ExampleJobsAPI_RepairRun_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", repairedRun) + log.InfoContext(ctx, "found %v", repairedRun) // cleanup @@ -554,7 +554,7 @@ func ExampleJobsAPI_Reset_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdJob) + log.InfoContext(ctx, "found %v", createdJob) newName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) @@ -562,7 +562,7 @@ func ExampleJobsAPI_Reset_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) err = w.Jobs.Reset(ctx, jobs.ResetJob{ JobId: byId.JobId, @@ -623,7 +623,7 @@ func ExampleJobsAPI_RunNow_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdJob) + log.InfoContext(ctx, "found %v", createdJob) runById, err := w.Jobs.RunNowAndWait(ctx, jobs.RunNow{ JobId: createdJob.JobId, @@ -631,7 +631,7 @@ func ExampleJobsAPI_RunNow_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", runById) + log.InfoContext(ctx, "found %v", runById) // cleanup @@ -679,7 +679,7 @@ func ExampleJobsAPI_Submit_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", run) + log.InfoContext(ctx, "found %v", run) // cleanup @@ -731,7 +731,7 @@ func ExampleJobsAPI_Update_jobsApiFullIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdJob) + log.InfoContext(ctx, "found %v", createdJob) err = w.Jobs.Update(ctx, jobs.UpdateJob{ JobId: createdJob.JobId, diff --git a/service/ml/experiments_usage_test.go b/service/ml/experiments_usage_test.go index cdcbd9465..71ba25219 100755 --- a/service/ml/experiments_usage_test.go +++ b/service/ml/experiments_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/ml" ) @@ -26,7 +26,7 @@ func ExampleExperimentsAPI_CreateExperiment_experiments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", experiment) + log.InfoContext(ctx, "found %v", experiment) // cleanup @@ -52,7 +52,7 @@ func ExampleExperimentsAPI_CreateExperiment_mLflowRuns() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", experiment) + log.InfoContext(ctx, "found %v", experiment) // cleanup @@ -78,7 +78,7 @@ func ExampleExperimentsAPI_CreateRun_mLflowRuns() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", experiment) + log.InfoContext(ctx, "found %v", experiment) created, err := w.Experiments.CreateRun(ctx, ml.CreateRun{ ExperimentId: experiment.ExperimentId, @@ -90,7 +90,7 @@ func ExampleExperimentsAPI_CreateRun_mLflowRuns() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -122,7 +122,7 @@ func ExampleExperimentsAPI_GetExperiment_experiments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", experiment) + log.InfoContext(ctx, "found %v", experiment) _, err = w.Experiments.GetExperiment(ctx, ml.GetExperimentRequest{ ExperimentId: experiment.ExperimentId, @@ -153,7 +153,7 @@ func ExampleExperimentsAPI_ListExperiments_experiments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -170,7 +170,7 @@ func ExampleExperimentsAPI_UpdateExperiment_experiments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", experiment) + log.InfoContext(ctx, "found %v", experiment) err = w.Experiments.UpdateExperiment(ctx, ml.UpdateExperiment{ NewName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -204,7 +204,7 @@ func ExampleExperimentsAPI_UpdateRun_mLflowRuns() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", experiment) + log.InfoContext(ctx, "found %v", experiment) created, err := w.Experiments.CreateRun(ctx, ml.CreateRun{ ExperimentId: experiment.ExperimentId, @@ -216,7 +216,7 @@ func ExampleExperimentsAPI_UpdateRun_mLflowRuns() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Experiments.UpdateRun(ctx, ml.UpdateRun{ RunId: created.Run.Info.RunId, diff --git a/service/ml/model_registry_usage_test.go b/service/ml/model_registry_usage_test.go index 7199cd404..0640aea58 100755 --- a/service/ml/model_registry_usage_test.go +++ b/service/ml/model_registry_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/ml" ) @@ -26,7 +26,7 @@ func ExampleModelRegistryAPI_CreateComment_modelVersionComments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", model) + log.InfoContext(ctx, "found %v", model) mv, err := w.ModelRegistry.CreateModelVersion(ctx, ml.CreateModelVersionRequest{ Name: model.RegisteredModel.Name, @@ -35,7 +35,7 @@ func ExampleModelRegistryAPI_CreateComment_modelVersionComments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", mv) + log.InfoContext(ctx, "found %v", mv) created, err := w.ModelRegistry.CreateComment(ctx, ml.CreateComment{ Comment: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -45,7 +45,7 @@ func ExampleModelRegistryAPI_CreateComment_modelVersionComments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -71,7 +71,7 @@ func ExampleModelRegistryAPI_CreateModel_models() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) } @@ -88,7 +88,7 @@ func ExampleModelRegistryAPI_CreateModel_modelVersions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", model) + log.InfoContext(ctx, "found %v", model) } @@ -105,7 +105,7 @@ func ExampleModelRegistryAPI_CreateModel_modelVersionComments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", model) + log.InfoContext(ctx, "found %v", model) } @@ -122,7 +122,7 @@ func ExampleModelRegistryAPI_CreateModelVersion_modelVersions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", model) + log.InfoContext(ctx, "found %v", model) created, err := w.ModelRegistry.CreateModelVersion(ctx, ml.CreateModelVersionRequest{ Name: model.RegisteredModel.Name, @@ -131,7 +131,7 @@ func ExampleModelRegistryAPI_CreateModelVersion_modelVersions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) } @@ -148,7 +148,7 @@ func ExampleModelRegistryAPI_CreateModelVersion_modelVersionComments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", model) + log.InfoContext(ctx, "found %v", model) mv, err := w.ModelRegistry.CreateModelVersion(ctx, ml.CreateModelVersionRequest{ Name: model.RegisteredModel.Name, @@ -157,7 +157,7 @@ func ExampleModelRegistryAPI_CreateModelVersion_modelVersionComments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", mv) + log.InfoContext(ctx, "found %v", mv) } @@ -178,7 +178,7 @@ func ExampleModelRegistryAPI_CreateWebhook_registryWebhooks() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -204,7 +204,7 @@ func ExampleModelRegistryAPI_GetModel_models() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) model, err := w.ModelRegistry.GetModel(ctx, ml.GetModelRequest{ Name: created.RegisteredModel.Name, @@ -212,7 +212,7 @@ func ExampleModelRegistryAPI_GetModel_models() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", model) + log.InfoContext(ctx, "found %v", model) } @@ -227,7 +227,7 @@ func ExampleModelRegistryAPI_ListModels_models() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -242,7 +242,7 @@ func ExampleModelRegistryAPI_ListWebhooks_registryWebhooks() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -259,7 +259,7 @@ func ExampleModelRegistryAPI_UpdateComment_modelVersionComments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", model) + log.InfoContext(ctx, "found %v", model) mv, err := w.ModelRegistry.CreateModelVersion(ctx, ml.CreateModelVersionRequest{ Name: model.RegisteredModel.Name, @@ -268,7 +268,7 @@ func ExampleModelRegistryAPI_UpdateComment_modelVersionComments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", mv) + log.InfoContext(ctx, "found %v", mv) created, err := w.ModelRegistry.CreateComment(ctx, ml.CreateComment{ Comment: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -278,7 +278,7 @@ func ExampleModelRegistryAPI_UpdateComment_modelVersionComments() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.ModelRegistry.UpdateComment(ctx, ml.UpdateComment{ Comment: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -312,7 +312,7 @@ func ExampleModelRegistryAPI_UpdateModel_models() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) model, err := w.ModelRegistry.GetModel(ctx, ml.GetModelRequest{ Name: created.RegisteredModel.Name, @@ -320,7 +320,7 @@ func ExampleModelRegistryAPI_UpdateModel_models() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", model) + log.InfoContext(ctx, "found %v", model) err = w.ModelRegistry.UpdateModel(ctx, ml.UpdateModelRequest{ Name: model.RegisteredModelDatabricks.Name, @@ -345,7 +345,7 @@ func ExampleModelRegistryAPI_UpdateModelVersion_modelVersions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", model) + log.InfoContext(ctx, "found %v", model) created, err := w.ModelRegistry.CreateModelVersion(ctx, ml.CreateModelVersionRequest{ Name: model.RegisteredModel.Name, @@ -354,7 +354,7 @@ func ExampleModelRegistryAPI_UpdateModelVersion_modelVersions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.ModelRegistry.UpdateModelVersion(ctx, ml.UpdateModelVersionRequest{ Description: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -384,7 +384,7 @@ func ExampleModelRegistryAPI_UpdateWebhook_registryWebhooks() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.ModelRegistry.UpdateWebhook(ctx, ml.UpdateRegistryWebhook{ Id: created.Webhook.Id, diff --git a/service/pipelines/pipelines_usage_test.go b/service/pipelines/pipelines_usage_test.go index 2eb96530e..3f7c43307 100755 --- a/service/pipelines/pipelines_usage_test.go +++ b/service/pipelines/pipelines_usage_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/pipelines" ) @@ -48,7 +48,7 @@ func ExamplePipelinesAPI_Create_pipelines() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -92,13 +92,13 @@ func ExamplePipelinesAPI_Get_pipelines() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := w.Pipelines.GetByPipelineId(ctx, created.PipelineId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -142,7 +142,7 @@ func ExamplePipelinesAPI_ListPipelineEvents_pipelines() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) events, err := w.Pipelines.ListPipelineEventsAll(ctx, pipelines.ListPipelineEventsRequest{ PipelineId: created.PipelineId, @@ -150,7 +150,7 @@ func ExamplePipelinesAPI_ListPipelineEvents_pipelines() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", events) + log.InfoContext(ctx, "found %v", events) // cleanup @@ -172,7 +172,7 @@ func ExamplePipelinesAPI_ListPipelines_pipelines() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -209,7 +209,7 @@ func ExamplePipelinesAPI_Update_pipelines() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.Pipelines.Update(ctx, pipelines.EditPipeline{ PipelineId: created.PipelineId, diff --git a/service/provisioning/credentials_usage_test.go b/service/provisioning/credentials_usage_test.go index a3da09222..6e9e3213e 100755 --- a/service/provisioning/credentials_usage_test.go +++ b/service/provisioning/credentials_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/provisioning" ) @@ -32,7 +32,7 @@ func ExampleCredentialsAPI_Create_logDelivery() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", creds) + log.InfoContext(ctx, "found %v", creds) // cleanup @@ -61,7 +61,7 @@ func ExampleCredentialsAPI_Create_credentials() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", role) + log.InfoContext(ctx, "found %v", role) // cleanup @@ -90,7 +90,7 @@ func ExampleCredentialsAPI_Create_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", role) + log.InfoContext(ctx, "found %v", role) // cleanup @@ -119,13 +119,13 @@ func ExampleCredentialsAPI_Get_credentials() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", role) + log.InfoContext(ctx, "found %v", role) byId, err := a.Credentials.GetByCredentialsId(ctx, role.CredentialsId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -147,6 +147,6 @@ func ExampleCredentialsAPI_ListAll_credentials() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", configs) + log.InfoContext(ctx, "found %v", configs) } diff --git a/service/provisioning/encryption_keys_usage_test.go b/service/provisioning/encryption_keys_usage_test.go index 9b7918dfd..1c6710ee2 100755 --- a/service/provisioning/encryption_keys_usage_test.go +++ b/service/provisioning/encryption_keys_usage_test.go @@ -7,7 +7,7 @@ import ( "os" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/provisioning" ) @@ -29,7 +29,7 @@ func ExampleEncryptionKeysAPI_Create_encryptionKeys() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -57,13 +57,13 @@ func ExampleEncryptionKeysAPI_Get_encryptionKeys() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := a.EncryptionKeys.GetByCustomerManagedKeyId(ctx, created.CustomerManagedKeyId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -85,6 +85,6 @@ func ExampleEncryptionKeysAPI_ListAll_encryptionKeys() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } diff --git a/service/provisioning/networks_usage_test.go b/service/provisioning/networks_usage_test.go index bf3f34c4d..ebe21c0a6 100755 --- a/service/provisioning/networks_usage_test.go +++ b/service/provisioning/networks_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/provisioning" ) @@ -29,7 +29,7 @@ func ExampleNetworksAPI_Create_networks() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", netw) + log.InfoContext(ctx, "found %v", netw) } @@ -49,13 +49,13 @@ func ExampleNetworksAPI_Get_networks() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", netw) + log.InfoContext(ctx, "found %v", netw) byId, err := a.Networks.GetByNetworkId(ctx, netw.NetworkId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) } @@ -70,6 +70,6 @@ func ExampleNetworksAPI_ListAll_networks() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", configs) + log.InfoContext(ctx, "found %v", configs) } diff --git a/service/provisioning/private_access_usage_test.go b/service/provisioning/private_access_usage_test.go index 13d89ec7e..a1c3e1d9c 100755 --- a/service/provisioning/private_access_usage_test.go +++ b/service/provisioning/private_access_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/provisioning" ) @@ -28,7 +28,7 @@ func ExamplePrivateAccessAPI_Create_privateAccess() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -53,13 +53,13 @@ func ExamplePrivateAccessAPI_Get_privateAccess() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := a.PrivateAccess.GetByPrivateAccessSettingsId(ctx, created.PrivateAccessSettingsId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -81,7 +81,7 @@ func ExamplePrivateAccessAPI_ListAll_privateAccess() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -99,7 +99,7 @@ func ExamplePrivateAccessAPI_Replace_privateAccess() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = a.PrivateAccess.Replace(ctx, provisioning.UpsertPrivateAccessSettingsRequest{ PrivateAccessSettingsId: created.PrivateAccessSettingsId, diff --git a/service/provisioning/storage_usage_test.go b/service/provisioning/storage_usage_test.go index 0c2738918..fd517f3e9 100755 --- a/service/provisioning/storage_usage_test.go +++ b/service/provisioning/storage_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/provisioning" ) @@ -30,7 +30,7 @@ func ExampleStorageAPI_Create_logDelivery() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", bucket) + log.InfoContext(ctx, "found %v", bucket) // cleanup @@ -57,7 +57,7 @@ func ExampleStorageAPI_Create_storage() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storage) + log.InfoContext(ctx, "found %v", storage) } @@ -77,7 +77,7 @@ func ExampleStorageAPI_Create_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storage) + log.InfoContext(ctx, "found %v", storage) // cleanup @@ -104,13 +104,13 @@ func ExampleStorageAPI_Get_storage() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storage) + log.InfoContext(ctx, "found %v", storage) byId, err := a.Storage.GetByStorageConfigurationId(ctx, storage.StorageConfigurationId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) } @@ -125,6 +125,6 @@ func ExampleStorageAPI_ListAll_storage() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", configs) + log.InfoContext(ctx, "found %v", configs) } diff --git a/service/provisioning/vpc_endpoints_usage_test.go b/service/provisioning/vpc_endpoints_usage_test.go index c13806d6a..9fee08e0f 100755 --- a/service/provisioning/vpc_endpoints_usage_test.go +++ b/service/provisioning/vpc_endpoints_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/provisioning" ) @@ -29,7 +29,7 @@ func ExampleVpcEndpointsAPI_Create_vpcEndpoints() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -55,13 +55,13 @@ func ExampleVpcEndpointsAPI_Get_vpcEndpoints() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := a.VpcEndpoints.GetByVpcEndpointId(ctx, created.VpcEndpointId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -83,6 +83,6 @@ func ExampleVpcEndpointsAPI_ListAll_vpcEndpoints() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } diff --git a/service/provisioning/workspaces_usage_test.go b/service/provisioning/workspaces_usage_test.go index e50e4c98c..f97cb4ed8 100755 --- a/service/provisioning/workspaces_usage_test.go +++ b/service/provisioning/workspaces_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/provisioning" ) @@ -30,7 +30,7 @@ func ExampleWorkspacesAPI_Create_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storage) + log.InfoContext(ctx, "found %v", storage) role, err := a.Credentials.Create(ctx, provisioning.CreateCredentialRequest{ CredentialsName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -43,7 +43,7 @@ func ExampleWorkspacesAPI_Create_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", role) + log.InfoContext(ctx, "found %v", role) created, err := a.Workspaces.CreateAndWait(ctx, provisioning.CreateWorkspaceRequest{ WorkspaceName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -54,7 +54,7 @@ func ExampleWorkspacesAPI_Create_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -89,7 +89,7 @@ func ExampleWorkspacesAPI_Get_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storage) + log.InfoContext(ctx, "found %v", storage) role, err := a.Credentials.Create(ctx, provisioning.CreateCredentialRequest{ CredentialsName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -102,7 +102,7 @@ func ExampleWorkspacesAPI_Get_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", role) + log.InfoContext(ctx, "found %v", role) created, err := a.Workspaces.CreateAndWait(ctx, provisioning.CreateWorkspaceRequest{ WorkspaceName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -113,13 +113,13 @@ func ExampleWorkspacesAPI_Get_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := a.Workspaces.GetByWorkspaceId(ctx, created.WorkspaceId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -149,7 +149,7 @@ func ExampleWorkspacesAPI_ListAll_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -169,7 +169,7 @@ func ExampleWorkspacesAPI_Update_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", storage) + log.InfoContext(ctx, "found %v", storage) role, err := a.Credentials.Create(ctx, provisioning.CreateCredentialRequest{ CredentialsName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -182,7 +182,7 @@ func ExampleWorkspacesAPI_Update_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", role) + log.InfoContext(ctx, "found %v", role) updateRole, err := a.Credentials.Create(ctx, provisioning.CreateCredentialRequest{ CredentialsName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -195,7 +195,7 @@ func ExampleWorkspacesAPI_Update_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", updateRole) + log.InfoContext(ctx, "found %v", updateRole) created, err := a.Workspaces.CreateAndWait(ctx, provisioning.CreateWorkspaceRequest{ WorkspaceName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -206,7 +206,7 @@ func ExampleWorkspacesAPI_Update_workspaces() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = a.Workspaces.UpdateAndWait(ctx, provisioning.UpdateWorkspaceRequest{ WorkspaceId: created.WorkspaceId, diff --git a/service/settings/ip_access_lists_usage_test.go b/service/settings/ip_access_lists_usage_test.go index 55aa19fc1..bcc9c7387 100755 --- a/service/settings/ip_access_lists_usage_test.go +++ b/service/settings/ip_access_lists_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/settings" ) @@ -28,7 +28,7 @@ func ExampleIpAccessListsAPI_Create_ipAccessLists() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -54,13 +54,13 @@ func ExampleIpAccessListsAPI_Get_ipAccessLists() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := w.IpAccessLists.GetByIpAccessListId(ctx, created.IpAccessList.ListId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -82,7 +82,7 @@ func ExampleIpAccessListsAPI_ListAll_ipAccessLists() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -101,7 +101,7 @@ func ExampleIpAccessListsAPI_Replace_ipAccessLists() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.IpAccessLists.Replace(ctx, settings.ReplaceIpAccessList{ IpAccessListId: created.IpAccessList.ListId, diff --git a/service/settings/token_management_usage_test.go b/service/settings/token_management_usage_test.go index cdc1baccb..1753d278c 100755 --- a/service/settings/token_management_usage_test.go +++ b/service/settings/token_management_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/iam" "github.com/databricks/databricks-sdk-go/service/settings" @@ -25,7 +25,7 @@ func ExampleTokenManagementAPI_CreateOboToken_createOboTokenOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", groups) + log.InfoContext(ctx, "found %v", groups) spn, err := w.ServicePrincipals.Create(ctx, iam.ServicePrincipal{ DisplayName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -36,7 +36,7 @@ func ExampleTokenManagementAPI_CreateOboToken_createOboTokenOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spn) + log.InfoContext(ctx, "found %v", spn) obo, err := w.TokenManagement.CreateOboToken(ctx, settings.CreateOboTokenRequest{ ApplicationId: spn.ApplicationId, @@ -45,7 +45,7 @@ func ExampleTokenManagementAPI_CreateOboToken_createOboTokenOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", obo) + log.InfoContext(ctx, "found %v", obo) // cleanup @@ -71,7 +71,7 @@ func ExampleTokenManagementAPI_Get_createOboTokenOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", groups) + log.InfoContext(ctx, "found %v", groups) spn, err := w.ServicePrincipals.Create(ctx, iam.ServicePrincipal{ DisplayName: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -82,7 +82,7 @@ func ExampleTokenManagementAPI_Get_createOboTokenOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", spn) + log.InfoContext(ctx, "found %v", spn) obo, err := w.TokenManagement.CreateOboToken(ctx, settings.CreateOboTokenRequest{ ApplicationId: spn.ApplicationId, @@ -91,13 +91,13 @@ func ExampleTokenManagementAPI_Get_createOboTokenOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", obo) + log.InfoContext(ctx, "found %v", obo) byId, err := w.TokenManagement.GetByTokenId(ctx, obo.TokenInfo.TokenId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -123,6 +123,6 @@ func ExampleTokenManagementAPI_ListAll_createOboTokenOnAws() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } diff --git a/service/settings/tokens_usage_test.go b/service/settings/tokens_usage_test.go index ccd8983fe..1bcf073d4 100755 --- a/service/settings/tokens_usage_test.go +++ b/service/settings/tokens_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/settings" ) @@ -27,7 +27,7 @@ func ExampleTokensAPI_Create_tokens() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", token) + log.InfoContext(ctx, "found %v", token) // cleanup @@ -52,13 +52,13 @@ func ExampleTokensAPI_Get_tokens() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", token) + log.InfoContext(ctx, "found %v", token) byName, err := w.Tokens.GetByComment(ctx, token.TokenInfo.Comment) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byName) + log.InfoContext(ctx, "found %v", byName) // cleanup @@ -80,6 +80,6 @@ func ExampleTokensAPI_ListAll_tokens() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } diff --git a/service/settings/workspace_conf_usage_test.go b/service/settings/workspace_conf_usage_test.go index cb29ba0bd..48c40274a 100755 --- a/service/settings/workspace_conf_usage_test.go +++ b/service/settings/workspace_conf_usage_test.go @@ -6,7 +6,7 @@ import ( "context" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/settings" ) @@ -24,6 +24,6 @@ func ExampleWorkspaceConfAPI_GetStatus_repos() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", conf) + log.InfoContext(ctx, "found %v", conf) } diff --git a/service/sharing/providers_usage_test.go b/service/sharing/providers_usage_test.go index d8ce5613e..64a77ef1a 100755 --- a/service/sharing/providers_usage_test.go +++ b/service/sharing/providers_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/sharing" ) @@ -34,7 +34,7 @@ func ExampleProvidersAPI_Create_providers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -66,7 +66,7 @@ func ExampleProvidersAPI_Get_providers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Providers.GetByName(ctx, created.Name) if err != nil { @@ -93,7 +93,7 @@ func ExampleProvidersAPI_ListAll_providers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -118,7 +118,7 @@ func ExampleProvidersAPI_ListShares_providers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) shares, err := w.Providers.ListSharesAll(ctx, sharing.ListSharesRequest{ Name: created.Name, @@ -126,7 +126,7 @@ func ExampleProvidersAPI_ListShares_providers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", shares) + log.InfoContext(ctx, "found %v", shares) // cleanup @@ -158,7 +158,7 @@ func ExampleProvidersAPI_Update_providers() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Providers.Update(ctx, sharing.UpdateProvider{ Name: created.Name, diff --git a/service/sharing/recipients_usage_test.go b/service/sharing/recipients_usage_test.go index ee78c5abe..29190be28 100755 --- a/service/sharing/recipients_usage_test.go +++ b/service/sharing/recipients_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/sharing" ) @@ -26,7 +26,7 @@ func ExampleRecipientsAPI_Create_recipients() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -50,7 +50,7 @@ func ExampleRecipientsAPI_Get_recipients() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Recipients.GetByName(ctx, created.Name) if err != nil { @@ -77,7 +77,7 @@ func ExampleRecipientsAPI_ListAll_recipients() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -94,7 +94,7 @@ func ExampleRecipientsAPI_RotateToken_recipients() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) recipientInfo, err := w.Recipients.RotateToken(ctx, sharing.RotateRecipientToken{ Name: created.Name, @@ -103,7 +103,7 @@ func ExampleRecipientsAPI_RotateToken_recipients() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", recipientInfo) + log.InfoContext(ctx, "found %v", recipientInfo) // cleanup @@ -127,13 +127,13 @@ func ExampleRecipientsAPI_SharePermissions_recipients() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) sharePermissions, err := w.Recipients.SharePermissionsByName(ctx, created.Name) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", sharePermissions) + log.InfoContext(ctx, "found %v", sharePermissions) // cleanup @@ -157,7 +157,7 @@ func ExampleRecipientsAPI_Update_recipients() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.Recipients.Update(ctx, sharing.UpdateRecipient{ Name: created.Name, diff --git a/service/sharing/shares_usage_test.go b/service/sharing/shares_usage_test.go index fe2015082..a6601cb17 100755 --- a/service/sharing/shares_usage_test.go +++ b/service/sharing/shares_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" "github.com/databricks/databricks-sdk-go/service/sharing" @@ -29,7 +29,7 @@ func ExampleSharesAPI_Create_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdShare) + log.InfoContext(ctx, "found %v", createdShare) // cleanup @@ -53,7 +53,7 @@ func ExampleSharesAPI_Get_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdShare) + log.InfoContext(ctx, "found %v", createdShare) _, err = w.Shares.GetByName(ctx, createdShare.Name) if err != nil { @@ -80,7 +80,7 @@ func ExampleSharesAPI_ListAll_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -99,7 +99,7 @@ func ExampleSharesAPI_Update_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -108,7 +108,7 @@ func ExampleSharesAPI_Update_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) _, err = w.StatementExecution.ExecuteAndWait(ctx, sql.ExecuteStatementRequest{ WarehouseId: os.Getenv("TEST_DEFAULT_WAREHOUSE_ID"), @@ -128,7 +128,7 @@ func ExampleSharesAPI_Update_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdShare) + log.InfoContext(ctx, "found %v", createdShare) _, err = w.Shares.Update(ctx, sharing.UpdateShare{ Name: createdShare.Name, diff --git a/service/sql/alerts_usage_test.go b/service/sql/alerts_usage_test.go index f919e7a11..402338515 100755 --- a/service/sql/alerts_usage_test.go +++ b/service/sql/alerts_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/sql" ) @@ -24,7 +24,7 @@ func ExampleAlertsAPI_Create_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", srcs) + log.InfoContext(ctx, "found %v", srcs) query, err := w.Queries.Create(ctx, sql.CreateQueryRequest{ Query: &sql.CreateQueryRequestQuery{ @@ -37,7 +37,7 @@ func ExampleAlertsAPI_Create_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", query) + log.InfoContext(ctx, "found %v", query) alert, err := w.Alerts.Create(ctx, sql.CreateAlertRequest{ Alert: &sql.CreateAlertRequestAlert{ @@ -61,7 +61,7 @@ func ExampleAlertsAPI_Create_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", alert) + log.InfoContext(ctx, "found %v", alert) // cleanup @@ -87,7 +87,7 @@ func ExampleAlertsAPI_Get_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", srcs) + log.InfoContext(ctx, "found %v", srcs) query, err := w.Queries.Create(ctx, sql.CreateQueryRequest{ Query: &sql.CreateQueryRequestQuery{ @@ -100,7 +100,7 @@ func ExampleAlertsAPI_Get_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", query) + log.InfoContext(ctx, "found %v", query) alert, err := w.Alerts.Create(ctx, sql.CreateAlertRequest{ Alert: &sql.CreateAlertRequestAlert{ @@ -124,13 +124,13 @@ func ExampleAlertsAPI_Get_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", alert) + log.InfoContext(ctx, "found %v", alert) byId, err := w.Alerts.GetById(ctx, alert.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -156,7 +156,7 @@ func ExampleAlertsAPI_ListAll_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -171,7 +171,7 @@ func ExampleAlertsAPI_Update_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", srcs) + log.InfoContext(ctx, "found %v", srcs) query, err := w.Queries.Create(ctx, sql.CreateQueryRequest{ Query: &sql.CreateQueryRequestQuery{ @@ -184,7 +184,7 @@ func ExampleAlertsAPI_Update_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", query) + log.InfoContext(ctx, "found %v", query) alert, err := w.Alerts.Create(ctx, sql.CreateAlertRequest{ Alert: &sql.CreateAlertRequestAlert{ @@ -208,7 +208,7 @@ func ExampleAlertsAPI_Update_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", alert) + log.InfoContext(ctx, "found %v", alert) _, err = w.Alerts.Update(ctx, sql.UpdateAlertRequest{ Id: alert.Id, diff --git a/service/sql/dashboards_usage_test.go b/service/sql/dashboards_usage_test.go index 19e3809cf..b3dc16fd5 100755 --- a/service/sql/dashboards_usage_test.go +++ b/service/sql/dashboards_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/sql" ) @@ -26,7 +26,7 @@ func ExampleDashboardsAPI_Create_dashboards() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -50,7 +50,7 @@ func ExampleDashboardsAPI_Delete_dashboards() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.Dashboards.DeleteByDashboardId(ctx, created.Id) if err != nil { @@ -79,13 +79,13 @@ func ExampleDashboardsAPI_Get_dashboards() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) byId, err := w.Dashboards.GetByDashboardId(ctx, created.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -107,7 +107,7 @@ func ExampleDashboardsAPI_ListAll_dashboards() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -124,7 +124,7 @@ func ExampleDashboardsAPI_Restore_dashboards() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) err = w.Dashboards.Restore(ctx, sql.RestoreDashboardRequest{ DashboardId: created.Id, diff --git a/service/sql/data_sources_usage_test.go b/service/sql/data_sources_usage_test.go index 7a683b48e..a8b935451 100755 --- a/service/sql/data_sources_usage_test.go +++ b/service/sql/data_sources_usage_test.go @@ -6,7 +6,7 @@ import ( "context" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" ) func ExampleDataSourcesAPI_ListAll_queries() { @@ -20,7 +20,7 @@ func ExampleDataSourcesAPI_ListAll_queries() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", srcs) + log.InfoContext(ctx, "found %v", srcs) } @@ -35,6 +35,6 @@ func ExampleDataSourcesAPI_ListAll_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", srcs) + log.InfoContext(ctx, "found %v", srcs) } diff --git a/service/sql/queries_usage_test.go b/service/sql/queries_usage_test.go index 287646903..d0ac07ad2 100755 --- a/service/sql/queries_usage_test.go +++ b/service/sql/queries_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/sql" ) @@ -24,7 +24,7 @@ func ExampleQueriesAPI_Create_queries() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", srcs) + log.InfoContext(ctx, "found %v", srcs) query, err := w.Queries.Create(ctx, sql.CreateQueryRequest{ Query: &sql.CreateQueryRequestQuery{ @@ -37,7 +37,7 @@ func ExampleQueriesAPI_Create_queries() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", query) + log.InfoContext(ctx, "found %v", query) // cleanup @@ -59,7 +59,7 @@ func ExampleQueriesAPI_Create_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", srcs) + log.InfoContext(ctx, "found %v", srcs) query, err := w.Queries.Create(ctx, sql.CreateQueryRequest{ Query: &sql.CreateQueryRequestQuery{ @@ -72,7 +72,7 @@ func ExampleQueriesAPI_Create_alerts() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", query) + log.InfoContext(ctx, "found %v", query) // cleanup @@ -94,7 +94,7 @@ func ExampleQueriesAPI_Get_queries() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", srcs) + log.InfoContext(ctx, "found %v", srcs) query, err := w.Queries.Create(ctx, sql.CreateQueryRequest{ Query: &sql.CreateQueryRequestQuery{ @@ -107,13 +107,13 @@ func ExampleQueriesAPI_Get_queries() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", query) + log.InfoContext(ctx, "found %v", query) byId, err := w.Queries.GetById(ctx, query.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -135,7 +135,7 @@ func ExampleQueriesAPI_Update_queries() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", srcs) + log.InfoContext(ctx, "found %v", srcs) query, err := w.Queries.Create(ctx, sql.CreateQueryRequest{ Query: &sql.CreateQueryRequestQuery{ @@ -148,7 +148,7 @@ func ExampleQueriesAPI_Update_queries() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", query) + log.InfoContext(ctx, "found %v", query) updated, err := w.Queries.Update(ctx, sql.UpdateQueryRequest{ Id: query.Id, @@ -162,7 +162,7 @@ func ExampleQueriesAPI_Update_queries() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", updated) + log.InfoContext(ctx, "found %v", updated) // cleanup diff --git a/service/sql/statement_execution_usage_test.go b/service/sql/statement_execution_usage_test.go index a88bccf68..01b4db6a9 100755 --- a/service/sql/statement_execution_usage_test.go +++ b/service/sql/statement_execution_usage_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/catalog" "github.com/databricks/databricks-sdk-go/service/sql" @@ -30,7 +30,7 @@ func ExampleStatementExecutionAPI_Execute_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -39,7 +39,7 @@ func ExampleStatementExecutionAPI_Execute_tables() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) _, err = w.StatementExecution.ExecuteAndWait(ctx, sql.ExecuteStatementRequest{ WarehouseId: os.Getenv("TEST_DEFAULT_WAREHOUSE_ID"), @@ -82,7 +82,7 @@ func ExampleStatementExecutionAPI_Execute_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdCatalog) + log.InfoContext(ctx, "found %v", createdCatalog) createdSchema, err := w.Schemas.Create(ctx, catalog.CreateSchema{ Name: fmt.Sprintf("sdk-%x", time.Now().UnixNano()), @@ -91,7 +91,7 @@ func ExampleStatementExecutionAPI_Execute_shares() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", createdSchema) + log.InfoContext(ctx, "found %v", createdSchema) _, err = w.StatementExecution.ExecuteAndWait(ctx, sql.ExecuteStatementRequest{ WarehouseId: os.Getenv("TEST_DEFAULT_WAREHOUSE_ID"), diff --git a/service/sql/warehouses_usage_test.go b/service/sql/warehouses_usage_test.go index 6eb2f60fc..c2c7784c6 100755 --- a/service/sql/warehouses_usage_test.go +++ b/service/sql/warehouses_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/sql" ) @@ -35,7 +35,7 @@ func ExampleWarehousesAPI_Create_sqlWarehouses() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) // cleanup @@ -68,7 +68,7 @@ func ExampleWarehousesAPI_Edit_sqlWarehouses() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) _, err = w.Warehouses.Edit(ctx, sql.EditWarehouseRequest{ Id: created.Id, @@ -112,13 +112,13 @@ func ExampleWarehousesAPI_Get_sqlWarehouses() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", created) + log.InfoContext(ctx, "found %v", created) wh, err := w.Warehouses.GetById(ctx, created.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", wh) + log.InfoContext(ctx, "found %v", wh) // cleanup @@ -140,6 +140,6 @@ func ExampleWarehousesAPI_ListAll_sqlWarehouses() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } diff --git a/service/workspace/git_credentials_usage_test.go b/service/workspace/git_credentials_usage_test.go index 7a91ecbcf..db3f0ceca 100755 --- a/service/workspace/git_credentials_usage_test.go +++ b/service/workspace/git_credentials_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/workspace" ) @@ -28,7 +28,7 @@ func ExampleGitCredentialsAPI_Create_gitCredentials() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", cr) + log.InfoContext(ctx, "found %v", cr) // cleanup @@ -54,13 +54,13 @@ func ExampleGitCredentialsAPI_Get_gitCredentials() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", cr) + log.InfoContext(ctx, "found %v", cr) byId, err := w.GitCredentials.GetByCredentialId(ctx, cr.CredentialId) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -82,7 +82,7 @@ func ExampleGitCredentialsAPI_ListAll_gitCredentials() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", list) + log.InfoContext(ctx, "found %v", list) } @@ -101,7 +101,7 @@ func ExampleGitCredentialsAPI_Update_gitCredentials() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", cr) + log.InfoContext(ctx, "found %v", cr) err = w.GitCredentials.Update(ctx, workspace.UpdateCredentialsRequest{ CredentialId: cr.CredentialId, diff --git a/service/workspace/repos_usage_test.go b/service/workspace/repos_usage_test.go index 0aa2d3460..d33d1625e 100755 --- a/service/workspace/repos_usage_test.go +++ b/service/workspace/repos_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/workspace" ) @@ -30,7 +30,7 @@ func ExampleReposAPI_Create_repos() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", ri) + log.InfoContext(ctx, "found %v", ri) // cleanup @@ -58,13 +58,13 @@ func ExampleReposAPI_Get_repos() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", ri) + log.InfoContext(ctx, "found %v", ri) byId, err := w.Repos.GetByRepoId(ctx, ri.Id) if err != nil { panic(err) } - logger.Infof(ctx, "found %v", byId) + log.InfoContext(ctx, "found %v", byId) // cleanup @@ -86,7 +86,7 @@ func ExampleReposAPI_ListAll_repos() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", all) + log.InfoContext(ctx, "found %v", all) } @@ -107,7 +107,7 @@ func ExampleReposAPI_Update_repos() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", ri) + log.InfoContext(ctx, "found %v", ri) err = w.Repos.Update(ctx, workspace.UpdateRepoRequest{ RepoId: ri.Id, diff --git a/service/workspace/secrets_usage_test.go b/service/workspace/secrets_usage_test.go index 2fdc0c7fb..d75d6cc15 100755 --- a/service/workspace/secrets_usage_test.go +++ b/service/workspace/secrets_usage_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/iam" "github.com/databricks/databricks-sdk-go/service/workspace" @@ -70,7 +70,7 @@ func ExampleSecretsAPI_ListAcls_secrets() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", acls) + log.InfoContext(ctx, "found %v", acls) // cleanup @@ -99,7 +99,7 @@ func ExampleSecretsAPI_ListScopes_secrets() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", scopes) + log.InfoContext(ctx, "found %v", scopes) } @@ -125,7 +125,7 @@ func ExampleSecretsAPI_ListSecrets_secrets() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", scrts) + log.InfoContext(ctx, "found %v", scrts) // cleanup @@ -158,7 +158,7 @@ func ExampleSecretsAPI_PutAcl_secrets() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", group) + log.InfoContext(ctx, "found %v", group) scopeName := fmt.Sprintf("sdk-%x", time.Now().UnixNano()) diff --git a/service/workspace/workspace_usage_test.go b/service/workspace/workspace_usage_test.go index 083fe60b5..21397ae65 100755 --- a/service/workspace/workspace_usage_test.go +++ b/service/workspace/workspace_usage_test.go @@ -10,7 +10,7 @@ import ( "time" "github.com/databricks/databricks-sdk-go" - "github.com/databricks/databricks-sdk-go/logger" + "github.com/databricks/databricks-sdk-go/databricks/log" "github.com/databricks/databricks-sdk-go/service/workspace" ) @@ -37,7 +37,7 @@ func ExampleWorkspaceAPI_Export_workspaceIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", exportResponse) + log.InfoContext(ctx, "found %v", exportResponse) } @@ -60,7 +60,7 @@ func ExampleWorkspaceAPI_GetStatus_genericPermissions() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", obj) + log.InfoContext(ctx, "found %v", obj) } @@ -83,7 +83,7 @@ func ExampleWorkspaceAPI_GetStatus_workspaceIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", getStatusResponse) + log.InfoContext(ctx, "found %v", getStatusResponse) } @@ -224,6 +224,6 @@ func ExampleWorkspaceAPI_ListAll_workspaceIntegration() { if err != nil { panic(err) } - logger.Infof(ctx, "found %v", objects) + log.InfoContext(ctx, "found %v", objects) }