:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ci): reduce false comment density warnings (#96192)
Paul D'Ambrae6b9a9dd320d
diff --git a/.github/scripts/check-comment-density.sh b/.github/scripts/check-comment-density.shindex a3d1ebb46c80..2f4198927f63 100644--- a/.github/scripts/check-comment-density.sh+++ b/.github/scripts/check-comment-density.sh@@ -8,7 +8,7 @@ script="$(dirname "$0")/check_comment_density.py"command -v python3 > /dev/null 2>&1 || exit 0# With GITHUB_OUTPUT unset the classifier prints `status=<ok|warn|alert> <summary>`.-report=$(git diff --cached -U0 --no-color | GITHUB_OUTPUT='' python3 "$script" 2> /dev/null) || exit 0+report=$(git diff --cached -U3 --no-color | GITHUB_OUTPUT='' python3 "$script" 2> /dev/null) || exit 0status=$(printf '%s\n' "$report" | head -n1 | sed -n 's/^status=\([a-z]*\) .*/\1/p')[ "$status" = "warn" ] || [ "$status" = "alert" ] || exit 0diff --git a/.github/scripts/check_comment_density.py b/.github/scripts/check_comment_density.pyindex 92e01661782f..b6cb0c51702b 100644--- a/.github/scripts/check_comment_density.py+++ b/.github/scripts/check_comment_density.py@@ -21,6 +21,7 @@ import sysimport uuidimport unicodedatafrom dataclasses import dataclass, field+from typing import Literal# Before agent-assisted PRs were common, the median PR had about 2% comment lines.WARN_RATIO = 0.03@@ -35,14 +36,15 @@ SQL_LANGS = {"sql"}CODE_LANGS = HASH_LANGS | SLASH_LANGS | SQL_LANGS# Workflow YAML and shell are left out because they need prose to be readable.-# `generated` anywhere in the path covers `/generated/`, `*.generated.ts`, and-# `generated_configs/`, which all carry a generator header over little code.+# Generated paths use standard lower-case separators or an `_generated_` filename.+# A narrow match keeps hand-written names that contain `Generated` in the measurement.EXCLUDED_PATHS = re.compile(- r"(^\.github/|generated|__snapshots__/|\.ambr$|\.snap$|\.lock$|migrations/\d|\.min\.js$|/dist/|/vendor/|/node_modules/|_pb2|\.d\.ts$)",- re.IGNORECASE,+ r"(^\.github/|(?:^|/)(?:generated[_./]|_generated_)|\.generated\.|__snapshots__/|\.ambr$|\.snap$|\.lock$|migrations/\d|\.min\.js$|/dist/|/vendor/|/node_modules/|_pb2|\.d\.ts$)")DIFF_SKIP_PREFIXES = ("+++", "---", "index ", "new file", "deleted file", "similarity", "rename ", "Binary")+ParserState = Literal["block_comment", "template_literal", "triple_string"] | None+@dataclass(frozen=False)class FileStats:@@ -73,61 +75,106 @@ def _extension(path: str) -> str:return name.rsplit(".", 1)[-1].lower() if "." in name else ""-def _classify_slash(line: str, in_block: bool) -> tuple[bool, bool]:- """Return (is_comment, in_block after this line) for a `//` and `/* */` language."""- if in_block:- return True, "*/" not in line- if line.startswith("//"):- return True, False- if line.startswith(("/*", "{/*")):+def _is_escaped(line: str, index: int) -> bool:+ backslashes = 0+ index -= 1+ while index >= 0 and line[index] == "\\":+ backslashes += 1+ index -= 1+ return backslashes % 2 == 1+++def _slash_state_after_line(line: str, state: ParserState) -> ParserState:+ index = 0+ quote = ""++ while index < len(line):+ if state == "block_comment":+ if line.startswith("*/", index):+ state = None+ index += 2+ continue+ index += 1+ continue++ if state == "template_literal":+ if line[index] == "`" and not _is_escaped(line, index):+ state = None+ index += 1+ continue++ if quote:+ if line[index] == quote and not _is_escaped(line, index):+ quote = ""+ index += 1+ continue++ if line.startswith("//", index):+ return None+ if line.startswith("/*", index):+ state = "block_comment"+ index += 2+ continue+ if line[index] in "'\"":+ quote = line[index]+ elif line[index] == "`":+ state = "template_literal"+ index += 1++ return state+++def _classify_slash(line: str, state: ParserState) -> tuple[bool, ParserState]:+ if state == "template_literal":+ return False, _slash_state_after_line(line, state)++ if state == "block_comment" or line.startswith(("/*", "{/*")):end = line.find("*/")- if end == -1:- return True, True- # `/* note */ doWork()` is code with a leading comment, not a comment line.- return line[end + 2 :].strip(" }") == "", False- return False, False+ is_comment = end == -1 or line[end + 2 :].strip(" }") == ""+ return is_comment, _slash_state_after_line(line, state)++ if line.startswith("//"):+ return True, None+ return False, _slash_state_after_line(line, state)-def _classify_hash(line: str, in_string: bool) -> tuple[bool, bool]:- """Return (is_comment, in_string after this line) for Python.- A `#` line inside a triple-quoted string (a prompt, a SQL template) is text,- not a comment.- """+def _classify_hash(line: str, state: ParserState) -> tuple[bool, ParserState]:toggles = (line.count('"""') + line.count("'''")) % 2 == 1- if in_string:- return False, not toggles- return line.startswith("#") and not line.startswith("#!"), toggles+ if state == "triple_string":+ return False, None if toggles else state+ is_comment = line.startswith("#") and not line.startswith("#!")+ return is_comment, "triple_string" if toggles else None-def _classify(lang: str, line: str, inside: bool) -> tuple[bool, bool]:+def _classify(lang: str, line: str, state: ParserState) -> tuple[bool, ParserState]:if lang in SLASH_LANGS:- return _classify_slash(line, inside)+ return _classify_slash(line, state)if lang in HASH_LANGS:- return _classify_hash(line, inside)+ return _classify_hash(line, state)if lang in SQL_LANGS:- return line.startswith("--"), False- return False, False+ return line.startswith("--"), None+ return False, Nonedef analyze(diff_text: str) -> Report:report = Report()lang = ""stats: FileStats | None = None- # True inside a block comment or a triple-quoted string that spans lines.- inside = False+ # The state tracks a block comment or a multi-line string across diff lines.+ state: ParserState = Nonefor raw in diff_text.splitlines():if raw.startswith("diff --git "):path = raw.split(" b/", 1)[-1]lang = _extension(path)stats = None- inside = False+ state = Noneif lang in CODE_LANGS and not EXCLUDED_PATHS.search(path):stats = report.files.setdefault(path, FileStats(path))continueif raw.startswith("@@"):- inside = False+ state = Nonecontinueif stats is None or raw.startswith(DIFF_SKIP_PREFIXES):continue@@ -140,7 +187,7 @@ def analyze(diff_text: str) -> Report:if not line:continue- is_comment, inside = _classify(lang, line, inside)+ is_comment, state = _classify(lang, line, state)if not added:continuediff --git a/.github/scripts/test_check_comment_density.py b/.github/scripts/test_check_comment_density.pyindex 21c4485e17f5..5367af462ecd 100644--- a/.github/scripts/test_check_comment_density.py+++ b/.github/scripts/test_check_comment_density.py@@ -51,7 +51,7 @@ def diff_for(path: str, body: str) -> str:"frontend/src/lib/thing.ts","""+/**- + * Block comment line+ + * Block comment with one ` marker+ */+const a = 1 // trailing+// full line@@ -59,11 +59,19 @@ def diff_for(path: str, body: str) -> str:+const b = 2+/* note */ doWork()+*ptr = 1+ +const snippet = `+ +// rendered SDK line+ +const escaped = \\`code\\`+ +/* rendered block */+ +`+ +const label = "Use one ` marker"+ +// real comment with one ` marker+ +// another real comment""",),- 9,- 5,- id="typescript-block-and-line-comments",+ 17,+ 7,+ id="typescript-block-line-and-template-comments",),pytest.param(diff_for(@@ -85,13 +93,22 @@ def diff_for(path: str, body: str) -> str:diff_for("frontend/src/generated/api.ts", "+// generated\n+// generated\n")+ diff_for("frontend/src/lib/agentScopes.generated.ts", "+// AUTO-GENERATED\n+// Do not edit\n")+ diff_for("products/x/backend/generated_configs/ably.py", "+# generated\n+# do not edit\n")+ + diff_for("posthog/hogql/test/_generated_grammar_strategies.py", "+# generated\n+# do not edit\n")+ diff_for(".github/workflows/ci.yml", "+# yaml prose\n+run: echo\n")+ diff_for("posthog/test/__snapshots__/x.ambr", "+# name: test\n")+ diff_for("docs/readme.md", "+<!-- not code -->\n")- + diff_for("posthog/hogql/q.sql", "+-- sql comment\n+SELECT 1\n"),- 2,- 1,- id="excluded-paths-and-non-code-files-are-ignored",+ + diff_for("posthog/hogql/q.sql", "+-- sql comment\n+SELECT 1\n")+ + diff_for(+ "products/notebooks/frontend/NotebookNodeGeneratedWidget/index.ts",+ "+// hand-written component\n+export const widget = 1\n",+ )+ + diff_for(+ "services/mcp/tests/unit/schema-generated.test.ts",+ "+// hand-written test\n+const schema = 1\n",+ ),+ 6,+ 3,+ id="only-generated-paths-and-non-code-files-are-ignored",),],)