Skip to content

feat(telemetry): add PostHog event tracking to publish and run commands #1607

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

Merged
merged 12 commits into from
Jul 19, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
refactor: clean up for send null logic
  • Loading branch information
amirabbas-gh authored and mohebifar committed Jul 19, 2025
commit e342bba660f1c713664128af5c60b3749b0bc930
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,8 @@
"statusBar.background": "#d6ff62",
"statusBar.foreground": "#0B151E",
"statusBar.border": "#0B151E"
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
Copy link
Member

Choose a reason for hiding this comment

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

remove this

}
}
34 changes: 15 additions & 19 deletions crates/cli/src/commands/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use tempfile::TempDir;
use walkdir::WalkDir;

use crate::auth::TokenStorage;
use codemod_telemetry::send_event::{BaseEvent, PostHogSender, TelemetrySender};
use codemod_telemetry::send_event::{BaseEvent, TelemetrySender};

#[derive(Args, Debug)]
pub struct Command {
Expand Down Expand Up @@ -119,7 +119,7 @@ struct PublishedPackage {
published_at: String,
}

pub async fn handler(args: &Command, telemetry: &PostHogSender) -> Result<()> {
pub async fn handler(args: &Command, telemetry: &dyn TelemetrySender) -> Result<()> {
let package_path = args
.path
.as_ref()
Expand Down Expand Up @@ -200,23 +200,19 @@ pub async fn handler(args: &Command, telemetry: &PostHogSender) -> Result<()> {

let cli_version = env!("CARGO_PKG_VERSION");

if std::env::var("DISABLE_ANALYTICS") == Ok("false".to_string())
|| std::env::var("DISABLE_ANALYTICS").is_err()
{
let _ = telemetry
.send_event(
BaseEvent {
kind: "codemodPublished".to_string(),
properties: HashMap::from([
("codemodName".to_string(), manifest.name.clone()),
("version".to_string(), manifest.version.clone()),
("cliVersion".to_string(), cli_version.to_string()),
]),
},
None,
)
.await;
}
let _ = telemetry
.send_event(
BaseEvent {
kind: "codemodPublished".to_string(),
properties: HashMap::from([
("codemodName".to_string(), manifest.name.clone()),
("version".to_string(), manifest.version.clone()),
("cliVersion".to_string(), cli_version.to_string()),
]),
},
None,
)
.await;

println!("✅ Package published successfully!");
println!("📦 {}", format_package_name(&response.package));
Expand Down
53 changes: 39 additions & 14 deletions crates/cli/src/commands/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::workflow_runner::{run_workflow, WorkflowRunConfig};
use butterflow_core::engine::{Engine, GLOBAL_STATS};
use butterflow_core::registry::{RegistryClient, RegistryConfig, RegistryError};
use codemod_sandbox::sandbox::engine::ExecutionStats;
use codemod_telemetry::send_event::{BaseEvent, PostHogSender, TelemetrySender};
use codemod_telemetry::send_event::{BaseEvent, TelemetrySender};

#[derive(Args, Debug)]
pub struct Command {
Expand Down Expand Up @@ -46,7 +46,11 @@ pub struct Command {
allow_dirty: bool,
}

pub async fn handler(engine: &Engine, args: &Command, telemetry: &PostHogSender) -> Result<()> {
pub async fn handler(
engine: &Engine,
args: &Command,
telemetry: &dyn TelemetrySender,
) -> Result<()> {
// Create auth provider
let auth_provider = CliAuthProvider::new()?;

Expand Down Expand Up @@ -103,34 +107,55 @@ pub async fn handler(engine: &Engine, args: &Command, telemetry: &PostHogSender)
&args.args,
args.dry_run,
)
.await?;
.await;

let cli_version = env!("CARGO_PKG_VERSION");
let execution_id: [u8; 20] = rand::thread_rng().gen();
let execution_id = base64::Engine::encode(
&base64::engine::general_purpose::URL_SAFE_NO_PAD,
execution_id,
);

if std::env::var("DISABLE_ANALYTICS") == Ok("false".to_string())
|| std::env::var("DISABLE_ANALYTICS").is_err()
{
if let Err(e) = stats {
let _ = telemetry
.send_event(
BaseEvent {
kind: "codemodExecuted".to_string(),
kind: "failedToExecuteCommand".to_string(),
properties: HashMap::from([
("codemodName".to_string(), args.package.clone()),
("executionId".to_string(), execution_id.clone()),
("fileCount".to_string(), stats.files_modified.to_string()),
("cliVersion".to_string(), cli_version.to_string()),
(
"commandName".to_string(),
"codemod.executeCodemod".to_string(),
),
]),
},
None,
)
.await;
return Err(anyhow::anyhow!("Error executing codemod: {}", e));
Copy link
Preview

Copilot AI Jul 19, 2025

Choose a reason for hiding this comment

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

The original error information is being lost by wrapping it in a new anyhow error with just the Display representation. Consider using return Err(e) or .context() to preserve the error chain.

Copilot uses AI. Check for mistakes.

}

let cli_version = env!("CARGO_PKG_VERSION");
let execution_id: [u8; 20] = rand::thread_rng().gen();
let execution_id = base64::Engine::encode(
&base64::engine::general_purpose::URL_SAFE_NO_PAD,
execution_id,
);

let _ = telemetry
.send_event(
BaseEvent {
kind: "codemodExecuted".to_string(),
properties: HashMap::from([
("codemodName".to_string(), args.package.clone()),
("executionId".to_string(), execution_id.clone()),
(
"fileCount".to_string(),
stats.unwrap().files_modified.to_string(),
),
("cliVersion".to_string(), cli_version.to_string()),
]),
},
None,
)
.await;

Ok(())
}

Expand Down
34 changes: 24 additions & 10 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ mod engine;
mod workflow_runner;
use ascii_art::print_ascii_art;
use auth::TokenStorage;
use codemod_telemetry::send_event::{PostHogSender, TelemetrySenderOptions};
use codemod_telemetry::{
send_event::{PostHogSender, TelemetrySender, TelemetrySenderOptions},
send_null::NullSender,
};

#[derive(Parser)]
#[command(name = "codemod")]
Expand Down Expand Up @@ -142,7 +145,7 @@ fn is_package_name(arg: &str) -> bool {
async fn handle_implicit_run_command(
engine: &butterflow_core::engine::Engine,
trailing_args: Vec<String>,
telemetry_sender: &PostHogSender,
telemetry_sender: &dyn TelemetrySender,
) -> Result<bool> {
if trailing_args.is_empty() {
return Ok(false);
Expand Down Expand Up @@ -199,11 +202,20 @@ async fn main() -> Result<()> {
let auth = storage.load_auth("https://app.codemod.com")?;
let auth = auth.unwrap();

let telemetry_sender = PostHogSender::new(TelemetrySenderOptions {
distinct_id: auth.user.id.clone(),
cloud_role: "cli".to_string(),
})
.await;
let telemetry_sender: Box<dyn codemod_telemetry::send_event::TelemetrySender> =
if std::env::var("DISABLE_ANALYTICS") == Ok("false".to_string())
|| std::env::var("DISABLE_ANALYTICS").is_err()
{
Box::new(
PostHogSender::new(TelemetrySenderOptions {
distinct_id: auth.user.id.clone(),
cloud_role: "CLI".to_string(),
})
.await,
)
} else {
Box::new(NullSender {})
};

// Handle command or implicit run
match &cli.command {
Expand Down Expand Up @@ -248,13 +260,13 @@ async fn main() -> Result<()> {
commands::whoami::handler(args).await?;
}
Some(Commands::Publish(args)) => {
commands::publish::handler(args, &telemetry_sender).await?;
commands::publish::handler(args, telemetry_sender.as_ref()).await?;
}
Some(Commands::Search(args)) => {
commands::search::handler(args).await?;
}
Some(Commands::Run(args)) => {
commands::run::handler(&engine, args, &telemetry_sender).await?;
commands::run::handler(&engine, args, telemetry_sender.as_ref()).await?;
}
Some(Commands::Unpublish(args)) => {
commands::unpublish::handler(args).await?;
Expand All @@ -264,7 +276,9 @@ async fn main() -> Result<()> {
}
None => {
// Try to parse as implicit run command
if !handle_implicit_run_command(&engine, cli.trailing_args, &telemetry_sender).await? {
if !handle_implicit_run_command(&engine, cli.trailing_args, telemetry_sender.as_ref())
.await?
{
// No valid subcommand or package name provided, show help
print_ascii_art();
eprintln!("No command provided. Use --help for usage information.");
Expand Down
1 change: 1 addition & 0 deletions crates/telemetry/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod send_event;
pub mod send_null;
6 changes: 5 additions & 1 deletion crates/telemetry/src/send_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,15 @@ impl TelemetrySender for PostHogSender {
.and_then(|o| o.cloud_role.clone())
.unwrap_or_else(|| self.options.cloud_role.clone());

let posthog_event = posthog_rs::Event::new(
let mut posthog_event = posthog_rs::Event::new(
format!("codemod.{}.{}", cloud_role, event.kind),
distinct_id.clone(),
);

for (key, value) in event.properties {
posthog_event.insert_prop(key, value).unwrap();
}

if let Err(e) = self.client.capture(posthog_event).await {
eprintln!("Failed to send PostHog event: {e}");
}
Expand Down
15 changes: 15 additions & 0 deletions crates/telemetry/src/send_null.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
use crate::send_event::{BaseEvent, PartialTelemetrySenderOptions, TelemetrySender};
use async_trait::async_trait;

pub struct NullSender;

#[async_trait]
impl TelemetrySender for NullSender {
async fn send_event(
&self,
_event: BaseEvent,
_options_override: Option<PartialTelemetrySenderOptions>,
) {
// Do nothing
}
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy