<commit_before>import argparse
import json
import logging

import colorama

from dvc.command.base import CmdBase, append_doc_link
from dvc.exceptions import DvcException


logger = logging.getLogger(__name__)


class CmdDiff(CmdBase):
    @staticmethod
    def _format(diff, include_checksums=False):
        """
        Given a diff structure, generate a string of filenames separated
        by new lines and grouped together by their state.

        A group's header is colored and its entries are sorted to enhance
        readability, for example:

            Added:
                another_file.txt
                backup.tar
                dir/
                dir/1

        An example of a diff formatted when `include_checksums` is truthy:

            Added:
                d3b07384 foo

            Modified:
                c157a790..f98bf6f1 bar

        If a group has no entries, it won't be included in the result.
        """

        def _digest(checksum):
            if type(checksum) is str:
                return checksum[0:8]
            return "{}..{}".format(checksum["old"][0:8], checksum["new"][0:8])

        colors = {
            "added": colorama.Fore.GREEN,
            "modified": colorama.Fore.YELLOW,
            "deleted": colorama.Fore.RED,
        }

        groups = []

        for state, entries in diff.items():
            if not entries:
                continue

            entries = [tuple(entry.values()) for entry in entries]
            entries = [
                "{space}{checksum}{separator}{filename}".format(
                    space="    ",
                    checksum=_digest(checksum) if include_checksums else "",
                    separator="  " if include_checksums else "",
                    filename=filename,
                )
                for filename, checksum in entries
            ]

            groups.append(
                "{color}{header}{nc}:\n{entries}".format(
                    color=colors[state],
                    header=state.capitalize(),
                    nc=colorama.Fore.RESET,
                    entries="\n".join(entries),
                )
            )

        return "\n\n".join(groups)

    def run(self):
        try:
            diff = self.repo.diff(
                self.args.a_ref, self.args.b_ref, target=self.args.target
            )

            if not any(diff.values()):
                return 0

            if self.args.json:
                print(json.dumps(diff))
                return 0

            print(self._format(diff, include_checksums=self.args.checksums))

        except DvcException:
            logger.exception("failed to get diff")
            return 1
        return 0


def add_parser(subparsers, parent_parser):
    DIFF_DESCRIPTION = (
        "Show diff of a data file or a directory that is under DVC control.\n"
        "Some basic statistics summary, how many files were deleted/changed."
    )
    DIFF_HELP = "Show a diff of a DVC controlled data file or a directory."
    diff_parser = subparsers.add_parser(
        "diff",
        parents=[parent_parser],
        description=append_doc_link(DIFF_DESCRIPTION, "diff"),
        help=DIFF_HELP,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    diff_parser.add_argument(
        "a_ref",
        help="Git reference from which diff calculates (defaults to HEAD)",
        nargs="?",
        default="HEAD",
    )
    diff_parser.add_argument(
        "b_ref",
        help=(
            "Git reference until which diff calculates, if omitted "
            "diff shows the difference between the working tree and a_ref"
        ),
        nargs="?",
    )
    diff_parser.add_argument(
        "-t",
        "--target",
        help=(
            "Source path to a data file or directory. Default None. "
            "If not specified, compares all files and directories "
            "that are under DVC control in the current working space."
        ),
    )
    diff_parser.add_argument(
        "--json",
        help=("Format the output into a JSON"),
        action="store_true",
        default=False,
    )
    diff_parser.add_argument(
        "--checksums",
        help=("Display checksums for each entry"),
        action="store_true",
        default=False,
    )
    diff_parser.set_defaults(func=CmdDiff)<commit_msg>:nail_care: remove excesive parenthesis<commit_after>import argparse
import json
import logging

import colorama

from dvc.command.base import CmdBase, append_doc_link
from dvc.exceptions import DvcException


logger = logging.getLogger(__name__)


class CmdDiff(CmdBase):
    @staticmethod
    def _format(diff, include_checksums=False):
        """
        Given a diff structure, generate a string of filenames separated
        by new lines and grouped together by their state.

        A group's header is colored and its entries are sorted to enhance
        readability, for example:

            Added:
                another_file.txt
                backup.tar
                dir/
                dir/1

        An example of a diff formatted when `include_checksums` is truthy:

            Added:
                d3b07384 foo

            Modified:
                c157a790..f98bf6f1 bar

        If a group has no entries, it won't be included in the result.
        """

        def _digest(checksum):
            if type(checksum) is str:
                return checksum[0:8]
            return "{}..{}".format(checksum["old"][0:8], checksum["new"][0:8])

        colors = {
            "added": colorama.Fore.GREEN,
            "modified": colorama.Fore.YELLOW,
            "deleted": colorama.Fore.RED,
        }

        groups = []

        for state, entries in diff.items():
            if not entries:
                continue

            entries = [tuple(entry.values()) for entry in entries]
            entries = [
                "{space}{checksum}{separator}{filename}".format(
                    space="    ",
                    checksum=_digest(checksum) if include_checksums else "",
                    separator="  " if include_checksums else "",
                    filename=filename,
                )
                for filename, checksum in entries
            ]

            groups.append(
                "{color}{header}{nc}:\n{entries}".format(
                    color=colors[state],
                    header=state.capitalize(),
                    nc=colorama.Fore.RESET,
                    entries="\n".join(entries),
                )
            )

        return "\n\n".join(groups)

    def run(self):
        try:
            diff = self.repo.diff(
                self.args.a_ref, self.args.b_ref, target=self.args.target
            )

            if not any(diff.values()):
                return 0

            if self.args.json:
                print(json.dumps(diff))
                return 0

            print(self._format(diff, include_checksums=self.args.checksums))

        except DvcException:
            logger.exception("failed to get diff")
            return 1
        return 0


def add_parser(subparsers, parent_parser):
    DIFF_DESCRIPTION = (
        "Show diff of a data file or a directory that is under DVC control.\n"
        "Some basic statistics summary, how many files were deleted/changed."
    )
    DIFF_HELP = "Show a diff of a DVC controlled data file or a directory."
    diff_parser = subparsers.add_parser(
        "diff",
        parents=[parent_parser],
        description=append_doc_link(DIFF_DESCRIPTION, "diff"),
        help=DIFF_HELP,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    diff_parser.add_argument(
        "a_ref",
        help="Git reference from which diff calculates (defaults to HEAD)",
        nargs="?",
        default="HEAD",
    )
    diff_parser.add_argument(
        "b_ref",
        help=(
            "Git reference until which diff calculates, if omitted "
            "diff shows the difference between the working tree and a_ref"
        ),
        nargs="?",
    )
    diff_parser.add_argument(
        "-t",
        "--target",
        help=(
            "Source path to a data file or directory. Default None. "
            "If not specified, compares all files and directories "
            "that are under DVC control in the current working space."
        ),
    )
    diff_parser.add_argument(
        "--json",
        help="Format the output into a JSON",
        action="store_true",
        default=False,
    )
    diff_parser.add_argument(
        "--checksums",
        help="Display checksums for each entry",
        action="store_true",
        default=False,
    )
    diff_parser.set_defaults(func=CmdDiff)
{'fraction_non_alphanumeric': 0.09155413138017852, 'fraction_numerical': 0.0061799038681620505, 'mean_word_length': 1.6790312691600244, 'pattern_counts': {'":': 6, '<': 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': '2086633', 'n_tokens_mistral': 2446, 'n_tokens_neox': 2270, 'n_words': 636}