11import atexit
22import os
3+ import subprocess
34import sys
45import time
56from typing import TYPE_CHECKING
67
78from sentry_sdk .utils import (
8- _git ,
99 _is_external_source ,
1010 capture_internal_exceptions ,
1111 env_to_bool ,
1212)
1313
1414if TYPE_CHECKING :
1515 from types import FrameType
16- from typing import List , Optional , Tuple
16+ from typing import List , Tuple
1717
1818 from sentry_sdk .client import BaseClient
1919
2020SETUP_CHECKLIST_PATH = os .path .join (os .path .dirname (__file__ ), "SETUP_CHECKLIST.md" )
2121
22- # Set by coding agents in the commands they run, for the agents that don't set AI_AGENT.
2322CODING_AGENT_ENV_VARS = (
2423 "CLAUDECODE" ,
2524 "CODEX_THREAD_ID" ,
2827 "GEMINI_CLI" ,
2928)
3029
31- # How long after a change to the file that calls init() the setup counts as in progress.
3230# Without git we can't tell whose change it is, so the window is shorter.
3331SETUP_IN_PROGRESS_SECONDS = 60 * 60
3432SETUP_IN_PROGRESS_SECONDS_WITHOUT_GIT = 10 * 60
3836_exit_hook_registered = False
3937# What _write_coding_agent_hint can print at exit: one entry for each file that called
4038# init() with tracing or logs off.
41- _hints_at_exit : "List[Tuple[str, str, str, str, str ]]" = []
39+ _hints_at_exit : "List[Tuple[str, bool, bool ]]" = []
4240
4341
4442def _running_under_coding_agent () -> bool :
@@ -54,31 +52,7 @@ def _running_under_coding_agent() -> bool:
5452 return any (os .environ .get (name ) for name in CODING_AGENT_ENV_VARS )
5553
5654
57- _MISSING_PRODUCTS = {
58- (False , False ): (
59- "Sentry will get errors from this app but not the request trace around them, "
60- "and its logs only as breadcrumbs." ,
61- "Tracing and logs are off, so Sentry only gets errors." ,
62- "they're" ,
63- "them" ,
64- ),
65- (False , True ): (
66- "Sentry will get errors from this app but not the request trace around them." ,
67- "Tracing is off, so Sentry gets errors and logs but no traces." ,
68- "it's" ,
69- "it" ,
70- ),
71- (True , False ): (
72- "Sentry will get errors from this app but its logs only as breadcrumbs." ,
73- "Logs are off, so Sentry gets errors and traces but no logs." ,
74- "they're" ,
75- "them" ,
76- ),
77- }
78-
79-
8055def _setup_in_progress (init_file : str ) -> bool :
81- """Whether this user changed the file that calls init() a short time ago."""
8256 now = time .time ()
8357 cutoff = now - SETUP_IN_PROGRESS_SECONDS
8458 try :
@@ -88,31 +62,84 @@ def _setup_in_progress(init_file: str) -> bool:
8862 if changed < cutoff :
8963 return False
9064
91- def git (* args : str ) -> "Optional[str]" :
92- # Read only: don't take the index lock (the user or an agent may be running
93- # git at the same time) and don't run a configured fsmonitor command.
94- return _git (
95- "--no-optional-locks" ,
96- "-c" ,
97- "core.fsmonitor=false" ,
98- * args ,
99- cwd = os .path .dirname (init_file ),
100- timeout = GIT_TIMEOUT_SECONDS ,
101- )
65+ cwd = os .path .dirname (init_file )
10266
10367 # --branch adds a header line, so an empty answer means git has no answer.
104- status = git ("status" , "--porcelain" , "--branch" , "--" , init_file )
68+ try :
69+ status = subprocess .run (
70+ [
71+ "git" ,
72+ "--no-optional-locks" ,
73+ "-c" ,
74+ "core.fsmonitor=false" ,
75+ "status" ,
76+ "--porcelain" ,
77+ "--branch" ,
78+ "--" ,
79+ init_file ,
80+ ],
81+ cwd = cwd ,
82+ stdin = subprocess .DEVNULL ,
83+ stdout = subprocess .PIPE ,
84+ stderr = subprocess .DEVNULL ,
85+ encoding = "utf-8" ,
86+ timeout = GIT_TIMEOUT_SECONDS ,
87+ ).stdout .strip ()
88+ except (OSError , subprocess .TimeoutExpired ):
89+ status = ""
10590 if not status :
10691 return changed >= now - SETUP_IN_PROGRESS_SECONDS_WITHOUT_GIT
10792 if "\n " in status :
10893 return True
10994
11095 # A checkout also gives a clean file a new mtime, so only count a commit
11196 # that was made here.
112- committer = git (
113- "log" , "-1" , f"--since={ int (cutoff )} " , "--format=%ce" , "--" , init_file
114- )
115- return bool (committer ) and committer == git ("config" , "user.email" )
97+ try :
98+ committer = subprocess .run (
99+ [
100+ "git" ,
101+ "--no-optional-locks" ,
102+ "-c" ,
103+ "core.fsmonitor=false" ,
104+ "log" ,
105+ "-1" ,
106+ f"--since={ int (cutoff )} " ,
107+ "--format=%ce" ,
108+ "--" ,
109+ init_file ,
110+ ],
111+ cwd = cwd ,
112+ stdin = subprocess .DEVNULL ,
113+ stdout = subprocess .PIPE ,
114+ stderr = subprocess .DEVNULL ,
115+ encoding = "utf-8" ,
116+ timeout = GIT_TIMEOUT_SECONDS ,
117+ ).stdout .strip ()
118+ except (OSError , subprocess .TimeoutExpired ):
119+ return False
120+ if not committer :
121+ return False
122+
123+ try :
124+ user_email = subprocess .run (
125+ [
126+ "git" ,
127+ "--no-optional-locks" ,
128+ "-c" ,
129+ "core.fsmonitor=false" ,
130+ "config" ,
131+ "user.email" ,
132+ ],
133+ cwd = cwd ,
134+ stdin = subprocess .DEVNULL ,
135+ stdout = subprocess .PIPE ,
136+ stderr = subprocess .DEVNULL ,
137+ encoding = "utf-8" ,
138+ timeout = GIT_TIMEOUT_SECONDS ,
139+ ).stdout .strip ()
140+ except (OSError , subprocess .TimeoutExpired ):
141+ return False
142+ return committer == user_email
116143
117144
118145def _logs_on (client : "BaseClient" ) -> bool :
@@ -133,7 +160,7 @@ def register_coding_agent_hint_exit_hook() -> None:
133160def _write_coding_agent_hint () -> None :
134161 with capture_internal_exceptions ():
135162 # One hint, for the first init() from a file that this user changed.
136- for init_file , not_shown , off , its , it in _hints_at_exit :
163+ for init_file , tracing_on , logs_on in _hints_at_exit :
137164 if _setup_in_progress (init_file ):
138165 break
139166 else :
@@ -142,45 +169,75 @@ def _write_coding_agent_hint() -> None:
142169 codex = "codex" in (os .environ .get ("AI_AGENT" ) or "" ).lower () or any (
143170 os .environ .get (name ) for name in ("CODEX_THREAD_ID" , "CODEX_SANDBOX" )
144171 )
145- if codex :
172+ if codex and tracing_on :
173+ hint = (
174+ "Logs are off, so Sentry gets errors and traces but no logs. If you "
175+ "leave them off, tell the user they're off and that you can turn them "
176+ "on if they want. Sentry's official setup checklist, included in the "
177+ f"sentry-sdk package you installed: { SETUP_CHECKLIST_PATH } "
178+ )
179+ elif codex and logs_on :
180+ hint = (
181+ "Tracing is off, so Sentry gets errors and logs but no traces. If you "
182+ "leave it off, tell the user it's off and that you can turn it on if "
183+ "they want. Sentry's official setup checklist, included in the "
184+ f"sentry-sdk package you installed: { SETUP_CHECKLIST_PATH } "
185+ )
186+ elif codex :
187+ hint = (
188+ "Tracing and logs are off, so Sentry only gets errors. If you leave "
189+ "them off, tell the user they're off and that you can turn them on if "
190+ "they want. Sentry's official setup checklist, included in the "
191+ f"sentry-sdk package you installed: { SETUP_CHECKLIST_PATH } "
192+ )
193+ elif tracing_on :
194+ hint = (
195+ "Sentry will get errors from this app but its logs only as "
196+ "breadcrumbs. The checklist shows what to change. If you're setting "
197+ "up Sentry, it is strongly recommended to check your setup against "
198+ "Sentry's official setup checklist, included in the sentry-sdk "
199+ f"package you installed: { SETUP_CHECKLIST_PATH } "
200+ )
201+ elif logs_on :
146202 hint = (
147- f"{ off } If you leave { it } off, tell the user { its } off and that you can "
148- f"turn { it } on if they want. Sentry's official setup checklist, included "
149- f"in the sentry-sdk package you installed: { SETUP_CHECKLIST_PATH } "
203+ "Sentry will get errors from this app but not the request trace "
204+ "around them. The checklist shows what to change. If you're setting "
205+ "up Sentry, it is strongly recommended to check your setup against "
206+ "Sentry's official setup checklist, included in the sentry-sdk "
207+ f"package you installed: { SETUP_CHECKLIST_PATH } "
150208 )
151209 else :
152210 hint = (
153- f"{ not_shown } The checklist shows what to change. If you're setting up "
154- "Sentry, it is strongly recommended to check your setup against Sentry's "
155- "official setup checklist, included in the sentry-sdk package you "
156- f"installed: { SETUP_CHECKLIST_PATH } "
211+ "Sentry will get errors from this app but not the request trace "
212+ "around them, and its logs only as breadcrumbs. The checklist shows "
213+ "what to change. If you're setting up Sentry, it is strongly "
214+ "recommended to check your setup against Sentry's official setup "
215+ "checklist, included in the sentry-sdk package you installed: "
216+ f"{ SETUP_CHECKLIST_PATH } "
157217 )
158218 sys .stdout .flush ()
159219 sys .stderr .write (f"[sentry] { hint } (hide with SENTRY_AGENT_HINTS=0)\n " )
160220 sys .stderr .flush ()
161221
162222
163223def show_coding_agent_hint (client : "BaseClient" , caller : "FrameType" ) -> None :
164- """Point a coding agent at the setup checklist while Sentry is being set up."""
165224 options = client .options
166225 rate = options ["traces_sample_rate" ]
167226 tracing_on = options ["traces_sampler" ] is not None or rate not in (0 , None )
168227 logs_on = _logs_on (client )
169228 if (
170229 not _exit_hook_registered
171- # Only tested on macOS and Linux.
230+ or sys . version_info < ( 3 , 9 )
172231 or sys .platform not in ("darwin" , "linux" )
173232 or not options ["dsn" ]
174233 or options ["_experiments" ].get ("agent_setup_complete" )
175234 or (tracing_on and logs_on )
176235 ):
177236 return
178237
179- # A script's own path is relative on Python 3.8 and older.
180- init_file = os .path .abspath (caller .f_code .co_filename )
181- # An installed tool that uses Sentry itself isn't the user's app.
238+ init_file = caller .f_code .co_filename
182239 if _is_external_source (init_file ):
183240 return
184- # Agents often cut a command's output with `| tail`, so the hint goes last, at exit .
241+ # Agents often cut a command's output with `| tail`, so the hint goes last.
185242 if all (init_file != seen [0 ] for seen in _hints_at_exit ):
186- _hints_at_exit .append ((init_file , * _MISSING_PRODUCTS [( tracing_on , logs_on )] ))
243+ _hints_at_exit .append ((init_file , tracing_on , logs_on ))
0 commit comments