Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: Add posthog telemetry integration #37

Merged
merged 1 commit into from
Aug 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,8 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
run: |
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -ldflags="-s -w" -o build/pizza-${{ matrix.goos }}-${{ matrix.goarch }}
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build \
-ldflags="-s -w" \
-ldflags="-X 'github.com/open-sauced/pizza-cli/pkg/utils.writeOnlyPublicPosthogKey=${{ secrets.POSTHOG_WRITE_PUBLIC_KEY }}'" \
-o build/pizza-${{ matrix.goos }}-${{ matrix.goarch }}
gh release upload ${{ needs.release.outputs.release-tag }} build/pizza-${{ matrix.goos }}-${{ matrix.goarch }}
40 changes: 33 additions & 7 deletions cmd/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,60 @@ import (

"github.com/cli/browser"
"github.com/open-sauced/pizza-cli/pkg/constants"
"github.com/open-sauced/pizza-cli/pkg/utils"
"github.com/spf13/cobra"
)

//go:embed success.html
var successHTML string

// Options are the persistent options for the login command
type Options struct {
// telemetry for capturing CLI events
telemetry *utils.PosthogCliClient
}

const loginLongDesc string = `Log into OpenSauced.

This command initiates the GitHub auth flow to log you into the OpenSauced application by launching your browser`

func NewLoginCommand() *cobra.Command {
opts := &Options{}

cmd := &cobra.Command{
Use: "login",
Short: "Log into the CLI application via GitHub",
Long: loginLongDesc,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return run()
username, err := run()

disableTelem, _ := cmd.Flags().GetBool("disable-telemetry")

if !disableTelem {
opts.telemetry = utils.NewPosthogCliClient()
defer opts.telemetry.Done()

if err != nil {
opts.telemetry.CaptureFailedLogin()
} else {
opts.telemetry.CaptureLogin(username)
}
}

return err
},
}

return cmd
}

func run() error {
func run() (string, error) {
username := ""

codeVerifier, codeChallenge, err := pkce(codeChallengeLength)
if err != nil {
return fmt.Errorf("PKCE error: %v", err.Error())
return "", fmt.Errorf("PKCE error: %v", err.Error())
}

supabaseAuthURL := fmt.Sprintf("https://%s.supabase.co/auth/v1/authorize", supabaseID)
Expand Down Expand Up @@ -107,7 +133,7 @@ func run() error {
fmt.Println("Error writing response:", err.Error())
}

username := sessionData.User.UserMetadata["user_name"]
username = sessionData.User.UserMetadata["user_name"].(string)
fmt.Println("πŸŽ‰ Login successful πŸŽ‰")
fmt.Println("Welcome aboard", username, "πŸ•")
})
Expand All @@ -130,17 +156,17 @@ func run() error {
select {
case err := <-errCh:
if err != nil && err != http.ErrServerClosed {
return err
return "", err
}
case <-time.After(60 * time.Second):
shutdown(server)
return errors.New("authentication timeout")
return "", errors.New("authentication timeout")
case <-interruptCh:
fmt.Println("\nAuthentication interrupted❗️")
shutdown(server)
os.Exit(0)
}
return nil
return username, nil
}

func getSession(authCode, codeVerifier string) (*accessTokenResponse, error) {
Expand Down
13 changes: 13 additions & 0 deletions cmd/bake/bake.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"os"

"github.com/open-sauced/pizza-cli/pkg/api"
"github.com/open-sauced/pizza-cli/pkg/utils"
"github.com/spf13/cobra"

"gopkg.in/yaml.v3"
Expand All @@ -31,6 +32,9 @@ type Options struct {

// FilePath is the location of the file containing a batch of repos to be baked
FilePath string

// telemetry for capturing CLI events
telemetry *utils.PosthogCliClient
}

const bakeLongDesc string = `WARNING: Proof of concept feature.
Expand All @@ -53,6 +57,7 @@ func NewBakeCommand() *cobra.Command {
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
disableTelem, _ := cmd.Flags().GetBool("disable-telemetry")
endpoint, _ := cmd.Flags().GetString("endpoint")
useBeta, _ := cmd.Flags().GetBool("beta")

Expand All @@ -63,6 +68,14 @@ func NewBakeCommand() *cobra.Command {
opts.APIClient = api.NewClient(endpoint)

opts.URLs = append(opts.URLs, args...)

if !disableTelem {
opts.telemetry = utils.NewPosthogCliClient()
defer opts.telemetry.Done()

opts.telemetry.CaptureBake(opts.URLs)
}

return run(opts)
},
}
Expand Down
13 changes: 13 additions & 0 deletions cmd/repo-query/repo-query.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"strings"

"github.com/open-sauced/pizza-cli/pkg/api"
"github.com/open-sauced/pizza-cli/pkg/utils"
"github.com/spf13/cobra"
)

Expand All @@ -24,6 +25,9 @@ type Options struct {
// URL is the git repo URL that will be indexed
URL string

// telemetry for capturing CLI events
telemetry *utils.PosthogCliClient

branch string
}

Expand All @@ -49,6 +53,7 @@ func NewRepoQueryCommand() *cobra.Command {
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
disableTelem, _ := cmd.Flags().GetBool("disable-telemetry")
endpoint, _ := cmd.Flags().GetString("endpoint")
useBeta, _ := cmd.Flags().GetBool("beta")

Expand All @@ -66,6 +71,14 @@ func NewRepoQueryCommand() *cobra.Command {
opts.APIClient = api.NewClient(endpoint)

opts.URL = args[0]

if !disableTelem {
opts.telemetry = utils.NewPosthogCliClient()
defer opts.telemetry.Done()

opts.telemetry.CaptureRepoQuery(opts.URL)
}

return run(opts)
},
}
Expand Down
1 change: 1 addition & 0 deletions cmd/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func NewRootCommand() (*cobra.Command, error) {

cmd.PersistentFlags().StringP("endpoint", "e", api.APIEndpoint, "The API endpoint to send requests to")
cmd.PersistentFlags().Bool("beta", false, fmt.Sprintf("Shorthand for using the beta OpenSauced API endpoint (\"%s\"). Superceds the '--endpoint' flag", api.BetaAPIEndpoint))
cmd.PersistentFlags().Bool("disable-telemetry", false, "Disable sending telemetry data to OpenSauced")

cmd.AddCommand(bake.NewBakeCommand())
cmd.AddCommand(repoquery.NewRepoQueryCommand())
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ go 1.20

require (
github.com/cli/browser v1.2.0
github.com/posthog/posthog-go v0.0.0-20230801140217-d607812dee69
github.com/spf13/cobra v1.7.0
github.com/spf13/pflag v1.0.5
golang.org/x/term v0.9.0
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/google/uuid v1.3.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
golang.org/x/sys v0.9.0 // indirect
)
11 changes: 11 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/cli/browser v1.2.0 h1:yvU7e9qf97kZqGFX6n2zJPHsmSObY9ske+iCvKelvXg=
github.com/cli/browser v1.2.0/go.mod h1:xFFnXLVcAyW9ni0cuo6NnrbCP75JxJ0RO7VtCBiH/oI=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posthog/posthog-go v0.0.0-20230801140217-d607812dee69 h1:01dHVodha5BzrMtVmcpPeA4VYbZEsTXQ6m4123zQXJk=
github.com/posthog/posthog-go v0.0.0-20230801140217-d607812dee69/go.mod h1:migYMxlAqcnQy+3eN8mcL0b2tpKy6R+8Zc0lxwk4dKM=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/urfave/cli v1.22.5/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s=
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.9.0 h1:GRRCnKYhdQrD8kfRAdQ6Zcw1P0OcELxGLKJvtjVMZ28=
golang.org/x/term v0.9.0/go.mod h1:M6DEAAIenWoTxdKrOltXcmDY3rSplQUkrvaDU5FcQyo=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
87 changes: 87 additions & 0 deletions pkg/utils/posthog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package utils

import (
"github.com/posthog/posthog-go"
)

var (
writeOnlyPublicPosthogKey = "dev"
posthogEndpoint = "https://app.posthog.com"
)

// PosthogCliClient is a wrapper around the posthog-go client and is used as a
// API entrypoint for sending OpenSauced telemetry data for CLI commands
type PosthogCliClient struct {
client posthog.Client
}

// NewPosthogCliClient returns a PosthogCliClient which can be used to capture
// telemetry events for CLI users
func NewPosthogCliClient() *PosthogCliClient {
client, err := posthog.NewWithConfig(
writeOnlyPublicPosthogKey,
posthog.Config{
Endpoint: posthogEndpoint,
},
)

if err != nil {
// Should never happen since we aren't setting posthog.Config data that
// would cause its validation to fail
panic(err)
}

return &PosthogCliClient{
client: client,
}
}

// Done should always be called in order to flush the Posthog buffers before
// the CLI exits to ensure all events are accurately captured.
//
//nolint:errcheck
func (p *PosthogCliClient) Done() {
p.client.Close()
}

// CaptureBake gathers telemetry on git repos that are being baked
//
//nolint:errcheck
func (p *PosthogCliClient) CaptureBake(urls []string) {
p.client.Enqueue(posthog.Capture{
DistinctId: "pizza-bakers",
Event: "cli_user baked repo",
Properties: posthog.NewProperties().Set("clone_url", urls),
})
}

// CaptureLogin gathers telemetry on users who log into OpenSauced via the CLI
//
//nolint:errcheck
func (p *PosthogCliClient) CaptureLogin(username string) {
p.client.Enqueue(posthog.Capture{
DistinctId: username,
Event: "cli_user logged in",
})
}

// CaptureFailedLogin gathers telemetry on failed logins via the CLI
//
//nolint:errcheck
func (p *PosthogCliClient) CaptureFailedLogin() {
p.client.Enqueue(posthog.Capture{
DistinctId: "login-failures",
Event: "cli_user failed log in",
})
}

// CaptureRepoQuery gathers telemetry on users using the repo-query service
//
//nolint:errcheck
func (p *PosthogCliClient) CaptureRepoQuery(url string) {
p.client.Enqueue(posthog.Capture{
DistinctId: "repo-queriers",
Event: "cli_user used repo-query",
Properties: posthog.NewProperties().Set("github_url", url),
})
}