Skip to content

refactor #183

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jan 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ repos:
hooks:
- id: setup-cfg-fmt

- repo: https://github.com/asottile/reorder-python-imports
rev: v3.13.0
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- args:
- --py38-plus
id: reorder-python-imports
- id: isort
name: isort (python)

- hooks:
- args:
- --py38-plus
Expand Down
3 changes: 3 additions & 0 deletions changelog.d/20250118_083011_15r10nk-git_refactor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- fixed some issues with dataclass arguments
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ dependencies = [
installer="uv"

[tool.hatch.envs.cov.scripts]
gh=[
github=[
"- rm htmlcov/*",
"gh run download -n html-report -D htmlcov",
"xdg-open htmlcov/index.html",
Expand Down Expand Up @@ -220,3 +220,7 @@ version = "command: cz bump --get-next"

[tool.pytest.ini_options]
markers=["no_rewriting: marks tests which need no code rewriting and can be used with pypy"]

[tool.isort]
profile="black"
force_single_line=true
2 changes: 1 addition & 1 deletion src/inline_snapshot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from ._code_repr import customize_repr
from ._code_repr import HasRepr
from ._code_repr import customize_repr
from ._external import external
from ._external import outsource
from ._inline_snapshot import snapshot
Expand Down
2 changes: 1 addition & 1 deletion src/inline_snapshot/_adapter/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def get_adapter(self, old_value, new_value) -> Adapter:
assert False

def assign(self, old_value, old_node, new_value):
raise NotImplementedError(cls)
raise NotImplementedError(self)

def value_assign(self, old_value, old_node, new_value):
from .value_adapter import ValueAdapter
Expand Down
4 changes: 2 additions & 2 deletions src/inline_snapshot/_adapter/dict_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
from .._change import DictInsert
from ..syntax_warnings import InlineSnapshotSyntaxWarning
from .adapter import Adapter
from .adapter import adapter_map
from .adapter import Item
from .adapter import adapter_map


class DictAdapter(Adapter):
Expand Down Expand Up @@ -86,7 +86,7 @@ def assign(self, old_value, old_node, new_value):
old_value.keys(),
(old_node.values if old_node is not None else [None] * len(old_value)),
):
if not key in new_value:
if key not in new_value:
# delete entries
yield Delete("fix", self.context.file._source, node, old_value[key])

Expand Down
26 changes: 18 additions & 8 deletions src/inline_snapshot/_adapter/generic_call_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
import warnings
from abc import ABC
from collections import defaultdict
from dataclasses import MISSING
from dataclasses import fields
from dataclasses import is_dataclass
from dataclasses import MISSING
from typing import Any

from .._change import CallArg
from .._change import Delete
from ..syntax_warnings import InlineSnapshotSyntaxWarning
from .adapter import Adapter
from .adapter import adapter_map
from .adapter import Item
from .adapter import adapter_map


def get_adapter_for_type(typ):
Expand Down Expand Up @@ -83,10 +83,17 @@ def items(cls, value, node):
assert isinstance(node, ast.Call)
assert all(kw.arg for kw in node.keywords)
kw_arg_node = {kw.arg: kw.value for kw in node.keywords if kw.arg}.get
pos_arg_node = lambda pos: node.args[pos]

def pos_arg_node(pos):
return node.args[pos]

else:
kw_arg_node = lambda _: None
pos_arg_node = lambda _: None

def kw_arg_node(_):
return None

def pos_arg_node(_):
return None

return [
Item(value=arg.value, node=pos_arg_node(i))
Expand Down Expand Up @@ -166,7 +173,7 @@ def assign(self, old_value, old_node, new_value):
# keyword arguments
result_kwargs = {}
for kw in old_node.keywords:
if (missing := not kw.arg in new_kwargs) or new_kwargs[kw.arg].is_default:
if (missing := kw.arg not in new_kwargs) or new_kwargs[kw.arg].is_default:
# delete entries
yield Delete(
"fix" if missing else "update",
Expand Down Expand Up @@ -258,8 +265,11 @@ def arguments(cls, value):
return ([], kwargs)

def argument(self, value, pos_or_name):
assert isinstance(pos_or_name, str)
return getattr(value, pos_or_name)
if isinstance(pos_or_name, str):
return getattr(value, pos_or_name)
else:
args = [field for field in fields(value) if field.init]
return args[pos_or_name]


try:
Expand Down
2 changes: 1 addition & 1 deletion src/inline_snapshot/_adapter/sequence_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
from .._compare_context import compare_context
from ..syntax_warnings import InlineSnapshotSyntaxWarning
from .adapter import Adapter
from .adapter import adapter_map
from .adapter import Item
from .adapter import adapter_map


class SequenceAdapter(Adapter):
Expand Down
3 changes: 2 additions & 1 deletion src/inline_snapshot/_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@
from collections import defaultdict
from dataclasses import dataclass
from typing import Any
from typing import cast
from typing import DefaultDict
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
from typing import cast

from asttokens.util import Token
from executing.executing import EnhancedAST

from inline_snapshot._source_file import SourceFile

from ._rewrite_code import ChangeRecorder
Expand Down
1 change: 0 additions & 1 deletion src/inline_snapshot/_code_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from functools import singledispatch
from unittest import mock


real_repr = repr


Expand Down
1 change: 0 additions & 1 deletion src/inline_snapshot/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from typing import List
from typing import Optional


if sys.version_info >= (3, 11):
from tomllib import loads
else:
Expand Down
4 changes: 2 additions & 2 deletions src/inline_snapshot/_find_external.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from executing import Source

from . import _external
from . import _inline_snapshot
from ._global_state import state
from ._rewrite_code import ChangeRecorder
from ._rewrite_code import end_of
from ._rewrite_code import start_of
Expand Down Expand Up @@ -47,7 +47,7 @@ def used_externals_in(source) -> Set[str]:

def used_externals() -> Set[str]:
result = set()
for filename in _inline_snapshot._files_with_snapshots:
for filename in state().files_with_snapshots:
result |= used_externals_in(pathlib.Path(filename).read_text("utf-8"))

return result
Expand Down
24 changes: 24 additions & 0 deletions src/inline_snapshot/_flags.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from typing import Set

from ._types import Category


class Flags:
"""
fix: the value needs to be changed to pass the tests
update: the value should be updated because the token-stream has changed
create: the snapshot is empty `snapshot()`
trim: the snapshot contains more values than neccessary. 1 could be trimmed in `5 in snapshot([1,5])`.
"""

def __init__(self, flags: Set[Category] = set()):
self.fix = "fix" in flags
self.update = "update" in flags
self.create = "create" in flags
self.trim = "trim" in flags

def to_set(self):
return {k for k, v in self.__dict__.items() if v}

def __repr__(self):
return f"Flags({self.to_set()})"
45 changes: 45 additions & 0 deletions src/inline_snapshot/_global_state.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from __future__ import annotations

import contextlib
from dataclasses import dataclass
from dataclasses import field
from typing import Generator

from ._flags import Flags


@dataclass
class State:
# snapshot
missing_values: int = 0
incorrect_values: int = 0

snapshots: dict = field(default_factory=dict)
update_flags: Flags = field(default_factory=Flags)
active: bool = True
files_with_snapshots: set[str] = field(default_factory=set)

# external
storage = None


_current = State()
_current.active = False


def state() -> State:
global _current
return _current


@contextlib.contextmanager
def snapshot_env() -> Generator[State]:

global _current
old = _current
_current = State()

try:
yield _current
finally:
_current = old
Loading
Loading