Skip to content

Commit 08d9861

Browse files
Align with commit to master
1 parent 553dc20 commit 08d9861

3 files changed

Lines changed: 195 additions & 248 deletions

File tree

‎sentry_sdk/_agent_hint.py‎

Lines changed: 118 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,24 @@
11
import atexit
22
import os
3+
import subprocess
34
import sys
45
import time
56
from typing import TYPE_CHECKING
67

78
from sentry_sdk.utils import (
8-
_git,
99
_is_external_source,
1010
capture_internal_exceptions,
1111
env_to_bool,
1212
)
1313

1414
if 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

2020
SETUP_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.
2322
CODING_AGENT_ENV_VARS = (
2423
"CLAUDECODE",
2524
"CODEX_THREAD_ID",
@@ -28,7 +27,6 @@
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.
3331
SETUP_IN_PROGRESS_SECONDS = 60 * 60
3432
SETUP_IN_PROGRESS_SECONDS_WITHOUT_GIT = 10 * 60
@@ -38,7 +36,7 @@
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

4442
def _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-
8055
def _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

118145
def _logs_on(client: "BaseClient") -> bool:
@@ -133,7 +160,7 @@ def register_coding_agent_hint_exit_hook() -> None:
133160
def _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

163223
def 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))

‎sentry_sdk/utils.py‎

Lines changed: 14 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,7 @@ def json_dumps(data: "Any") -> bytes:
128128
return json.dumps(data, allow_nan=False, separators=(",", ":")).encode("utf-8")
129129

130130

131-
def _git(
132-
*args: str, cwd: "Optional[str]" = None, timeout: "Optional[float]" = None
133-
) -> "Optional[str]":
131+
def get_git_revision() -> "Optional[str]":
134132
try:
135133
with open(os.path.devnull, "w+") as null:
136134
# prevent command prompt windows from popping up on windows
@@ -139,31 +137,22 @@ def _git(
139137
startupinfo = subprocess.STARTUPINFO()
140138
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
141139

142-
with subprocess.Popen(
143-
["git", *args],
144-
cwd=cwd,
145-
startupinfo=startupinfo,
146-
stdout=subprocess.PIPE,
147-
stderr=null,
148-
stdin=null,
149-
) as process:
150-
try:
151-
output = (
152-
process.communicate(timeout=timeout)[0].strip().decode("utf-8")
153-
)
154-
except subprocess.TimeoutExpired:
155-
# Don't read the rest of the output: a child process of git can
156-
# keep the pipe open after git is killed.
157-
process.kill()
158-
return None
140+
revision = (
141+
subprocess.Popen(
142+
["git", "rev-parse", "HEAD"],
143+
startupinfo=startupinfo,
144+
stdout=subprocess.PIPE,
145+
stderr=null,
146+
stdin=null,
147+
)
148+
.communicate()[0]
149+
.strip()
150+
.decode("utf-8")
151+
)
159152
except (OSError, IOError, FileNotFoundError):
160153
return None
161154

162-
return output
163-
164-
165-
def get_git_revision() -> "Optional[str]":
166-
return _git("rev-parse", "HEAD")
155+
return revision
167156

168157

169158
def get_default_release() -> "Optional[str]":

0 commit comments

Comments
 (0)