annotate.py 4.4 KB

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