Skip to content

Commit

Permalink
Merge pull request #21 from n-takumasa/_warn_unused
Browse files Browse the repository at this point in the history
mnt: fix #20
  • Loading branch information
n-takumasa authored Mar 28, 2024
2 parents 82bbc07 + c92d214 commit 945cbe5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
19 changes: 8 additions & 11 deletions jsonc/_add_comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import copy
import io
import json
import os
import sys
import warnings
from tokenize import COMMENT, NL, STRING, TokenInfo, generate_tokens, untokenize
Expand All @@ -12,6 +13,8 @@
CommentsDict = dict[str, "Comments"] | dict[int, "Comments"]
Comments = str | CommentsDict | tuple[str, CommentsDict]

_warn_skips = (os.path.dirname(__file__),) # noqa: PTH120


def _make_comment(text: str, indent=0) -> str:
return "\n".join(
Expand Down Expand Up @@ -46,17 +49,11 @@ def _warn_unused(
if full_key:
full_key += "."
for k in comments:
f = sys._getframe() # noqa: SLF001
filename = f.f_code.co_filename
stacklevel = 2
while f := f.f_back:
if f.f_code.co_filename != filename:
break
stacklevel += 1
warnings.warn(
"Unused comment with key: " + full_key + str(k),
stacklevel=4,
)
msg = f"Unused comment with key: {full_key}{k}"
if sys.version_info >= (3, 12):
warnings.warn(msg, stacklevel=2, skip_file_prefixes=_warn_skips)
else:
warnings.warn(msg, stacklevel=4)


def _add_comments(data: str, comments: Comments) -> str: # noqa: C901
Expand Down
11 changes: 11 additions & 0 deletions tests/test_warn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from pathlib import Path

import pytest

import jsonc


def test_unused():
with pytest.warns(UserWarning, match="Unused comment with key: warn") as w:
jsonc.dumps({}, indent=2, comments={"warn": "spam"})
assert Path(w.list[0].filename).absolute() == Path(__file__).absolute()

0 comments on commit 945cbe5

Please sign in to comment.