annotate.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. # annotate.py -- Annotate files with last changed revision
  2. # Copyright (C) 2015 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # or (at your option) a later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Annotate file contents indicating when they were last changed.
  19. Annotated lines are represented as tuples with last modified revision SHA1
  20. and contents.
  21. Please note that this is a very naive annotate implementation. It works,
  22. but its speed could be improved - in particular because it uses
  23. Python's difflib.
  24. """
  25. import difflib
  26. from typing import TYPE_CHECKING, Optional, cast
  27. from dulwich.walk import (
  28. ORDER_DATE,
  29. Walker,
  30. )
  31. if TYPE_CHECKING:
  32. from dulwich.diff_tree import TreeChange, TreeEntry
  33. from dulwich.object_store import BaseObjectStore
  34. from dulwich.objects import Blob, Commit
  35. # Walk over ancestry graph breadth-first
  36. # When checking each revision, find lines that according to difflib.Differ()
  37. # are common between versions.
  38. # Any lines that are not in common were introduced by the newer revision.
  39. # If there were no lines kept from the older version, stop going deeper in the
  40. # graph.
  41. def update_lines(
  42. annotated_lines: list[tuple[tuple["Commit", "TreeEntry"], bytes]],
  43. new_history_data: tuple["Commit", "TreeEntry"],
  44. new_blob: "Blob",
  45. ) -> list[tuple[tuple["Commit", "TreeEntry"], bytes]]:
  46. """Update annotation lines with old blob lines."""
  47. ret: list[tuple[tuple[Commit, TreeEntry], bytes]] = []
  48. new_lines = new_blob.splitlines()
  49. matcher = difflib.SequenceMatcher(
  50. a=[line for (h, line) in annotated_lines], b=new_lines
  51. )
  52. for tag, i1, i2, j1, j2 in matcher.get_opcodes():
  53. if tag == "equal":
  54. ret.extend(annotated_lines[i1:i2])
  55. elif tag in ("insert", "replace"):
  56. ret.extend([(new_history_data, line) for line in new_lines[j1:j2]])
  57. elif tag == "delete":
  58. pass # don't care
  59. else:
  60. raise RuntimeError(f"Unknown tag {tag} returned in diff")
  61. return ret
  62. def annotate_lines(
  63. store: "BaseObjectStore",
  64. commit_id: bytes,
  65. path: bytes,
  66. order: str = ORDER_DATE,
  67. lines: Optional[list[tuple[tuple["Commit", "TreeEntry"], bytes]]] = None,
  68. follow: bool = True,
  69. ) -> list[tuple[tuple["Commit", "TreeEntry"], bytes]]:
  70. """Annotate the lines of a blob.
  71. :param store: Object store to retrieve objects from
  72. :param commit_id: Commit id in which to annotate path
  73. :param path: Path to annotate
  74. :param order: Order in which to process history (defaults to ORDER_DATE)
  75. :param lines: Initial lines to compare to (defaults to specified)
  76. :param follow: Whether to follow changes across renames/copies
  77. :return: List of (commit, line) entries where
  78. commit is the oldest commit that changed a line
  79. """
  80. walker = Walker(
  81. store, include=[commit_id], paths=[path], order=order, follow=follow
  82. )
  83. revs: list[tuple[Commit, TreeEntry]] = []
  84. for log_entry in walker:
  85. for tree_change in log_entry.changes():
  86. changes: list[TreeChange]
  87. if isinstance(tree_change, list):
  88. changes = tree_change
  89. else:
  90. changes = [tree_change]
  91. for change in changes:
  92. if change.new.path == path:
  93. path = change.old.path
  94. revs.append((log_entry.commit, change.new))
  95. break
  96. lines_annotated: list[tuple[tuple[Commit, TreeEntry], bytes]] = []
  97. for commit, entry in reversed(revs):
  98. lines_annotated = update_lines(
  99. lines_annotated, (commit, entry), cast("Blob", store[entry.sha])
  100. )
  101. return lines_annotated