posthog_cli/utils/
posthog.rs

1// Random utils for sending metrics to PostHog
2
3use std::thread::JoinHandle;
4
5use posthog_rs::Event;
6use tracing::{debug, warn};
7
8pub fn init_posthog() {
9    // This is pulled at compile time, not runtime - we set it at build.
10    let Some(token) = option_env!("POSTHOG_API_TOKEN") else {
11        warn!("Posthog api token not set at build time - is this a debug build?");
12        return;
13    };
14
15    let ph_config = posthog_rs::ClientOptionsBuilder::default()
16        .api_key(token.to_string())
17        .request_timeout_seconds(5) // It's a CLI, 5 seconds is an eternity
18        .build()
19        .expect("Building PH config succeeds");
20
21    posthog_rs::init_global(ph_config).expect("Initializing PostHog client");
22}
23
24pub fn capture_command_invoked(
25    command: impl AsRef<str>,
26    env_id: Option<impl AsRef<str>>,
27) -> JoinHandle<()> {
28    let event_name = "posthog cli command run".to_string();
29    let mut event = Event::new_anon(event_name);
30
31    event
32        .insert_prop("command_name", command.as_ref())
33        .expect("Inserting command prop succeeds");
34
35    if let Some(env_id) = env_id {
36        event
37            .insert_prop("env_id", env_id.as_ref())
38            .expect("Inserting env_id prop succeeds");
39    }
40
41    spawn_capture(event)
42}
43
44fn spawn_capture(event: Event) -> JoinHandle<()> {
45    std::thread::spawn(move || {
46        debug!("Capturing event");
47        let res = posthog_rs::capture(event); // Purposefully ignore errors here
48        if let Err(err) = res {
49            debug!("Failed to capture event: {:?}", err);
50        } else {
51            debug!("Event captured successfully");
52        }
53    })
54}