<commit_before>"""Various miscellaneous functions to make code easier to read & write."""

import collections.abc
import inspect
import logging
import functools
import urllib.parse

import jsonschema
import jsonpointer


_logger = logging.getLogger("holocron")


def resolve_json_references(value, context, keep_unknown=True):
    def _do_resolve(node):
        if isinstance(node, collections.abc.Mapping) and "$ref" in node:
            uri, fragment = urllib.parse.urldefrag(node["$ref"])
            try:
                return jsonpointer.resolve_pointer(context[uri], fragment)
            except KeyError:
                if keep_unknown:
                    return node
                raise
        elif isinstance(node, collections.abc.Mapping):
            for k, v in node.items():
                node[k] = _do_resolve(v)
        elif isinstance(node, collections.abc.Sequence) and not isinstance(
            node, str
        ):
            if not isinstance(node, collections.abc.MutableSequence):
                node = list(node)
<commit_msg>Do not mutate original node in JSON ref resolver<commit_after>"""Various miscellaneous functions to make code easier to read & write."""

import copy
import collections.abc
import inspect
import logging
import functools
import urllib.parse

import jsonschema
import jsonpointer


_logger = logging.getLogger("holocron")


def resolve_json_references(value, context, keep_unknown=True):
    def _do_resolve(node):
        node = copy.copy(node)

        if isinstance(node, collections.abc.Mapping) and "$ref" in node:
            uri, fragment = urllib.parse.urldefrag(node["$ref"])
            try:
                return jsonpointer.resolve_pointer(context[uri], fragment)
            except KeyError:
                if keep_unknown:
                    return node
                raise
        elif isinstance(node, collections.abc.Mapping):
            for k, v in node.items():
                node[k] = _do_resolve(v)
        elif isinstance(node, collections.abc.Sequence) and not isinstance(
            node, str
        ):
            if not isinstance(node, collections.abc.MutableSequence):
                node = list(node)

{'fraction_non_alphanumeric': 0.08458390177353342, 'fraction_numerical': 0.0, 'mean_word_length': 2.3846153846153846, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4605818', 'n_tokens_mistral': 585, 'n_tokens_neox': 563, 'n_words': 166}