Ejemplo n.º 1
0
def format_file(
    src: Path,
    from_line: int,
    to_line: int,
    config: str = None,
):
    black_args = BlackConfig(config=config)
    edited = worktree_content = TextDocument.from_file(src)
    max_context_lines = len(edited.lines)
    minimum_context_lines = BinarySearch(0, max_context_lines + 1)
    edited_linenums = list(range(from_line, to_line + 1))

    while not minimum_context_lines.found:
        formatted = run_black(edited, black_args)
        opcodes = diff_and_get_opcodes(edited, formatted)
        black_chunks = list(opcodes_to_chunks(opcodes, edited, formatted))
        chosen = TextDocument.from_lines(
            choose_lines(black_chunks, edited_linenums),
            encoding=worktree_content.encoding,
            newline=worktree_content.newline,
        )

        try:
            verify_ast_unchanged(edited, chosen, black_chunks, edited_linenums)
        except NotEquivalentError:
            minimum_context_lines.respond(False)
        else:
            minimum_context_lines.respond(True)
            modify_file(src, chosen)
Ejemplo n.º 2
0
    def revision_vs_lines(self, path_in_repo: Path, lines: List[str],
                          context_lines: int) -> List[int]:
        """For file `path_in_repo`, return changed line numbers from given revision

        :param path_in_repo: Path of the file to compare, relative to repository root
        :param lines: The contents to compare to, e.g. from current working tree
        :return: Line numbers of lines changed between the revision and given content

        """
        revision_lines = git_get_unmodified_content(path_in_repo,
                                                    self.revision,
                                                    self.git_root)
        edited_opcodes = diff_and_get_opcodes(revision_lines, lines)
        return list(opcodes_to_edit_linenums(edited_opcodes, context_lines))
Ejemplo n.º 3
0
Archivo: git.py Proyecto: wnoise/darker
    def revision_vs_lines(self, path_in_repo: Path, content: TextDocument,
                          context_lines: int) -> List[int]:
        """For file `path_in_repo`, return changed line numbers from given revision

        :param path_in_repo: Path of the file to compare, relative to repository root
        :param content: The contents to compare to, e.g. from current working tree
        :param context_lines: The number of lines to include before and after a change
        :return: Line numbers of lines changed between the revision and given content

        """
        old = git_get_content_at_revision(path_in_repo, self.revrange.rev1,
                                          self.git_root)
        edited_opcodes = diff_and_get_opcodes(old, content)
        return list(opcodes_to_edit_linenums(edited_opcodes, context_lines))
Ejemplo n.º 4
0
def test_diff_and_get_opcodes():
    src_lines = FUNCTIONS2_PY.splitlines()
    dst_lines = FUNCTIONS2_PY_REFORMATTED.splitlines()
    opcodes = diff_and_get_opcodes(src_lines, dst_lines)
    assert opcodes == EXPECT_OPCODES
Ejemplo n.º 5
0
def format_edited_parts(
    srcs: Iterable[Path],
    revision: str,
    enable_isort: bool,
    linter_cmdlines: List[str],
    black_args: BlackArgs,
) -> Generator[Tuple[Path, str, str, List[str]], None, None]:
    """Black (and optional isort) formatting for chunks with edits since the last commit

    1. run isort on each edited file (optional)
    2. diff the given revision and worktree (optionally with isort modifications) for
       all file & dir paths on the command line
    3. extract line numbers in each edited to-file for changed lines
    4. run black on the contents of each edited to-file
    5. get a diff between the edited to-file and the reformatted content
    6. convert the diff into chunks, keeping original and reformatted content for each
       chunk
    7. choose reformatted content for each chunk if there were any changed lines inside
       the chunk in the edited to-file, or choose the chunk's original contents if no
       edits were done in that chunk
    8. concatenate all chosen chunks
    9. verify that the resulting reformatted source code parses to an identical AST as
       the original edited to-file
    10. write the reformatted source back to the original file
    11. run linter subprocesses for all edited files (11.-14. optional)
    12. diff the given revision and worktree (after isort and Black reformatting) for
        each file reported by a linter
    13. extract line numbers in each file reported by a linter for changed lines
    14. print only linter error lines which fall on changed lines

    :param srcs: Directories and files to re-format
    :param revision: The Git revision against which to compare the working tree
    :param enable_isort: ``True`` to also run ``isort`` first on each changed file
    :param linter_cmdlines: The command line(s) for running linters on the changed
                            files.
    :param black_args: Command-line arguments to send to ``black.FileMode``
    :return: A generator which yields details about changes for each file which should
             be reformatted, and skips unchanged files.

    """
    git_root = get_common_root(srcs)
    changed_files = git_get_modified_files(srcs, revision, git_root)
    edited_linenums_differ = EditedLinenumsDiffer(git_root, revision)

    for path_in_repo in sorted(changed_files):
        src = git_root / path_in_repo
        worktree_content = src.read_text()

        # 1. run isort
        if enable_isort:
            edited_content = apply_isort(
                worktree_content,
                src,
                black_args.get("config"),
                black_args.get("line_length"),
            )
        else:
            edited_content = worktree_content
        edited_lines = edited_content.splitlines()
        max_context_lines = len(edited_lines)
        for context_lines in range(max_context_lines + 1):
            # 2. diff the given revision and worktree for the file
            # 3. extract line numbers in the edited to-file for changed lines
            edited_linenums = edited_linenums_differ.revision_vs_lines(
                path_in_repo, edited_lines, context_lines)
            if (enable_isort and not edited_linenums
                    and edited_content == worktree_content):
                logger.debug("No changes in %s after isort", src)
                break

            # 4. run black
            formatted = run_black(src, edited_content, black_args)
            logger.debug("Read %s lines from edited file %s",
                         len(edited_lines), src)
            logger.debug("Black reformat resulted in %s lines", len(formatted))

            # 5. get the diff between the edited and reformatted file
            opcodes = diff_and_get_opcodes(edited_lines, formatted)

            # 6. convert the diff into chunks
            black_chunks = list(
                opcodes_to_chunks(opcodes, edited_lines, formatted))

            # 7. choose reformatted content
            chosen_lines: List[str] = list(
                choose_lines(black_chunks, edited_linenums))

            # 8. concatenate chosen chunks
            result_str = joinlines(chosen_lines)

            # 9. verify
            logger.debug(
                "Verifying that the %s original edited lines and %s reformatted lines "
                "parse into an identical abstract syntax tree",
                len(edited_lines),
                len(chosen_lines),
            )
            try:
                verify_ast_unchanged(edited_content, result_str, black_chunks,
                                     edited_linenums)
            except NotEquivalentError:
                # Diff produced misaligned chunks which couldn't be reconstructed into
                # a partially re-formatted Python file which produces an identical AST.
                # Try again with a larger `-U<context_lines>` option for `git diff`,
                # or give up if `context_lines` is already very large.
                if context_lines == max_context_lines:
                    raise
                logger.debug(
                    "AST verification failed. "
                    "Trying again with %s lines of context for `git diff -U`",
                    context_lines + 1,
                )
                continue
            else:
                # 10. A re-formatted Python file which produces an identical AST was
                #     created successfully - write an updated file or print the diff
                #     if there were any changes to the original
                if result_str != worktree_content:
                    # `result_str` is just `chosen_lines` concatenated with newlines.
                    # We need both forms when showing diffs or modifying files.
                    # Pass them both on to avoid back-and-forth conversion.
                    yield src, worktree_content, result_str, chosen_lines
                break
    # 11. run linter subprocesses for all edited files (11.-14. optional)
    # 12. diff the given revision and worktree (after isort and Black reformatting) for
    #     each file reported by a linter
    # 13. extract line numbers in each file reported by a linter for changed lines
    # 14. print only linter error lines which fall on changed lines
    for linter_cmdline in linter_cmdlines:
        run_linter(linter_cmdline, git_root, changed_files, revision)
Ejemplo n.º 6
0
def post_gh_suggestion(path, old_content: str, new_lines):
    # assert (
    #    os.environ["GITHUB_EVENT_NAME"] == "pull_request"
    # ), "This action runs only on pull request events."
    github_token = os.environ.get("GITHUB_TOKEN", None)
    import json
    import requests

    # maybe cleanup previous comments

    try:
        with open(os.environ["GITHUB_EVENT_PATH"]) as f:
            event_data = json.load(f)
        comment_url = event_data["pull_request"]["review_comments_url"]
        commit_id = event_data["pull_request"]["head"]["sha"]
        mock = False
    except Exception:
        comment_url = "Mock URL"
        commit_id = "MOCK ID"
        mock = True
    headers = {
        "authorization": f"Bearer {github_token}",
        "Accept": COMFORT_FADE,
        # "Accept": "application/vnd.github.v3.raw+json",
    }
    if not mock:
        data = requests.get(comment_url, headers=headers).json()
    print(f"Found {len(data)} comments")
    for comment in data:
        c_user = comment["user"]["login"]
        c_id = comment["user"]["id"]
        c_is_darker = "<!-- darker-autoreformat-action -->" in comment["body"]
        should_remove = (c_user == "github-actions[bot]" and (c_id == 41898282)
                         and c_is_darker)
        print(f"{c_user=}, {c_id=} , {c_is_darker=}, {should_remove=}")
        print("removing... ", comment["url"])
        requests.delete(comment["url"], headers=headers)

    changes = []
    new_content = "\n".join(new_lines)
    for action, x, y, z, t in diff_and_get_opcodes(old_content.splitlines(),
                                                   new_lines):
        sugg = ""
        old_cont = "\n".join(old_content.splitlines()[x:y])
        if action == "replace":
            old_cont = "\n".join(old_content.splitlines()[x:y])
            sugg = "\n" + "\n".join(new_lines[z:t])
            start = x + 1
            end = y
        elif action == "insert":
            old_cont = "\n".join(old_content.splitlines()[x - 1:y])
            sugg = "\n" + "\n".join(new_lines[z - 1:t])
            start = x
            end = y
        elif action == "delete":
            continue
        elif action == "equal":
            continue
        else:
            raise ValueError(action)
        body = f"""
from {x} to {y} : {action}
```suggestion{sugg}
```
should replace ({z}, {t}):
```
{old_cont}

```
<!-- darker-autoreformat-action -->
            """
        print(body)
        if start == y:
            print("!!! we have an equal ! {start=}, {end=} for {action}")
        changes.append((path, start, end, body))
    print(
        f"Will post about {len(changes)} changes (cutting to max 15 for now)")
    changes = changes[:15]

    def post(action, url, json, headers):
        print("===========")
        # print(action)
        # print(url)
        # print(json)
        # print({k:v for k,v in headers.items() if k != 'authorization'})
        print("===")
        if not mock:
            res = requests.post(url, json=json, headers=headers)
            print("REPLY")
            print(res.json())
            print("REPLY END")
            res.raise_for_status()
        else:
            print("no actual requests...")

    def suggests(changes, head_sha, comment_url):
        review_url = comment_url.rsplit("/", maxsplit=1)[0] + "/reviews"

        comments = []
        for path, start, end, body in changes:
            data = {
                "body": body,
                # "commit_id": head_sha,
                "path": path,
                "line": end,
                "side": "RIGHT",
            }
            if start != end:
                print(f"{start=}, {end=}")
                data.update({
                    "start_line": start,
                    "start_side": "RIGHT",
                })
            comments.append(data)
        review_data = {
            "body":
            "This is an automated review from GitHub action that suggest changes to autoformat the code using Darker.",
            "commit_id": head_sha,
            "event": "REQUEST_CHANGES" if comments else "APPROVE",
            "comments": comments,
        }
        post(
            "POST",
            review_url,
            json=review_data,
            headers=headers,
        )

    suggests(changes, commit_id, comment_url)
Ejemplo n.º 7
0
def format_edited_parts(
    srcs: Iterable[Path],
    isort: bool,
    black_args: Dict[str, Union[bool, int]],
    print_diff: bool,
) -> None:
    """Black (and optional isort) formatting for chunks with edits since the last commit

    1. run isort on each edited file
    2. diff HEAD and worktree for all file & dir paths on the command line
    3. extract line numbers in each edited to-file for changed lines
    4. run black on the contents of each edited to-file
    5. get a diff between the edited to-file and the reformatted content
    6. convert the diff into chunks, keeping original and reformatted content for each
       chunk
    7. choose reformatted content for each chunk if there were any changed lines inside
       the chunk in the edited to-file, or choose the chunk's original contents if no
       edits were done in that chunk
    8. concatenate all chosen chunks
    9. verify that the resulting reformatted source code parses to an identical AST as
       the original edited to-file
    10. write the reformatted source back to the original file

    :param srcs: Directories and files to re-format
    :param isort: ``True`` to also run ``isort`` first on each changed file
    :param black_args: Command-line arguments to send to ``black.FileMode``
    :param print_diff: ``True`` to output diffs instead of modifying source files

    """
    git_root = get_common_root(srcs)
    changed_files = git_diff_name_only(srcs, git_root)
    head_srcs = {
        src: git_get_unmodified_content(src, git_root) for src in changed_files
    }
    worktree_srcs = {src: (git_root / src).read_text() for src in changed_files}

    # 1. run isort
    if isort:
        edited_srcs = {
            src: apply_isort(edited_content)
            for src, edited_content in worktree_srcs.items()
        }
    else:
        edited_srcs = worktree_srcs

    for src_relative, edited_content in edited_srcs.items():
        for context_lines in range(MAX_CONTEXT_LINES + 1):
            src = git_root / src_relative
            edited = edited_content.splitlines()
            head_lines = head_srcs[src_relative]

            # 2. diff HEAD and worktree for all file & dir paths on the command line
            edited_opcodes = diff_and_get_opcodes(head_lines, edited)

            # 3. extract line numbers in each edited to-file for changed lines
            edited_linenums = list(opcodes_to_edit_linenums(edited_opcodes))
            if (
                isort
                and not edited_linenums
                and edited_content == worktree_srcs[src_relative]
            ):
                logger.debug("No changes in %s after isort", src)
                break

            # 4. run black
            formatted = run_black(src, edited_content, black_args)
            logger.debug("Read %s lines from edited file %s", len(edited), src)
            logger.debug("Black reformat resulted in %s lines", len(formatted))

            # 5. get the diff between each edited and reformatted file
            opcodes = diff_and_get_opcodes(edited, formatted)

            # 6. convert the diff into chunks
            black_chunks = list(opcodes_to_chunks(opcodes, edited, formatted))

            # 7. choose reformatted content
            chosen_lines: List[str] = list(choose_lines(black_chunks, edited_linenums))

            # 8. concatenate chosen chunks
            result_str = joinlines(chosen_lines)

            # 9. verify
            logger.debug(
                "Verifying that the %s original edited lines and %s reformatted lines "
                "parse into an identical abstract syntax tree",
                len(edited),
                len(chosen_lines),
            )
            try:
                verify_ast_unchanged(
                    edited_content, result_str, black_chunks, edited_linenums
                )
            except NotEquivalentError:
                # Diff produced misaligned chunks which couldn't be reconstructed into
                # a partially re-formatted Python file which produces an identical AST.
                # Try again with a larger `-U<context_lines>` option for `git diff`,
                # or give up if `context_lines` is already very large.
                if context_lines == MAX_CONTEXT_LINES:
                    raise
                logger.debug(
                    "AST verification failed. "
                    "Trying again with %s lines of context for `git diff -U`",
                    context_lines + 1,
                )
                continue
            else:
                # 10. A re-formatted Python file which produces an identical AST was
                #     created successfully - write an updated file
                #     or print the diff
                if print_diff:
                    difflines = list(
                        unified_diff(
                            worktree_srcs[src_relative].splitlines(),
                            chosen_lines,
                            src.as_posix(),
                            src.as_posix(),
                        )
                    )
                    if len(difflines) > 2:
                        h1, h2, *rest = difflines
                        print(h1, end="")
                        print(h2, end="")
                        print("\n".join(rest))
                else:
                    logger.info("Writing %s bytes into %s", len(result_str), src)
                    src.write_text(result_str)
                break
Ejemplo n.º 8
0
def test_diff_and_get_opcodes():
    src = TextDocument.from_str(FUNCTIONS2_PY)
    dst = TextDocument.from_str(FUNCTIONS2_PY_REFORMATTED)
    opcodes = diff_and_get_opcodes(src, dst)
    assert opcodes == EXPECT_OPCODES
Ejemplo n.º 9
0
def format_edited_parts(
    git_root: Path,
    changed_files: Iterable[Path],
    revrange: RevisionRange,
    enable_isort: bool,
    black_args: BlackArgs,
) -> Generator[Tuple[Path, TextDocument, TextDocument], None, None]:
    """Black (and optional isort) formatting for chunks with edits since the last commit

    :param git_root: The root of the Git repository the files are in
    :param changed_files: Files which have been modified in the repository between the
                          given Git revisions
    :param revrange: The Git revisions to compare
    :param enable_isort: ``True`` to also run ``isort`` first on each changed file
    :param black_args: Command-line arguments to send to ``black.FileMode``
    :return: A generator which yields details about changes for each file which should
             be reformatted, and skips unchanged files.

    """
    edited_linenums_differ = EditedLinenumsDiffer(git_root, revrange)

    for path_in_repo in sorted(changed_files):
        src = git_root / path_in_repo
        worktree_content = TextDocument.from_file(src)

        # 1. run isort
        if enable_isort:
            edited = apply_isort(
                worktree_content,
                src,
                black_args.get("config"),
                black_args.get("line_length"),
            )
        else:
            edited = worktree_content
        max_context_lines = len(edited.lines)
        minimum_context_lines = BinarySearch(0, max_context_lines + 1)
        last_successful_reformat = None
        while not minimum_context_lines.found:
            context_lines = minimum_context_lines.get_next()
            if context_lines > 0:
                logger.debug(
                    "Trying with %s lines of context for `git diff -U %s`",
                    context_lines,
                    src,
                )
            # 2. diff the given revision and worktree for the file
            # 3. extract line numbers in the edited to-file for changed lines
            edited_linenums = edited_linenums_differ.revision_vs_lines(
                path_in_repo, edited, context_lines)
            if enable_isort and not edited_linenums and edited == worktree_content:
                logger.debug("No changes in %s after isort", src)
                break

            # 4. run black
            formatted = run_black(src, edited, black_args)
            logger.debug("Read %s lines from edited file %s",
                         len(edited.lines), src)
            logger.debug("Black reformat resulted in %s lines",
                         len(formatted.lines))

            # 5. get the diff between the edited and reformatted file
            opcodes = diff_and_get_opcodes(edited, formatted)

            # 6. convert the diff into chunks
            black_chunks = list(opcodes_to_chunks(opcodes, edited, formatted))

            # 7. choose reformatted content
            chosen = TextDocument.from_lines(
                choose_lines(black_chunks, edited_linenums),
                encoding=worktree_content.encoding,
                newline=worktree_content.newline,
            )

            # 8. verify
            logger.debug(
                "Verifying that the %s original edited lines and %s reformatted lines "
                "parse into an identical abstract syntax tree",
                len(edited.lines),
                len(chosen.lines),
            )
            try:
                verify_ast_unchanged(edited, chosen, black_chunks,
                                     edited_linenums)
            except NotEquivalentError:
                # Diff produced misaligned chunks which couldn't be reconstructed into
                # a partially re-formatted Python file which produces an identical AST.
                # Try again with a larger `-U<context_lines>` option for `git diff`,
                # or give up if `context_lines` is already very large.
                logger.debug(
                    "AST verification of %s with %s lines of context failed",
                    src,
                    context_lines,
                )
                minimum_context_lines.respond(False)
            else:
                minimum_context_lines.respond(True)
                last_successful_reformat = (src, worktree_content, chosen)
        if not last_successful_reformat:
            raise NotEquivalentError(path_in_repo)
        # 9. A re-formatted Python file which produces an identical AST was
        #    created successfully - write an updated file or print the diff if
        #    there were any changes to the original
        src, worktree_content, chosen = last_successful_reformat
        if chosen != worktree_content:
            # `result_str` is just `chosen_lines` concatenated with newlines.
            # We need both forms when showing diffs or modifying files.
            # Pass them both on to avoid back-and-forth conversion.
            yield src, worktree_content, chosen
Ejemplo n.º 10
0
def test_diff_and_get_opcodes():
    src_lines = FUNCTIONS2_PY.splitlines()
    dst_lines = format_str(FUNCTIONS2_PY, mode=FileMode()).splitlines()
    opcodes = diff_and_get_opcodes(src_lines, dst_lines)
    assert opcodes == OPCODES