• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

andreoliwa / nitpick / 9594924093

20 Jun 2024 09:21AM CUT coverage: 96.746%. Remained the same
9594924093

push

github

andreoliwa
build(deps): bump urllib3 from 2.0.7 to 2.2.2

Bumps [urllib3](https://github.com/urllib3/urllib3) from 2.0.7 to 2.2.2.
- [Release notes](https://github.com/urllib3/urllib3/releases)
- [Changelog](https://github.com/urllib3/urllib3/blob/main/CHANGES.rst)
- [Commits](https://github.com/urllib3/urllib3/compare/2.0.7...2.2.2)

---
updated-dependencies:
- dependency-name: urllib3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

788 of 827 branches covered (95.28%)

Branch coverage included in aggregate %.

2096 of 2154 relevant lines covered (97.31%)

4.86 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.43
/src/nitpick/plugins/json.py
1
"""JSON files."""
2

3
from __future__ import annotations
5✔
4

5
import json
5✔
6
from itertools import chain
5✔
7
from typing import TYPE_CHECKING, ClassVar, Iterator
5✔
8

9
from loguru import logger
5✔
10

11
from nitpick import fields
5✔
12
from nitpick.blender import BaseDoc, Comparison, JsonDoc, flatten_quotes, unflatten_quotes
5✔
13
from nitpick.plugins import hookimpl
5✔
14
from nitpick.plugins.base import NitpickPlugin
5✔
15
from nitpick.schemas import BaseNitpickSchema
5✔
16
from nitpick.violations import Fuss, SharedViolations, ViolationEnum
5✔
17

18
if TYPE_CHECKING:
19
    from nitpick.plugins.info import FileInfo
20
    from nitpick.typedefs import JsonDict
21

22
KEY_CONTAINS_KEYS = "contains_keys"
5✔
23
KEY_CONTAINS_JSON = "contains_json"
5✔
24
VALUE_PLACEHOLDER = "<some value here>"
5✔
25

26

27
class JsonFileSchema(BaseNitpickSchema):
5✔
28
    """Validation schema for any JSON file added to the style."""
29

30
    contains_keys = fields.List(fields.NonEmptyString)
5✔
31
    contains_json = fields.Dict(fields.NonEmptyString, fields.JsonString)
5✔
32

33

34
class JsonPlugin(NitpickPlugin):
5✔
35
    """Enforce configurations and autofix JSON files.
36

37
    Add the configurations for the file name you wish to check.
38
    Style example: :gitref:`the default config for package.json <src/nitpick/resources/javascript/package-json.toml>`.
39
    """
40

41
    validation_schema = JsonFileSchema
5✔
42
    identify_tags: ClassVar = {"json"}
5✔
43
    violation_base_code = 340
5✔
44
    fixable = True
5✔
45

46
    def enforce_rules(self) -> Iterator[Fuss]:
5✔
47
        """Enforce rules for missing keys and JSON content."""
48
        json_doc = JsonDoc(path=self.file_path)
5✔
49
        blender: JsonDict = json_doc.as_object.copy() if self.autofix else {}
5✔
50

51
        comparison = Comparison(json_doc, self.expected_dict_from_contains_keys(), self.special_config)()
5✔
52
        if comparison.missing:
5✔
53
            yield from self.report(SharedViolations.MISSING_VALUES, blender, comparison.missing)
5✔
54

55
        comparison = Comparison(json_doc, self.expected_dict_from_contains_json(), self.special_config)()
5✔
56
        if comparison.has_changes:
5✔
57
            yield from chain(
5✔
58
                self.report(SharedViolations.DIFFERENT_VALUES, blender, comparison.diff),
59
                self.report(SharedViolations.MISSING_VALUES, blender, comparison.missing),
60
            )
61

62
        if self.autofix and self.dirty and blender:
5✔
63
            self.file_path.write_text(JsonDoc(obj=unflatten_quotes(blender)).reformatted)
5✔
64

65
    def expected_dict_from_contains_keys(self):
5✔
66
        """Expected dict created from "contains_keys" values."""
67
        return unflatten_quotes(
5✔
68
            {key: VALUE_PLACEHOLDER for key in set(self.expected_config.get(KEY_CONTAINS_KEYS) or [])}
69
        )
70

71
    def expected_dict_from_contains_json(self):
5✔
72
        """Expected dict created from "contains_json" values."""
73
        expected_config = {}
5✔
74
        # TODO: feat: accept key as a jmespath expression, value is valid JSON
75
        for key, json_string in (self.expected_config.get(KEY_CONTAINS_JSON) or {}).items():
5✔
76
            try:
5✔
77
                expected_config[key] = json.loads(json_string)
5✔
78
            except json.JSONDecodeError as err:  # noqa: PERF203
×
79
                # This should not happen, because the style was already validated before.
80
                # Maybe the NIP??? code was disabled by the user?
81
                logger.error(f"{err} on {KEY_CONTAINS_JSON} while checking {self.file_path}")
×
82
                continue
×
83
        return expected_config
5✔
84

85
    def report(self, violation: ViolationEnum, blender: JsonDict, change: BaseDoc | None):
5✔
86
        """Report a violation while optionally modifying the JSON dict."""
87
        if not change:
5✔
88
            return
5✔
89
        if blender:
5✔
90
            blender.update(flatten_quotes(change.as_object))
5✔
91
            self.dirty = True
5✔
92
        yield self.reporter.make_fuss(violation, change.reformatted, prefix="", fixed=self.autofix)
5✔
93

94
    @property
5✔
95
    def initial_contents(self) -> str:
5✔
96
        """Suggest the initial content for this missing file."""
97
        suggestion = flatten_quotes(self.expected_dict_from_contains_keys())
5✔
98
        suggestion.update(flatten_quotes(self.expected_dict_from_contains_json()))
5✔
99
        return self.write_initial_contents(JsonDoc, unflatten_quotes(suggestion))
5✔
100

101

102
@hookimpl
5✔
103
def plugin_class() -> type[NitpickPlugin]:
5✔
104
    """Handle JSON files."""
105
    return JsonPlugin
5✔
106

107

108
@hookimpl
5✔
109
def can_handle(info: FileInfo) -> type[NitpickPlugin] | None:
5✔
110
    """Handle JSON files."""
111
    if JsonPlugin.identify_tags & info.tags:
5✔
112
        return JsonPlugin
5✔
113
    return None
5✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc