Move code for including command name in user agent (#203)

This commit is contained in:
Pieter Noordhuis 2023-02-15 10:33:35 +01:00 committed by GitHub
parent 2e01473902
commit 3851b59bbd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 37 additions and 32 deletions

View File

@ -1,42 +1,10 @@
package root package root
import ( import (
"context"
"strings"
"github.com/databricks/bricks/internal/build" "github.com/databricks/bricks/internal/build"
"github.com/databricks/databricks-sdk-go/useragent" "github.com/databricks/databricks-sdk-go/useragent"
"github.com/spf13/cobra"
) )
// commandSeparator joins command names in a command hierachy.
// We enforce no command name contains this character.
// See unit test [main.TestCommandsDontUseUnderscoreInName].
const commandSeparator = "_"
// commandString walks up the command hierarchy of the specified
// command to build a string representing this hierarchy.
func commandString(cmd *cobra.Command) string {
reversed := []string{cmd.Name()}
cmd.VisitParents(func(p *cobra.Command) {
if !p.HasParent() {
return
}
reversed = append(reversed, p.Name())
})
ordered := make([]string, 0, len(reversed))
for i := len(reversed) - 1; i >= 0; i-- {
ordered = append(ordered, reversed[i])
}
return strings.Join(ordered, commandSeparator)
}
func withCommandInUserAgent(ctx context.Context, cmd *cobra.Command) context.Context {
return useragent.InContext(ctx, "cmd", commandString(cmd))
}
func init() { func init() {
useragent.WithProduct("bricks", build.GetInfo().Version) useragent.WithProduct("bricks", build.GetInfo().Version)
} }

View File

@ -0,0 +1,37 @@
package root
import (
"context"
"strings"
"github.com/databricks/databricks-sdk-go/useragent"
"github.com/spf13/cobra"
)
// commandSeparator joins command names in a command hierachy.
// We enforce no command name contains this character.
// See unit test [main.TestCommandsDontUseUnderscoreInName].
const commandSeparator = "_"
// commandString walks up the command hierarchy of the specified
// command to build a string representing this hierarchy.
func commandString(cmd *cobra.Command) string {
reversed := []string{cmd.Name()}
cmd.VisitParents(func(p *cobra.Command) {
if !p.HasParent() {
return
}
reversed = append(reversed, p.Name())
})
ordered := make([]string, 0, len(reversed))
for i := len(reversed) - 1; i >= 0; i-- {
ordered = append(ordered, reversed[i])
}
return strings.Join(ordered, commandSeparator)
}
func withCommandInUserAgent(ctx context.Context, cmd *cobra.Command) context.Context {
return useragent.InContext(ctx, "cmd", commandString(cmd))
}