Skip to content

Commit

Permalink
moved telemetry in command context
Browse files Browse the repository at this point in the history
  • Loading branch information
JulesFaucherre committed Aug 1, 2023
1 parent c357de6 commit eaf3f6b
Show file tree
Hide file tree
Showing 35 changed files with 268 additions and 185 deletions.
10 changes: 5 additions & 5 deletions cmd/build.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cmd

import (
"github.com/CircleCI-Public/circleci-cli/cmd/create_telemetry"
"github.com/CircleCI-Public/circleci-cli/local"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/CircleCI-Public/circleci-cli/telemetry"
Expand All @@ -18,11 +17,12 @@ func newLocalExecuteCommand(config *settings.Config) *cobra.Command {
return nil
},
RunE: func(cmd *cobra.Command, _ []string) error {
telemetryClient := create_telemetry.CreateTelemetry(config)
defer telemetryClient.Close()

err := local.Execute(cmd.Flags(), config, args)
_ = telemetryClient.Track(telemetry.CreateLocalExecuteEvent(create_telemetry.GetCommandInformation(cmd, true)))

telemetryClient, ok := telemetry.FromContext(cmd.Context())
if ok {
_ = telemetryClient.Track(telemetry.CreateLocalExecuteEvent(telemetry.GetCommandInformation(cmd, true)))
}

return err
},
Expand Down
8 changes: 4 additions & 4 deletions cmd/completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cmd
import (
"os"

"github.com/CircleCI-Public/circleci-cli/cmd/create_telemetry"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/CircleCI-Public/circleci-cli/telemetry"
"github.com/spf13/cobra"
Expand All @@ -14,9 +13,10 @@ func newCompletionCommand(config *settings.Config) *cobra.Command {
Use: "completion",
Short: "Generate shell completion scripts",
PersistentPreRun: func(cmd *cobra.Command, _ []string) {
telemetryClient := create_telemetry.CreateTelemetry(config)
defer telemetryClient.Close()
_ = telemetryClient.Track(telemetry.CreateCompletionCommand(create_telemetry.GetCommandInformation(cmd, false)))
telemetryClient, ok := telemetry.FromContext(cmd.Context())
if ok {
_ = telemetryClient.Track(telemetry.CreateCompletionCommand(telemetry.GetCommandInformation(cmd, true)))
}
},
Run: func(cmd *cobra.Command, _ []string) {
err := cmd.Help()
Expand Down
37 changes: 13 additions & 24 deletions cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/CircleCI-Public/circleci-config/labeling"
"github.com/CircleCI-Public/circleci-config/labeling/codebase"

"github.com/CircleCI-Public/circleci-cli/cmd/create_telemetry"
"github.com/CircleCI-Public/circleci-cli/config"
"github.com/CircleCI-Public/circleci-cli/filetree"
"github.com/CircleCI-Public/circleci-cli/proxy"
Expand All @@ -30,33 +29,21 @@ var configAnnotations = map[string]string{
}

func newConfigCommand(globalConfig *settings.Config) *cobra.Command {
var telemetryClient telemetry.Client

closeTelemetryClient := func() {
if telemetryClient != nil {
telemetryClient.Close()
telemetryClient = nil
}
}

configCmd := &cobra.Command{
Use: "config",
Short: "Operate on build config files",
PersistentPreRun: func(_ *cobra.Command, _ []string) {
telemetryClient = create_telemetry.CreateTelemetry(globalConfig)
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
closeTelemetryClient()
},
}

packCommand := &cobra.Command{
Use: "pack <path>",
Short: "Pack up your CircleCI configuration into a single file.",
RunE: func(cmd *cobra.Command, args []string) error {
defer closeTelemetryClient()
err := packConfig(args)
_ = telemetryClient.Track(telemetry.CreateConfigEvent(create_telemetry.GetCommandInformation(cmd, true), err))

telemetryClient, ok := telemetry.FromContext(cmd.Context())
if ok {
_ = telemetryClient.Track(telemetry.CreateConfigEvent(telemetry.GetCommandInformation(cmd, true), err))
}
return err
},
Args: cobra.ExactArgs(1),
Expand All @@ -69,8 +56,6 @@ func newConfigCommand(globalConfig *settings.Config) *cobra.Command {
Aliases: []string{"check"},
Short: "Check that the config file is well formed.",
RunE: func(cmd *cobra.Command, args []string) error {
defer closeTelemetryClient()

compiler := config.New(globalConfig)
orgID, _ := cmd.Flags().GetString("org-id")
orgSlug, _ := cmd.Flags().GetString("org-slug")
Expand All @@ -89,7 +74,10 @@ func newConfigCommand(globalConfig *settings.Config) *cobra.Command {
IgnoreDeprecatedImages: ignoreDeprecatedImages,
VerboseOutput: verboseOutput,
})
_ = telemetryClient.Track(telemetry.CreateConfigEvent(create_telemetry.GetCommandInformation(cmd, true), err))
telemetryClient, ok := telemetry.FromContext(cmd.Context())
if ok {
_ = telemetryClient.Track(telemetry.CreateConfigEvent(telemetry.GetCommandInformation(cmd, true), err))
}

return err
},
Expand All @@ -111,8 +99,6 @@ func newConfigCommand(globalConfig *settings.Config) *cobra.Command {
Use: "process <path>",
Short: "Validate config and display expanded configuration.",
RunE: func(cmd *cobra.Command, args []string) error {
defer closeTelemetryClient()

compiler := config.New(globalConfig)
pipelineParamsFilePath, _ := cmd.Flags().GetString("pipeline-parameters")
orgID, _ := cmd.Flags().GetString("org-id")
Expand All @@ -131,7 +117,10 @@ func newConfigCommand(globalConfig *settings.Config) *cobra.Command {
PipelineParamsFilePath: pipelineParamsFilePath,
VerboseOutput: verboseOutput,
})
_ = telemetryClient.Track(telemetry.CreateConfigEvent(create_telemetry.GetCommandInformation(cmd, true), err))
telemetryClient, ok := telemetry.FromContext(cmd.Context())
if ok {
_ = telemetryClient.Track(telemetry.CreateConfigEvent(telemetry.GetCommandInformation(cmd, true), err))
}
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ var _ = Describe("Config", func() {
"config", "pack",
"--skip-update-check",
filepath.Join("testdata", "hugo-pack", ".circleci"),
"--mock-telemetry", tempSettings.TelemetryDestPath,
)
command.Env = append(command.Env, fmt.Sprintf("MOCK_TELEMETRY=%s", tempSettings.TelemetryDestPath))
})

AfterEach(func() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package create_telemetry
package cmd

import (
"fmt"
Expand Down Expand Up @@ -62,8 +62,12 @@ func (client nullTelemetryAPIClient) GetMyUserId() (string, error) {

// Make sure the user gave their approval for the telemetry and
func CreateTelemetry(config *settings.Config) telemetry.Client {
if config.MockTelemetry != "" {
return telemetry.CreateFileTelemetry(config.MockTelemetry)
mockTelemetry := config.MockTelemetry
if mockTelemetry == "" {
mockTelemetry = os.Getenv("MOCK_TELEMETRY")
}
if mockTelemetry != "" {
return telemetry.CreateFileTelemetry(mockTelemetry)
}

if config.IsTelemetryDisabled {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package create_telemetry
package cmd

import (
"path/filepath"
Expand Down
12 changes: 6 additions & 6 deletions cmd/diagnostic.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

"github.com/CircleCI-Public/circleci-cli/api"
"github.com/CircleCI-Public/circleci-cli/api/graphql"
"github.com/CircleCI-Public/circleci-cli/cmd/create_telemetry"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/CircleCI-Public/circleci-cli/telemetry"
"github.com/spf13/cobra"
Expand All @@ -30,12 +29,13 @@ func newDiagnosticCommand(config *settings.Config) *cobra.Command {
opts.args = args
opts.cl = graphql.NewClient(config.HTTPClient, config.Host, config.Endpoint, config.Token, config.Debug)
},
RunE: func(_ *cobra.Command, _ []string) error {
telemetryClient := create_telemetry.CreateTelemetry(config)
defer telemetryClient.Close()

RunE: func(cmd *cobra.Command, _ []string) error {
err := diagnostic(opts)
_ = telemetryClient.Track(telemetry.CreateDiagnosticEvent(err))

telemetryClient, ok := telemetry.FromContext(cmd.Context())
if ok {
_ = telemetryClient.Track(telemetry.CreateDiagnosticEvent(err))
}

return err
},
Expand Down
4 changes: 2 additions & 2 deletions cmd/diagnostic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ var _ = Describe("Diagnostic", func() {
command = commandWithHome(pathCLI, tempSettings.Home,
"diagnostic",
"--skip-update-check",
"--host", tempSettings.TestServer.URL(),
"--mock-telemetry", tempSettings.TelemetryDestPath)
"--host", tempSettings.TestServer.URL())
command.Env = append(command.Env, fmt.Sprintf("MOCK_TELEMETRY=%s", tempSettings.TelemetryDestPath))
tempSettings.Config.Write([]byte(`token: mytoken`))
session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)
Expect(err).ShouldNot(HaveOccurred())
Expand Down
12 changes: 6 additions & 6 deletions cmd/follow.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"

"github.com/CircleCI-Public/circleci-cli/api"
"github.com/CircleCI-Public/circleci-cli/cmd/create_telemetry"
"github.com/CircleCI-Public/circleci-cli/git"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/CircleCI-Public/circleci-cli/telemetry"
Expand Down Expand Up @@ -55,12 +54,13 @@ func followProjectCommand(config *settings.Config) *cobra.Command {
followCommand := &cobra.Command{
Use: "follow",
Short: "Attempt to follow the project for the current git repository.",
RunE: func(_ *cobra.Command, _ []string) error {
telemetryClient := create_telemetry.CreateTelemetry(config)
defer telemetryClient.Close()

RunE: func(cmd *cobra.Command, _ []string) error {
err := followProject(opts)
_ = telemetryClient.Track(telemetry.CreateFollowEvent(err))

telemetryClient, ok := telemetry.FromContext(cmd.Context())
if ok {
_ = telemetryClient.Track(telemetry.CreateFollowEvent(err))
}

return err
},
Expand Down
18 changes: 7 additions & 11 deletions cmd/info/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package info

import (
"github.com/CircleCI-Public/circleci-cli/api/info"
"github.com/CircleCI-Public/circleci-cli/cmd/create_telemetry"
"github.com/CircleCI-Public/circleci-cli/cmd/validator"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/CircleCI-Public/circleci-cli/telemetry"
Expand All @@ -13,9 +12,8 @@ import (

// infoOptions info command options
type infoOptions struct {
cfg *settings.Config
validator validator.Validator
createTelemetry func() telemetry.Client
cfg *settings.Config
validator validator.Validator
}

// NewInfoCommand information cobra command creation
Expand All @@ -25,9 +23,6 @@ func NewInfoCommand(config *settings.Config, preRunE validator.Validator) *cobra
opts := infoOptions{
cfg: config,
validator: preRunE,
createTelemetry: func() telemetry.Client {
return create_telemetry.CreateTelemetry(config)
},
}
infoCommand := &cobra.Command{
Use: "info",
Expand All @@ -47,11 +42,12 @@ func orgInfoCommand(client info.InfoClient, opts infoOptions) *cobra.Command {
Long: `View your Organizations' names and ids.`,
PreRunE: opts.validator,
RunE: func(cmd *cobra.Command, _ []string) error {
telemetryClient := opts.createTelemetry()
defer telemetryClient.Close()

err := getOrgInformation(cmd, client)
_ = telemetryClient.Track(telemetry.CreateInfoEvent(create_telemetry.GetCommandInformation(cmd, true), err))

telemetryClient, ok := telemetry.FromContext(cmd.Context())
if ok {
_ = telemetryClient.Track(telemetry.CreateInfoEvent(telemetry.GetCommandInformation(cmd, true), err))
}

return err
},
Expand Down
41 changes: 24 additions & 17 deletions cmd/info/info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ package info

import (
"bytes"
"encoding/json"
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"

"github.com/CircleCI-Public/circleci-cli/clitest"
"github.com/CircleCI-Public/circleci-cli/cmd/validator"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/CircleCI-Public/circleci-cli/telemetry"
Expand Down Expand Up @@ -110,10 +108,19 @@ func TestFailedValidator(t *testing.T) {
assert.Error(t, err, errorMessage)
}

func TestTelemetry(t *testing.T) {
tempSettings := clitest.WithTempSettings()
defer tempSettings.Close()
type testTelemetryClient struct {
events []telemetry.Event
}

func (cli *testTelemetryClient) Track(event telemetry.Event) error {
cli.events = append(cli.events, event)
return nil
}

func (cli *testTelemetryClient) Close() error { return nil }

func TestTelemetry(t *testing.T) {
telemetryClient := testTelemetryClient{make([]telemetry.Event, 0)}
// Test server
var serverHandler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
Expand All @@ -124,25 +131,25 @@ func TestTelemetry(t *testing.T) {

// Test command
config := &settings.Config{
Token: "testtoken",
HTTPClient: http.DefaultClient,
Host: server.URL,
MockTelemetry: tempSettings.TelemetryDestPath,
Token: "testtoken",
HTTPClient: http.DefaultClient,
Host: server.URL,
}
cmd := NewInfoCommand(config, nil)
cmd.SetArgs([]string{"org"})
ctx := cmd.Context()
if ctx == nil {
ctx = context.Background()
}
cmd.SetContext(telemetry.NewContext(ctx, &telemetryClient))

// Execute
err := cmd.Execute()

assert.NilError(t, err)
// We compare the
content, err := os.ReadFile(tempSettings.TelemetryDestPath)
assert.NilError(t, err)

result := []telemetry.Event{}
err = json.Unmarshal(content, &result)
assert.NilError(t, err)
assert.DeepEqual(t, result, []telemetry.Event{
// Read the telemetry events and compare them
assert.DeepEqual(t, telemetryClient.events, []telemetry.Event{
telemetry.CreateInfoEvent(telemetry.CommandInfo{
Name: "org",
LocalArgs: map[string]string{"help": "false"},
Expand Down
10 changes: 5 additions & 5 deletions cmd/namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

"github.com/CircleCI-Public/circleci-cli/api"
"github.com/CircleCI-Public/circleci-cli/api/graphql"
"github.com/CircleCI-Public/circleci-cli/cmd/create_telemetry"
"github.com/CircleCI-Public/circleci-cli/prompt"
"github.com/CircleCI-Public/circleci-cli/settings"
"github.com/CircleCI-Public/circleci-cli/telemetry"
Expand Down Expand Up @@ -70,17 +69,18 @@ Please note that at this time all namespaces created in the registry are world-r
return validateToken(opts.cfg)
},
RunE: func(cmd *cobra.Command, _ []string) error {
telemetryClient := create_telemetry.CreateTelemetry(config)
defer telemetryClient.Close()

if opts.integrationTesting {
opts.tty = createNamespaceTestUI{
confirm: true,
}
}

err := createNamespace(cmd, opts)
_ = telemetryClient.Track(telemetry.CreateNamespaceEvent(create_telemetry.GetCommandInformation(cmd, true)))

telemetryClient, ok := telemetry.FromContext(cmd.Context())
if ok {
_ = telemetryClient.Track(telemetry.CreateNamespaceEvent(telemetry.GetCommandInformation(cmd, true)))
}

return err
},
Expand Down
Loading

0 comments on commit eaf3f6b

Please sign in to comment.