annotate.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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
  27. from dulwich.objects import Blob
  28. from dulwich.walk import (
  29. ORDER_DATE,
  30. Walker,
  31. )
  32. if TYPE_CHECKING:
  33. from dulwich.diff_tree import TreeChange, TreeEntry
  34. from dulwich.object_store import BaseObjectStore
  35. from dulwich.objects import Commit
  36. # Walk over ancestry graph breadth-first
  37. # When checking each revision, find lines that according to difflib.Differ()
  38. # are common between versions.
  39. # Any lines that are not in common were introduced by the newer revision.
  40. # If there were no lines kept from the older version, stop going deeper in the
  41. # graph.
  42. def update_lines(
  43. annotated_lines: list[tuple[tuple["Commit", "TreeEntry"], bytes]],
  44. new_history_data: tuple["Commit", "TreeEntry"],
  45. new_blob: "Blob",
  46. ) -> list[tuple[tuple["Commit", "TreeEntry"], bytes]]:
  47. """Update annotation lines with old blob lines."""
  48. ret: list[tuple[tuple[Commit, TreeEntry], bytes]] = []
  49. new_lines = new_blob.splitlines()
  50. matcher = difflib.SequenceMatcher(
  51. a=[line for (h, line) in annotated_lines], b=new_lines
  52. )
  53. for tag, i1, i2, j1, j2 in matcher.get_opcodes():
  54. if tag == "equal":
  55. ret.extend(annotated_lines[i1:i2])
  56. elif tag in ("insert", "replace"):
  57. ret.extend([(new_history_data, line) for line in new_lines[j1:j2]])
  58. elif tag == "delete":
  59. pass # don't care
  60. else:
  61. raise RuntimeError(f"Unknown tag {tag} returned in diff")
  62. return ret
  63. def annotate_lines(
  64. store: "BaseObjectStore",
  65. commit_id: bytes,
  66. path: bytes,
  67. order: str = ORDER_DATE,
  68. lines: Optional[list[tuple[tuple["Commit", "TreeEntry"], bytes]]] = None,
  69. follow: bool = True,
  70. ) -> list[tuple[tuple["Commit", "TreeEntry"], bytes]]:
  71. """Annotate the lines of a blob.
  72. :param store: Object store to retrieve objects from
  73. :param commit_id: Commit id in which to annotate path
  74. :param path: Path to annotate
  75. :param order: Order in which to process history (defaults to ORDER_DATE)
  76. :param lines: Initial lines to compare to (defaults to specified)
  77. :param follow: Whether to follow changes across renames/copies
  78. :return: List of (commit, line) entries where
  79. commit is the oldest commit that changed a line
  80. """
  81. walker = Walker(
  82. store, include=[commit_id], paths=[path], order=order, follow=follow
  83. )
  84. revs: list[tuple[Commit, TreeEntry]] = []
  85. for log_entry in walker:
  86. for tree_change in log_entry.changes():
  87. changes: list[TreeChange]
  88. if isinstance(tree_change, list):
  89. changes = tree_change
  90. else:
  91. changes = [tree_change]
  92. for change in changes:
  93. if change.new.path == path:
  94. path = change.old.path
  95. revs.append((log_entry.commit, change.new))
  96. break
  97. lines_annotated: list[tuple[tuple[Commit, TreeEntry], bytes]] = []
  98. for commit, entry in reversed(revs):
  99. blob_obj = store[entry.sha]
  100. assert isinstance(blob_obj, Blob)
  101. lines_annotated = update_lines(lines_annotated, (commit, entry), blob_obj)
  102. return lines_annotated