git_to_sphinx.py¶
Last source¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 | #!/usr/bin/env python
# Set env `GIT_TO_SPHINX_UPDATE_BRANCHES` to other than empty string to update the remote branches
# Careful: in dev environment it will reset all your local branches if they diverged from the
# remove ones
import os
import re
import shutil
import sys
import tempfile
from collections import defaultdict
from contextlib import contextmanager
from functools import partial
import rstcheck
from cached_property import cached_property
from git.objects.util import from_timestamp
from pydriller import RepositoryMining as RepositoryMiningBase
from pydriller.domain.commit import ModificationType
from pydriller.git_repository import GitRepository as GitRepositoryBase
DOC_DIRNAME = "git"
SOURCE_DIRNAME = "source"
DIRNAME = os.path.dirname(__file__)
BASEPATH = os.path.join(DIRNAME, DOC_DIRNAME)
SOURCE_BASE_PATH = os.path.join(DIRNAME, SOURCE_DIRNAME)
REMOVED = " (removed)"
GIT_ENVIRON = {
"GIT_COMMITTER_NAME": "git-to-sphinx",
"GIT_COMMITTER_EMAIL": "git-to-sphinx@example.com",
"GIT_AUTHOR_NAME": "git-to-sphinx",
"GIT_AUTHOR_EMAIL": "git-to-sphinx@example.com",
}
@contextmanager
def override_environ(**env):
original_env = {key: os.getenv(key) for key in env}
os.environ.update(env)
try:
yield
finally:
for key, value in original_env.items():
if value is None:
del os.environ[key]
else:
os.environ[key] = value
def slugify(text):
text = text.lower()
for c in slugify.to_underscore:
text = text.replace(c, "_")
text = slugify.re_W.sub("", text).replace("_", " ")
return slugify.re_s.sub(" ", text).strip().replace(" ", "-")
slugify.to_underscore = [" ", "-", ".", "/"]
slugify.re_W = re.compile(r"\W")
slugify.re_s = re.compile(r"\s+")
def escape_path(path):
if path.endswith(".rst"):
path += "_"
return path
def escape_subject(text):
for what, how in escape_subject.replacements:
text = text.replace(what, how)
return text
escape_subject.replacements = [("*", r"\*"), ("_", r"\_")]
def path_in_tree(path, tree, allow_root=True):
if allow_root and (not path or path == "/"):
return True
return path in tree
MODIFICATION_TYPES = {
"ADD": "Added",
"COPY": "Copied",
"RENAME": "Renamed",
"DELETE": "Deleted",
"MODIFY": "Modified",
"UNKNOWN": "Unknown",
}
class GitRepository(GitRepositoryBase):
@cached_property
def git(self):
return super().git
def _discover_main_branch(self, repo):
if repo.head.is_detached:
for branch in repo.branches:
if branch.commit.hexsha == repo.head.commit.hexsha:
self._conf.set_value("main_branch", branch.name)
else:
super()._discover_main_branch(repo)
@cached_property
def repo(self):
return super().repo
def get_list_tags(self):
for tag in sorted(
self.repo.tags,
key=lambda t: t.commit.committed_datetime,
reverse=True,
):
yield tag
def get_list_branches(self):
for branch in sorted(
self.repo.branches,
key=lambda t: t.commit.committed_datetime,
reverse=True,
):
yield branch
def get_list_tree(self, node, parent_path=""):
for child in node:
path = os.path.join(parent_path, child.name)
yield (child, path)
if child.type == "tree":
yield from self.get_list_tree(child, path)
def get_flat_tree(self):
yield from self.get_list_tree(self.get_head()._c_object.tree)
class RepositoryMining(RepositoryMiningBase):
def get_git_repo(self):
path_repo = self._conf.get("path_to_repos")[0]
if self._is_remote(path_repo):
path_repo = self._clone_remote_repo(self._clone_folder(), path_repo)
git_repo = GitRepository(path_repo)
# we need to fetch all branches:
repo = git_repo.repo
if os.environ.get("GIT_TO_SPHINX_UPDATE_BRANCHES"):
# get remote branches not fetched yet
existing_branches = {
branch.name: branch.commit.hexsha for branch in repo.branches
}
remote_branches = {}
for ref_info in repo.remote("origin").fetch():
local_ref_name = ref_info.name.split("/", 1)[1]
if ref_info.commit.hexsha != existing_branches.get(local_ref_name):
remote_branches[local_ref_name] = ref_info.name
if remote_branches:
# save the current head
head_detached = repo.head.is_detached
if head_detached:
current_ref = repo.head.commit
else:
current_ref = repo.head.ref
# stash existing updates if needed
with override_environ(**GIT_ENVIRON):
stashed = "No local changes to save" not in repo.git.stash(
"save", "-u"
)
# fetch remote branches not fetched yet
for local_branch_name, remote_branch_name in remote_branches.items():
repo.git.checkout("-B", local_branch_name, remote_branch_name)
# restore previous head
if head_detached:
repo.git.checkout(current_ref.hexsha)
else:
current_ref.checkout()
# and restore previous updates
if stashed:
with override_environ(**GIT_ENVIRON):
repo.git.stash("pop")
# get the branch from the head now that we are sure we have all branches
git_repo._discover_main_branch(repo)
return git_repo
def __init__(self, path_to_repo):
super().__init__(path_to_repo=path_to_repo, order="reverse")
if not isinstance(self._conf.get("path_to_repo"), str):
raise Exception("The path to the repo has to be of type 'string'")
self.git_repo = self.get_git_repo()
def traverse_tags(self):
for tag in self.git_repo.get_list_tags():
yield tag
def traverse_branches(self):
for branch in self.git_repo.get_list_branches():
yield branch
def traverse_commits(self, revision=None):
for commit in self.git_repo.get_list_commits(rev=revision, reverse=False):
yield commit
def traverse_tree(self):
yield from self.git_repo.get_flat_tree()
BRANCH_TEMPLATE = """\
:doc:`{name} </{doc_dirname}/branches/{slug}>`{active}
{commit}
"""
TAG_TEMPLATE = """\
:doc:`{name} </{doc_dirname}/tags/{slug}>`
{message}
"""
BRANCH_TEMPLATE_SHORT = """\
:doc:`{name} </{doc_dirname}/branches/{slug}>` {head}
"""
TAG_TEMPLATE_SHORT = """\
:doc:`{name} </{doc_dirname}/tags/{slug}>` {head}
"""
COMMIT_TEMPLATE = """\
**{subject}** :doc:`[{short_hexsha}] </{doc_dirname}/commits/{hexsha}>` — *{at}*
"""
INDEX_PAGE_TEMPLATE = """\
Git repository
==============
.. toctree::
Content <content/index>
branches/index
tags/index
commits/index
"""
BRANCHES_PAGE_TEMPLATE = """\
========
Branches
========
.. toctree::
:hidden:
{branch_links}
{branches}
"""
BRANCH_TOCTREE_LINK_TEMPLATE = """\
{name} {active} </{doc_dirname}/branches/{slug}>
"""
TAGS_PAGE_TEMPLATE = """\
====
Tags
====
.. toctree::
:hidden:
{tag_links}
{tags}
"""
TAG_TOCTREE_LINK_TEMPLATE = """\
{name} </{doc_dirname}/tags/{slug}>
"""
COMMITS_PAGE_TEMPLATE = """\
=======
Commits
=======
.. toctree::
:glob:
:hidden:
*
.. note::
To see commits, pick a :doc:`branch </{doc_dirname}/branches/index>`
"""
COMMIT_PAGE_TEMPLATE = """\
{subject_line}
{subject}
{subject_line}
.. contents::
:depth: 1
:local:
:backlinks: top
{description}
----
Info
----
Hash
{commit_hexsha}
Date
{commit_at}
Parents
{parents}
Children
{children}
Branches
{branches}
Tags
{tags}
-------
Changes
-------
.. contents::
:depth: 1
:local:
:backlinks: top
{modifications}
"""
LINK_TO_SOURCE_TEMPLATE = """\
:doc:`View documentation </{source_dirname}/{python_path}>`
"""
FILE_PAGE_TEMPLATE = """\
{title_line}
{title}
{title_line}
.. contents::
:depth: 1
:local:
:backlinks: top
----
Info
----
Parent directory
:doc:`{dirname}{parent_old} </{doc_dirname}/content/{escaped_dirname}index>`
Last update
:ref:`{last_type} — {last_updated_at} <{path}-{last_commit_hash}>`
{new_path}
{old_path}
-----------
Last source
-----------
{documentation}
{source_code}
-------
Changes
-------
.. contents::
:depth: 1
:local:
:backlinks: top
{modifications}
"""
DIR_PAGE_TEMPLATE = """\
{title_line}
{title}
{title_line}
.. toctree::
:hidden:
{entry_links}
{parent_directory}
Content
{entries}
"""
DIR_ENTRY_FILE_TEMPLATE = """\
- :doc:`{name}{old} </{doc_dirname}/content/{escaped_path}>`
"""
DIR_ENTRY_DIR_TEMPLATE = """\
- :doc:`{name}/{old} </{doc_dirname}/content/{escaped_path}/index>`
"""
DIR_TOCTREE_FILE_TEMPLATE = """\
{name}{old} </{doc_dirname}/content/{escaped_path}>
"""
DIR_TOCTREE_DIR_TEMPLATE = """\
{name}/{old} </{doc_dirname}/content/{escaped_path}/index>
"""
DESCRIPTION_TEMPLATE = """\
-----------
Description
-----------
.. include:: {description_path}
{kind}
"""
MODIFICATION_FOR_PATH_IN_COMMIT_TEMPLATE = """\
{path}
{path_line}
.. note::
:doc:`View last source and history </{doc_dirname}/content/{escaped_path}>`
Type
{type}
{old_path}
Stats
+{added} -{removed}
{diff}
"""
MODIFICATION_FOR_COMMIT_IN_PATH_TEMPLATE = """\
.. _{current_path}-{commit_hash}:
{commit_subject}
{commit_subject_line}
Commit
Hash
:doc:`{commit_hash} </{doc_dirname}/commits/{commit_hash}>`
Date
{commit_at}
Type
{type}
{old_path}
{new_path}
Stats
+{added} -{removed}
{diff}
"""
MODIFICATION_DIFF_TEMPLATE = """\
.. code-block:: diff
{diff}
"""
SOURCE_CODE_TEMPLATE = """\
.. code-block::
:linenos:
{source_code}
"""
BRANCH_PAGE_TEMPLATE = """\
{name_line}
{name}
{name_line}
{active}
{commits}
"""
BRANCH_IS_ACTIVE_TEMPLATE = """\
.. NOTE::
This is the active branch
"""
TAG_PAGE_TEMPLATE = """\
{name_line}
{name}
{name_line}
{message}
{commits}
"""
OTHER_PATH_TEMPLATE = """\
{keyword} path
:doc:`{path} </{doc_dirname}/content/{escaped_path}>`
"""
def format_date(dt):
return dt.strftime("%Y-%m-%d %H:%M:%S %z")
def split_commit_message(message):
parts = message.split("\n", 1)
return [parts[0].strip(), parts[1].strip() if len(parts) > 1 else ""]
def short_hexsha(hexsha):
return str(hexsha)[:8]
def indent(text, prefix):
return "\n".join(prefix + line for line in text.splitlines())
def render_tag(tag):
try:
message = escape_subject(split_commit_message(tag.tag.message)[0])
except AttributeError:
message = "(no message)"
return TAG_TEMPLATE.format(
name=tag.name,
slug=slugify(tag.name),
commit=render_commit(tag.commit),
doc_dirname=DOC_DIRNAME,
message="**{message}** — *{at}*".format(
message=message or "",
at=format_date(
from_timestamp(tag.tag.tagged_date, tag.tag.tagger_tz_offset)
)
if hasattr(tag.tag, "tagged_date")
else "(no date)",
),
)
def render_branch(branch, active_branch_name):
return BRANCH_TEMPLATE.format(
name=branch.name,
slug=slugify(branch.name),
commit=render_commit(branch.commit),
doc_dirname=DOC_DIRNAME,
active=" [ACTIVE BRANCH]" if branch.name == active_branch_name else "",
)
def render_branch_short(name, is_head):
if (name, is_head) not in render_branch_short.cache:
render_branch_short.cache[(name, is_head)] = BRANCH_TEMPLATE_SHORT.format(
name=name,
slug=slugify(name),
doc_dirname=DOC_DIRNAME,
head=" (head)" if is_head else "",
)
return render_branch_short.cache[(name, is_head)]
render_branch_short.cache = {}
def render_tag_short(name, is_head):
if (name, is_head) not in render_tag_short.cache:
render_tag_short.cache[(name, is_head)] = TAG_TEMPLATE_SHORT.format(
name=name,
slug=slugify(name),
doc_dirname=DOC_DIRNAME,
head=" (head)" if is_head else "",
)
return render_tag_short.cache[(name, is_head)]
render_tag_short.cache = {}
def render_commit(commit):
if commit.hexsha not in render_commit.cache:
render_commit.cache[commit.hexsha] = COMMIT_TEMPLATE.format(
at=format_date(commit.committed_datetime),
subject=escape_subject(split_commit_message(commit.message)[0]),
hexsha=commit.hexsha,
short_hexsha=short_hexsha(commit.hexsha),
doc_dirname=DOC_DIRNAME,
)
return render_commit.cache[commit.hexsha]
render_commit.cache = {}
def render_index_pages(repo):
return {"index.rst": INDEX_PAGE_TEMPLATE.format(doc_dirname=DOC_DIRNAME)}
def render_branches_pages(branches, active_branch_name):
rendered_branches = []
branch_links = []
for branch in branches:
rendered_branches.append(render_branch(branch, active_branch_name).strip())
branch_links.append(
BRANCH_TOCTREE_LINK_TEMPLATE.format(
doc_dirname=DOC_DIRNAME,
name=branch.name,
slug=slugify(branch.name),
active=" [ACTIVE]" if branch.name == active_branch_name else "",
).strip()
)
return {
"branches/index.rst": BRANCHES_PAGE_TEMPLATE.format(
branches="\n\n".join(rendered_branches),
branch_links=indent("\n".join(branch_links), " "),
)
}
def render_tags_pages(tags):
rendered_tags = []
tag_links = []
for tag in tags:
rendered_tags.append(render_tag(tag).strip())
tag_links.append(
TAG_TOCTREE_LINK_TEMPLATE.format(
doc_dirname=DOC_DIRNAME, name=tag.name, slug=slugify(tag.name)
).strip()
)
return {
"tags/index.rst": TAGS_PAGE_TEMPLATE.format(
tags="\n\n".join(rendered_tags),
tag_links=indent("\n".join(tag_links), " "),
)
}
def render_commits_pages(repo):
return {"commits/index.rst": COMMITS_PAGE_TEMPLATE.format(doc_dirname=DOC_DIRNAME)}
def render_branch_pages(branch, commits, active_branch_name):
commits = "\n".join(render_commit(commit).strip() for commit in commits)
return {
f"branches/{slugify(branch.name)}.rst": BRANCH_PAGE_TEMPLATE.format(
name=branch.name,
name_line="=" * len(branch.name),
commits=indent(commits, "- "),
active=BRANCH_IS_ACTIVE_TEMPLATE
if branch.name == active_branch_name
else "",
)
}
def render_tag_pages(tag, commits):
commits = "\n".join(render_commit(commit).strip() for commit in commits)
try:
message = tag.tag.message.strip()
except AttributeError:
message = "(no message)"
return {
f"tags/{slugify(tag.name)}.rst": TAG_PAGE_TEMPLATE.format(
name=tag.name,
name_line="=" * len(tag.name),
commits=indent(commits, "- "),
message=("::\n\n" + indent(message, " ")) if message else "",
)
}
def render_commit_pages(commit, children, branches, tags):
subject, description = split_commit_message(commit.msg)
subject = escape_subject(subject)
parents = "\n".join(
render_commit(parent).strip() for parent in commit._c_object.parents
)
children = "\n".join(render_commit(child._c_object).strip() for child in children)
branches = "\n".join(
render_branch_short(branch.name, commit.hash == branch.commit.hexsha).strip()
for branch in branches
)
tags = " • ".join(
render_tag_short(tag.name, commit.hash == tag.commit.hexsha).strip()
for tag in tags
)
modifications = "\n\n".join(
render_modification_for_path_in_commit(modification).strip()
for modification in commit.modifications
)
return {
f"commits/{commit.hash}.rst": COMMIT_PAGE_TEMPLATE.format(
subject=subject,
subject_line="=" * len(subject),
description=render_commit_description(commit, description),
commit_hexsha=commit.hash,
commit_at=format_date(commit.committer_date),
parents=indent(parents, " - ") if parents else " (No parents)",
children=indent(children, " - ") if children else " (No children)",
branches=indent(branches, " - ") if branches else " (No branches)",
tags=indent(tags, " ") if tags else " (No tags)",
modifications=modifications,
),
f"commits/descriptions/{commit.hash}": description,
}
def find_last_source_code(path, change, changes_by_file):
commit, modification, parent_change = change
if modification.source_code or modification.added or modification.removed:
return modification.source_code
if parent_change:
return find_last_source_code(path, parent_change, changes_by_file)
if (
modification.change_type == ModificationType.RENAME
and modification.old_path
and modification.old_path != modification.new_path
):
return find_last_source_code(
modification.old_path,
changes_by_file[modification.old_path][0],
changes_by_file,
)
return None
def render_file_pages(path, changes_by_file, current_tree):
last_change = changes_by_file[path][0]
changes = [change for change in changes_by_file[path] if not change[0].merge]
modifications = "\n\n".join(
"\n"
+ render_modification_for_commit_in_path(modification, commit, path).strip()
for commit, modification, *__ in changes
)
last_commit, last_modification = changes[0][:2]
first_commit, first_modification = changes[-1][:2]
basename = os.path.basename(path)
dirname = os.path.dirname(path)
suffixed_dirname = dirname + "/"
title = basename
if not path_in_tree(path, current_tree):
title += REMOVED
source_code = last_change[1].source_code or find_last_source_code(
path, last_change, changes_by_file
)
documentation = ""
if path.endswith(".py"):
parts = path[:-3].split("/")
if parts[-1] == "__init__":
parts.pop()
python_path = ".".join(parts)
if os.path.exists(os.path.join(SOURCE_BASE_PATH, python_path + ".rst")):
documentation = LINK_TO_SOURCE_TEMPLATE.format(
python_path=python_path, source_dirname=SOURCE_DIRNAME
)
return {
f"content/{escape_path(path)}.rst": FILE_PAGE_TEMPLATE.format(
path=path,
title=title,
title_line="=" * len(title),
dirname=suffixed_dirname,
escaped_dirname=escape_path(suffixed_dirname),
modifications=modifications,
source_code=SOURCE_CODE_TEMPLATE.format(
source_code=indent(source_code, " ")
)
if source_code
else "(No source code)",
last_type=MODIFICATION_TYPES[last_modification.change_type.name],
last_updated_at=format_date(last_commit.committer_date),
last_commit_hash=last_commit.hash,
doc_dirname=DOC_DIRNAME,
old_path=render_old_path(
first_modification.old_path, DOC_DIRNAME, keyword="Previous"
)
if first_modification.old_path and first_modification.old_path != path
else "",
new_path=render_new_path(last_modification.new_path, DOC_DIRNAME)
if last_modification.new_path and last_modification.new_path != path
else "",
documentation=documentation,
parent_old="" if path_in_tree(dirname, current_tree) else REMOVED,
)
}
def render_dir_pages(path, entries, current_tree):
is_removed = not path_in_tree(path, current_tree)
rendered_entries = []
entry_links = []
for entry, is_dir in sorted(
entries, key=lambda entry: (not entry[1], entry[0].lower())
):
rendered_entry = render_dir_entry(entry, is_dir, path, current_tree, is_removed)
if rendered_entry:
rendered_entries.append(rendered_entry.strip())
entry_path = os.path.join(path, entry)
entry_links.append(
(DIR_TOCTREE_DIR_TEMPLATE if is_dir else DIR_TOCTREE_FILE_TEMPLATE)
.format(
doc_dirname=DOC_DIRNAME,
name=entry,
escaped_path=escape_path(entry_path),
old="" if path_in_tree(entry_path, current_tree) else REMOVED,
)
.strip()
)
basename = os.path.basename(path)
title = (basename + "/") if basename else "`/`"
if is_removed:
title += REMOVED
dirname = os.path.dirname(path)
suffixed_dirname = dirname + "/"
return {
f"content/{escape_path(path)}/index.rst": DIR_PAGE_TEMPLATE.format(
title=title,
title_line="=" * len(title),
parent_directory="Parent directory\n :doc:`{dirname}{old} </{doc_dirname}/content/{escaped_dirname}index>`".format(
dirname=suffixed_dirname,
escaped_dirname=escape_path(suffixed_dirname),
doc_dirname=DOC_DIRNAME,
old="" if path_in_tree(dirname, current_tree) else REMOVED,
)
if path
else "",
entries=indent("\n".join(rendered_entries), " "),
entry_links=indent("\n".join(entry_links), " "),
)
}
def render_dir_entry(name, is_dir, parent_dir, current_tree, include_removed):
path = os.path.join(parent_dir, name)
is_removed = not path_in_tree(path, current_tree)
if is_removed and not include_removed:
return None
return (DIR_ENTRY_DIR_TEMPLATE if is_dir else DIR_ENTRY_FILE_TEMPLATE).format(
name=name,
escaped_path=escape_path(path),
doc_dirname=DOC_DIRNAME,
old=REMOVED if is_removed else "",
)
def render_commit_description(commit, description):
if not description:
return ""
kind = ""
if list(
rstcheck.check(
description, f"/{DOC_DIRNAME}/commits/descriptions/{commit.hash}"
)
):
kind = " :literal:\n"
return DESCRIPTION_TEMPLATE.format(
description_path=f"descriptions/{commit.hash}", kind=kind
)
def get_modification_paths(modification):
path = modification.new_path or modification.old_path
old_path = (
modification.old_path
if modification.new_path is not None
and modification.old_path is not None
and modification.new_path != modification.old_path
else None
)
return path, old_path
def _render_changed_path(path, dirname, keyword):
return (
OTHER_PATH_TEMPLATE.format(
doc_dirname=dirname,
path=path,
keyword=keyword,
escaped_path=escape_path(path),
)
if path
else ""
)
render_old_path = partial(_render_changed_path, keyword="Old")
render_new_path = partial(_render_changed_path, keyword="New")
def render_modification_for_path_in_commit(modification):
path, old_path = get_modification_paths(modification)
return MODIFICATION_FOR_PATH_IN_COMMIT_TEMPLATE.format(
path=path,
path_line="=" * len(path),
escaped_path=escape_path(path),
type=MODIFICATION_TYPES[modification.change_type.name],
old_path=render_old_path(old_path, DOC_DIRNAME),
added=modification.added or 0,
removed=modification.removed or 0,
diff=MODIFICATION_DIFF_TEMPLATE.format(diff=indent(modification.diff, " "))
if modification.diff
else "",
doc_dirname=DOC_DIRNAME,
)
def render_modification_for_commit_in_path(modification, commit, current_path):
path, old_path = get_modification_paths(modification)
subject = escape_subject(split_commit_message(commit.msg)[0])
return MODIFICATION_FOR_COMMIT_IN_PATH_TEMPLATE.format(
current_path=current_path,
commit_subject=subject,
commit_subject_line="=" * len(subject),
commit_hash=commit.hash,
commit_at=format_date(commit.committer_date),
type=MODIFICATION_TYPES[modification.change_type.name],
old_path=render_old_path(old_path, DOC_DIRNAME)
if old_path and old_path != current_path
else "",
new_path=render_new_path(path, DOC_DIRNAME) if path != current_path else "",
added=modification.added or 0,
removed=modification.removed or 0,
diff=MODIFICATION_DIFF_TEMPLATE.format(diff=indent(modification.diff, " "))
if modification.diff
else "",
doc_dirname=DOC_DIRNAME,
)
def render_to_file(content, name, basepath=BASEPATH):
path = os.path.join(basepath, name)
dir = os.path.dirname(path)
if dir not in render_to_file.dirs_ok:
os.makedirs(dir, exist_ok=True)
render_to_file.dirs_ok.add(dir)
with open(path, "w") as fd:
fd.write(content)
render_to_file.dirs_ok = set()
def render_to_files(rendered_pages, basepath=BASEPATH):
for page_name, content in rendered_pages.items():
if content:
render_to_file(content, page_name, basepath)
def render(location, basepath=BASEPATH, clean=True):
if clean:
shutil.rmtree(BASEPATH, ignore_errors=True)
print(f"\nGit to Sphinx: {location}...\n")
print("Reading repository...", end="")
repo = RepositoryMining(location)
print("\rReading repository [ok]")
print("Rendering indexes:")
print(" - branches...", end="")
branches = list(repo.traverse_branches())
render_to_files(
render_branches_pages(branches, repo.git_repo._conf.get("main_branch")),
basepath=basepath,
)
print("\r - branches [ok]")
print(" - tags...", end="")
tags = list(repo.traverse_tags())
render_to_files(render_tags_pages(tags), basepath=basepath)
print("\r - tags [ok]")
print(" - commits...", end="")
render_to_files(render_commits_pages(repo), basepath=basepath)
print("\r - commits [ok]")
print(" - main...", end="")
render_to_files(render_index_pages(repo), basepath=basepath)
print("\r - main [ok]")
print("Rendering branches:")
commits_branches = defaultdict(list)
for branch in branches:
print(f" - {branch.name}...", end="")
commits = [branch.commit] + list(branch.commit.iter_parents())
render_to_files(
render_branch_pages(
branch, commits, repo.git_repo._conf.get("main_branch")
),
basepath=basepath,
)
for commit in commits:
commits_branches[commit.hexsha].append(branch)
print(f"\r - {branch.name} [ok]")
print("Rendering tags:")
commits_tags = defaultdict(list)
for tag in tags:
print(f" - {tag.name}...", end="")
commits = [tag.commit] + list(tag.commit.iter_parents())
render_to_files(render_tag_pages(tag, commits=commits), basepath=basepath)
for commit in commits:
commits_tags[commit.hexsha].append(tag)
print(f"\r - {tag.name} [ok]")
print("Building commits trees...", end="")
children = defaultdict(list)
revisions = branches + tags
nb_revisions = len(revisions)
commits = {}
for index, revision in enumerate(revisions, 1):
print(f"\rBuilding commits trees [{index}/{nb_revisions}]", end="")
rev_commits = list(repo.traverse_commits(revision=revision.name))
for commit in rev_commits:
if commit.hash in commits:
break
commits[commit.hash] = commit
for parent_hash in commit.parents:
if commit.hash in children[parent_hash]:
continue
children[parent_hash].append(commit.hash)
print("")
print("Rendering commits...", end="")
changes_by_file = defaultdict(list)
nb_commits = len(commits)
for index, (__, commit) in enumerate(commits.items(), 1):
print(f"\rRendering commits [{index}/{nb_commits}]", end="")
if (commit.hash not in commits_branches) and (commit.hash not in commits_tags):
# ignore commits not in branches or tags: they won't be rendered anywhere
continue
render_to_files(
render_commit_pages(
commit,
children=[commits[hash] for hash in children[commit.hash]],
branches=commits_branches.get(commit.hash) or [],
tags=commits_tags.get(commit.hash) or [],
),
basepath=basepath,
)
for modification in commit.modifications:
if modification.new_path:
changes_by_file[modification.new_path].append(
[commit, modification, None]
)
if modification.old_path and modification.old_path != modification.new_path:
changes_by_file[modification.old_path].append(
[commit, modification, None]
)
# link changes to their parent
for path, changes in changes_by_file.items():
for index, change in enumerate(changes[:-1]):
change[2] = changes[index + 1]
print("")
print("Building content tree...", end="")
current_tree = {path: node for node, path in repo.traverse_tree()}
print("\rBuilding content tree [ok]")
print("Rendering files...", end="")
nb_files = len(changes_by_file)
dirs = defaultdict(set)
for index, path in enumerate(sorted(changes_by_file), 1):
print(f"\rRendering files [{index}/{nb_files}]", end="")
current, is_dir = path, False
while True:
dirname, basename = os.path.dirname(current), os.path.basename(current)
dirs[dirname].add((basename, is_dir))
if dirname:
current = dirname
is_dir = True
else:
break
render_to_files(
render_file_pages(path, changes_by_file, current_tree), basepath=basepath
)
print("")
print("Rendering dirs...", end="")
nb_dirs = len(dirs)
for index, dir in enumerate(sorted(dirs), 1):
print(f"\rRendering dirs [{index}/{nb_dirs}]", end="")
render_to_files(
render_dir_pages(dir, dirs[dir], current_tree), basepath=basepath
)
print(f"\n\nGit to Sphinx: {location} [ok]\n")
if __name__ == "__main__":
assert len(sys.argv) > 1 and sys.argv[1], "Missing location"
render(sys.argv[1])
|
Changes¶
docs(source): Make links between python files in source and git¶
- Commit
- Hash
- Date
2020-09-25 23:40:13 +0200
- Type
Modified
- Stats
+21 -2
@@ -22,7 +22,10 @@ from pydriller.git_repository import GitRepository as GitRepositoryBase
DOC_DIRNAME = "git"
-BASEPATH = os.path.join(os.path.dirname(__file__), DOC_DIRNAME)
+SOURCE_DIRNAME = "source"
+DIRNAME = os.path.dirname(__file__)
+BASEPATH = os.path.join(DIRNAME, DOC_DIRNAME)
+SOURCE_BASE_PATH = os.path.join(DIRNAME, SOURCE_DIRNAME)
REMOVED = " (removed)"
@@ -349,6 +352,10 @@ Changes
"""
+LINK_TO_SOURCE_TEMPLATE = """\
+:doc:`View documentation </{source_dirname}/{python_path}>`
+"""
+
FILE_PAGE_TEMPLATE = """\
{title_line}
{title}
@@ -374,7 +381,7 @@ Last update
-----------
Last source
-----------
-
+{documentation}
{source_code}
-------
@@ -763,6 +770,17 @@ def render_file_pages(path, changes_by_file, current_tree):
source_code = last_change[1].source_code or find_last_source_code(
path, last_change, changes_by_file
)
+ documentation = ""
+ if path.endswith(".py"):
+ parts = path[:-3].split("/")
+ if parts[-1] == "__init__":
+ parts.pop()
+ python_path = ".".join(parts)
+ if os.path.exists(os.path.join(SOURCE_BASE_PATH, python_path + ".rst")):
+ documentation = LINK_TO_SOURCE_TEMPLATE.format(
+ python_path=python_path, source_dirname=SOURCE_DIRNAME
+ )
+
return {
f"content/{escape_path(path)}.rst": FILE_PAGE_TEMPLATE.format(
path=path,
@@ -788,6 +806,7 @@ def render_file_pages(path, changes_by_file, current_tree):
new_path=render_new_path(last_modification.new_path, DOC_DIRNAME)
if last_modification.new_path and last_modification.new_path != path
else "",
+ documentation=documentation,
parent_old="" if path_in_tree(dirname, current_tree) else REMOVED,
)
}
docs(git): Only update remote branches if asked¶
- Commit
- Hash
- Date
2020-09-25 23:37:37 +0200
- Type
Modified
- Stats
+42 -35
@@ -1,5 +1,9 @@
#!/usr/bin/env python
+# Set env `GIT_TO_SPHINX_UPDATE_BRANCHES` to other than empty string to update the remote branches
+# Careful: in dev environment it will reset all your local branches if they diverged from the
+# remove ones
+
import os
import re
import shutil
@@ -144,42 +148,45 @@ class RepositoryMining(RepositoryMiningBase):
# we need to fetch all branches:
repo = git_repo.repo
- # get remote branches not fetched yet
- existing_branches = {
- branch.name: branch.commit.hexsha for branch in repo.branches
- }
- remote_branches = {}
- for ref_info in repo.remote("origin").fetch():
- local_ref_name = ref_info.name.split("/", 1)[1]
- if ref_info.commit.hexsha != existing_branches.get(local_ref_name):
- remote_branches[local_ref_name] = ref_info.name
-
- if remote_branches:
- # save the current head
- head_detached = repo.head.is_detached
- if head_detached:
- current_ref = repo.head.commit
- else:
- current_ref = repo.head.ref
-
- # stash existing updates if needed
- with override_environ(**GIT_ENVIRON):
- stashed = "No local changes to save" not in repo.git.stash("save", "-u")
-
- # fetch remote branches not fetched yet
- for local_branch_name, remote_branch_name in remote_branches.items():
- repo.git.checkout("-B", local_branch_name, remote_branch_name)
-
- # restore previous head
- if head_detached:
- repo.git.checkout(current_ref.hexsha)
- else:
- current_ref.checkout()
-
- # and restore previous updates
- if stashed:
+ if os.environ.get("GIT_TO_SPHINX_UPDATE_BRANCHES"):
+ # get remote branches not fetched yet
+ existing_branches = {
+ branch.name: branch.commit.hexsha for branch in repo.branches
+ }
+ remote_branches = {}
+ for ref_info in repo.remote("origin").fetch():
+ local_ref_name = ref_info.name.split("/", 1)[1]
+ if ref_info.commit.hexsha != existing_branches.get(local_ref_name):
+ remote_branches[local_ref_name] = ref_info.name
+
+ if remote_branches:
+ # save the current head
+ head_detached = repo.head.is_detached
+ if head_detached:
+ current_ref = repo.head.commit
+ else:
+ current_ref = repo.head.ref
+
+ # stash existing updates if needed
with override_environ(**GIT_ENVIRON):
- repo.git.stash("pop")
+ stashed = "No local changes to save" not in repo.git.stash(
+ "save", "-u"
+ )
+
+ # fetch remote branches not fetched yet
+ for local_branch_name, remote_branch_name in remote_branches.items():
+ repo.git.checkout("-B", local_branch_name, remote_branch_name)
+
+ # restore previous head
+ if head_detached:
+ repo.git.checkout(current_ref.hexsha)
+ else:
+ current_ref.checkout()
+
+ # and restore previous updates
+ if stashed:
+ with override_environ(**GIT_ENVIRON):
+ repo.git.stash("pop")
# get the branch from the head now that we are sure we have all branches
git_repo._discover_main_branch(repo)
docs(git): Show source of renamed files¶
- Commit
- Hash
- Date
2020-09-25 23:37:36 +0200
- Type
Modified
- Stats
+50 -19
@@ -13,6 +13,7 @@ import rstcheck
from cached_property import cached_property
from git.objects.util import from_timestamp
from pydriller import RepositoryMining as RepositoryMiningBase
+from pydriller.domain.commit import ModificationType
from pydriller.git_repository import GitRepository as GitRepositoryBase
@@ -363,9 +364,9 @@ Last update
{new_path}
{old_path}
-------
-Source
-------
+-----------
+Last source
+-----------
{source_code}
@@ -717,25 +718,44 @@ def render_commit_pages(commit, children, branches, tags):
}
-def render_file_pages(path, commits_and_modifications, current_tree):
- commits_and_modifications = [
- (commit, modification)
- for commit, modification in commits_and_modifications
- if not commit.merge
- ]
+def find_last_source_code(path, change, changes_by_file):
+ commit, modification, parent_change = change
+ if modification.source_code or modification.added or modification.removed:
+ return modification.source_code
+ if parent_change:
+ return find_last_source_code(path, parent_change, changes_by_file)
+ if (
+ modification.change_type == ModificationType.RENAME
+ and modification.old_path
+ and modification.old_path != modification.new_path
+ ):
+ return find_last_source_code(
+ modification.old_path,
+ changes_by_file[modification.old_path][0],
+ changes_by_file,
+ )
+ return None
+
+
+def render_file_pages(path, changes_by_file, current_tree):
+ last_change = changes_by_file[path][0]
+ changes = [change for change in changes_by_file[path] if not change[0].merge]
modifications = "\n\n".join(
"\n"
+ render_modification_for_commit_in_path(modification, commit, path).strip()
- for commit, modification in commits_and_modifications
+ for commit, modification, *__ in changes
)
- last_commit, last_modification = commits_and_modifications[0]
- first_commit, first_modification = commits_and_modifications[-1]
+ last_commit, last_modification = changes[0][:2]
+ first_commit, first_modification = changes[-1][:2]
basename = os.path.basename(path)
dirname = os.path.dirname(path)
suffixed_dirname = dirname + "/"
title = basename
if not path_in_tree(path, current_tree):
title += REMOVED
+ source_code = last_change[1].source_code or find_last_source_code(
+ path, last_change, changes_by_file
+ )
return {
f"content/{escape_path(path)}.rst": FILE_PAGE_TEMPLATE.format(
path=path,
@@ -745,9 +765,9 @@ def render_file_pages(path, commits_and_modifications, current_tree):
escaped_dirname=escape_path(suffixed_dirname),
modifications=modifications,
source_code=SOURCE_CODE_TEMPLATE.format(
- source_code=indent(last_modification.source_code, " ")
+ source_code=indent(source_code, " ")
)
- if last_modification.source_code
+ if source_code
else "(No source code)",
last_type=MODIFICATION_TYPES[last_modification.change_type.name],
last_updated_at=format_date(last_commit.committer_date),
@@ -1003,7 +1023,7 @@ def render(location, basepath=BASEPATH, clean=True):
print("")
print("Rendering commits...", end="")
- commits_by_file = defaultdict(list)
+ changes_by_file = defaultdict(list)
nb_commits = len(commits)
for index, (__, commit) in enumerate(commits.items(), 1):
print(f"\rRendering commits [{index}/{nb_commits}]", end="")
@@ -1021,9 +1041,19 @@ def render(location, basepath=BASEPATH, clean=True):
)
for modification in commit.modifications:
if modification.new_path:
- commits_by_file[modification.new_path].append((commit, modification))
+ changes_by_file[modification.new_path].append(
+ [commit, modification, None]
+ )
if modification.old_path and modification.old_path != modification.new_path:
- commits_by_file[modification.old_path].append((commit, modification))
+ changes_by_file[modification.old_path].append(
+ [commit, modification, None]
+ )
+
+ # link changes to their parent
+ for path, changes in changes_by_file.items():
+ for index, change in enumerate(changes[:-1]):
+ change[2] = changes[index + 1]
+
print("")
print("Building content tree...", end="")
@@ -1031,9 +1061,9 @@ def render(location, basepath=BASEPATH, clean=True):
print("\rBuilding content tree [ok]")
print("Rendering files...", end="")
- nb_files = len(commits_by_file)
+ nb_files = len(changes_by_file)
dirs = defaultdict(set)
- for index, path in enumerate(sorted(commits_by_file), 1):
+ for index, path in enumerate(sorted(changes_by_file), 1):
print(f"\rRendering files [{index}/{nb_files}]", end="")
current, is_dir = path, False
@@ -1047,8 +1077,7 @@ def render(location, basepath=BASEPATH, clean=True):
break
render_to_files(
- render_file_pages(path, commits_by_file[path], current_tree),
- basepath=basepath,
+ render_file_pages(path, changes_by_file, current_tree), basepath=basepath
)
print("")
chore: Fix breaking changes from updated dependencies¶
- Commit
- Hash
- Date
2020-09-25 22:54:00 +0200
- Type
Modified
- Stats
+20 -27
@@ -96,7 +96,7 @@ class GitRepository(GitRepositoryBase):
if repo.head.is_detached:
for branch in repo.branches:
if branch.commit.hexsha == repo.head.commit.hexsha:
- self.main_branch = branch.name
+ self._conf.set_value("main_branch", branch.name)
else:
super()._discover_main_branch(repo)
@@ -104,25 +104,22 @@ class GitRepository(GitRepositoryBase):
def repo(self):
return super().repo
- def get_list_tags(self, reverse_order=False):
+ def get_list_tags(self):
for tag in sorted(
self.repo.tags,
key=lambda t: t.commit.committed_datetime,
- reverse=not reverse_order,
+ reverse=True,
):
yield tag
- def get_list_branches(self, reverse_order=False):
+ def get_list_branches(self):
for branch in sorted(
self.repo.branches,
key=lambda t: t.commit.committed_datetime,
- reverse=not reverse_order,
+ reverse=True,
):
yield branch
- def get_list_commits(self, branch=None, reverse_order=False):
- return super().get_list_commits(branch=branch, reverse_order=reverse_order)
-
def get_list_tree(self, node, parent_path=""):
for child in node:
path = os.path.join(parent_path, child.name)
@@ -135,17 +132,11 @@ class GitRepository(GitRepositoryBase):
class RepositoryMining(RepositoryMiningBase):
- def _sanity_check_repos(self, path_to_repo):
- if not isinstance(path_to_repo, str):
- raise Exception("The path to the repo has to be of type 'string'")
-
def get_git_repo(self):
- path_repo = self._path_to_repo[0]
+ path_repo = self._conf.get("path_to_repos")[0]
- if self._isremote(path_repo):
- # save in `self` to avoid premature destruction of the tmp directory
- self.tmp_folder = tempfile.TemporaryDirectory()
- path_repo = self._clone_remote_repos(self.tmp_folder.name, path_repo)
+ if self._is_remote(path_repo):
+ path_repo = self._clone_remote_repo(self._clone_folder(), path_repo)
git_repo = GitRepository(path_repo)
@@ -195,24 +186,23 @@ class RepositoryMining(RepositoryMiningBase):
return git_repo
def __init__(self, path_to_repo):
- super().__init__(path_to_repo=path_to_repo, reversed_order=True)
+ super().__init__(path_to_repo=path_to_repo, order="reverse")
+
+ if not isinstance(self._conf.get("path_to_repo"), str):
+ raise Exception("The path to the repo has to be of type 'string'")
self.git_repo = self.get_git_repo()
def traverse_tags(self):
- for tag in self.git_repo.get_list_tags(reverse_order=not self._reversed_order):
+ for tag in self.git_repo.get_list_tags():
yield tag
def traverse_branches(self):
- for branch in self.git_repo.get_list_branches(
- reverse_order=not self._reversed_order
- ):
+ for branch in self.git_repo.get_list_branches():
yield branch
def traverse_commits(self, revision=None):
- for commit in self.git_repo.get_list_commits(
- branch=revision, reverse_order=not self._reversed_order
- ):
+ for commit in self.git_repo.get_list_commits(rev=revision, reverse=False):
yield commit
def traverse_tree(self):
@@ -954,7 +944,8 @@ def render(location, basepath=BASEPATH, clean=True):
print(" - branches...", end="")
branches = list(repo.traverse_branches())
render_to_files(
- render_branches_pages(branches, repo.git_repo.main_branch), basepath=basepath
+ render_branches_pages(branches, repo.git_repo._conf.get("main_branch")),
+ basepath=basepath,
)
print("\r - branches [ok]")
print(" - tags...", end="")
@@ -974,7 +965,9 @@ def render(location, basepath=BASEPATH, clean=True):
print(f" - {branch.name}...", end="")
commits = [branch.commit] + list(branch.commit.iter_parents())
render_to_files(
- render_branch_pages(branch, commits, repo.git_repo.main_branch),
+ render_branch_pages(
+ branch, commits, repo.git_repo._conf.get("main_branch")
+ ),
basepath=basepath,
)
for commit in commits:
docs(fix): Fix usage of pydriller in git_to_sphinx¶
- Commit
- Hash
- Date
2019-08-16 00:12:17 +0200
- Type
Modified
- Stats
+1 -1
@@ -140,7 +140,7 @@ class RepositoryMining(RepositoryMiningBase):
raise Exception("The path to the repo has to be of type 'string'")
def get_git_repo(self):
- path_repo = self._path_to_repo
+ path_repo = self._path_to_repo[0]
if self._isremote(path_repo):
# save in `self` to avoid premature destruction of the tmp directory
docs(git): Add git commits to documentation¶
- Commit
- Hash
- Date
2019-06-03 13:54:59 +0200
- Type
Added
- Stats
+1075 -0
@@ -0,0 +1,1075 @@
+#!/usr/bin/env python
+
+import os
+import re
+import shutil
+import sys
+import tempfile
+from collections import defaultdict
+from contextlib import contextmanager
+from functools import partial
+
+import rstcheck
+from cached_property import cached_property
+from git.objects.util import from_timestamp
+from pydriller import RepositoryMining as RepositoryMiningBase
+from pydriller.git_repository import GitRepository as GitRepositoryBase
+
+
+DOC_DIRNAME = "git"
+BASEPATH = os.path.join(os.path.dirname(__file__), DOC_DIRNAME)
+
+REMOVED = " (removed)"
+
+GIT_ENVIRON = {
+ "GIT_COMMITTER_NAME": "git-to-sphinx",
+ "GIT_COMMITTER_EMAIL": "git-to-sphinx@example.com",
+ "GIT_AUTHOR_NAME": "git-to-sphinx",
+ "GIT_AUTHOR_EMAIL": "git-to-sphinx@example.com",
+}
+
+
+@contextmanager
+def override_environ(**env):
+ original_env = {key: os.getenv(key) for key in env}
+ os.environ.update(env)
+ try:
+ yield
+ finally:
+ for key, value in original_env.items():
+ if value is None:
+ del os.environ[key]
+ else:
+ os.environ[key] = value
+
+
+def slugify(text):
+ text = text.lower()
+ for c in slugify.to_underscore:
+ text = text.replace(c, "_")
+ text = slugify.re_W.sub("", text).replace("_", " ")
+ return slugify.re_s.sub(" ", text).strip().replace(" ", "-")
+
+
+slugify.to_underscore = [" ", "-", ".", "/"]
+slugify.re_W = re.compile(r"\W")
+slugify.re_s = re.compile(r"\s+")
+
+
+def escape_path(path):
+ if path.endswith(".rst"):
+ path += "_"
+ return path
+
+
+def escape_subject(text):
+ for what, how in escape_subject.replacements:
+ text = text.replace(what, how)
+ return text
+
+
+escape_subject.replacements = [("*", r"\*"), ("_", r"\_")]
+
+
+def path_in_tree(path, tree, allow_root=True):
+ if allow_root and (not path or path == "/"):
+ return True
+ return path in tree
+
+
+MODIFICATION_TYPES = {
+ "ADD": "Added",
+ "COPY": "Copied",
+ "RENAME": "Renamed",
+ "DELETE": "Deleted",
+ "MODIFY": "Modified",
+ "UNKNOWN": "Unknown",
+}
+
+
+class GitRepository(GitRepositoryBase):
+ @cached_property
+ def git(self):
+ return super().git
+
+ def _discover_main_branch(self, repo):
+ if repo.head.is_detached:
+ for branch in repo.branches:
+ if branch.commit.hexsha == repo.head.commit.hexsha:
+ self.main_branch = branch.name
+ else:
+ super()._discover_main_branch(repo)
+
+ @cached_property
+ def repo(self):
+ return super().repo
+
+ def get_list_tags(self, reverse_order=False):
+ for tag in sorted(
+ self.repo.tags,
+ key=lambda t: t.commit.committed_datetime,
+ reverse=not reverse_order,
+ ):
+ yield tag
+
+ def get_list_branches(self, reverse_order=False):
+ for branch in sorted(
+ self.repo.branches,
+ key=lambda t: t.commit.committed_datetime,
+ reverse=not reverse_order,
+ ):
+ yield branch
+
+ def get_list_commits(self, branch=None, reverse_order=False):
+ return super().get_list_commits(branch=branch, reverse_order=reverse_order)
+
+ def get_list_tree(self, node, parent_path=""):
+ for child in node:
+ path = os.path.join(parent_path, child.name)
+ yield (child, path)
+ if child.type == "tree":
+ yield from self.get_list_tree(child, path)
+
+ def get_flat_tree(self):
+ yield from self.get_list_tree(self.get_head()._c_object.tree)
+
+
+class RepositoryMining(RepositoryMiningBase):
+ def _sanity_check_repos(self, path_to_repo):
+ if not isinstance(path_to_repo, str):
+ raise Exception("The path to the repo has to be of type 'string'")
+
+ def get_git_repo(self):
+ path_repo = self._path_to_repo
+
+ if self._isremote(path_repo):
+ # save in `self` to avoid premature destruction of the tmp directory
+ self.tmp_folder = tempfile.TemporaryDirectory()
+ path_repo = self._clone_remote_repos(self.tmp_folder.name, path_repo)
+
+ git_repo = GitRepository(path_repo)
+
+ # we need to fetch all branches:
+ repo = git_repo.repo
+
+ # get remote branches not fetched yet
+ existing_branches = {
+ branch.name: branch.commit.hexsha for branch in repo.branches
+ }
+ remote_branches = {}
+ for ref_info in repo.remote("origin").fetch():
+ local_ref_name = ref_info.name.split("/", 1)[1]
+ if ref_info.commit.hexsha != existing_branches.get(local_ref_name):
+ remote_branches[local_ref_name] = ref_info.name
+
+ if remote_branches:
+ # save the current head
+ head_detached = repo.head.is_detached
+ if head_detached:
+ current_ref = repo.head.commit
+ else:
+ current_ref = repo.head.ref
+
+ # stash existing updates if needed
+ with override_environ(**GIT_ENVIRON):
+ stashed = "No local changes to save" not in repo.git.stash("save", "-u")
+
+ # fetch remote branches not fetched yet
+ for local_branch_name, remote_branch_name in remote_branches.items():
+ repo.git.checkout("-B", local_branch_name, remote_branch_name)
+
+ # restore previous head
+ if head_detached:
+ repo.git.checkout(current_ref.hexsha)
+ else:
+ current_ref.checkout()
+
+ # and restore previous updates
+ if stashed:
+ with override_environ(**GIT_ENVIRON):
+ repo.git.stash("pop")
+
+ # get the branch from the head now that we are sure we have all branches
+ git_repo._discover_main_branch(repo)
+
+ return git_repo
+
+ def __init__(self, path_to_repo):
+ super().__init__(path_to_repo=path_to_repo, reversed_order=True)
+
+ self.git_repo = self.get_git_repo()
+
+ def traverse_tags(self):
+ for tag in self.git_repo.get_list_tags(reverse_order=not self._reversed_order):
+ yield tag
+
+ def traverse_branches(self):
+ for branch in self.git_repo.get_list_branches(
+ reverse_order=not self._reversed_order
+ ):
+ yield branch
+
+ def traverse_commits(self, revision=None):
+ for commit in self.git_repo.get_list_commits(
+ branch=revision, reverse_order=not self._reversed_order
+ ):
+ yield commit
+
+ def traverse_tree(self):
+ yield from self.git_repo.get_flat_tree()
+
+
+BRANCH_TEMPLATE = """\
+:doc:`{name} </{doc_dirname}/branches/{slug}>`{active}
+ {commit}
+"""
+
+TAG_TEMPLATE = """\
+:doc:`{name} </{doc_dirname}/tags/{slug}>`
+ {message}
+"""
+
+BRANCH_TEMPLATE_SHORT = """\
+:doc:`{name} </{doc_dirname}/branches/{slug}>` {head}
+"""
+
+TAG_TEMPLATE_SHORT = """\
+:doc:`{name} </{doc_dirname}/tags/{slug}>` {head}
+"""
+
+COMMIT_TEMPLATE = """\
+**{subject}** :doc:`[{short_hexsha}] </{doc_dirname}/commits/{hexsha}>` — *{at}*
+"""
+
+INDEX_PAGE_TEMPLATE = """\
+Git repository
+==============
+
+.. toctree::
+
+ Content <content/index>
+ branches/index
+ tags/index
+ commits/index
+
+"""
+
+BRANCHES_PAGE_TEMPLATE = """\
+========
+Branches
+========
+
+.. toctree::
+ :hidden:
+
+{branch_links}
+
+{branches}
+"""
+
+BRANCH_TOCTREE_LINK_TEMPLATE = """\
+{name} {active} </{doc_dirname}/branches/{slug}>
+"""
+
+TAGS_PAGE_TEMPLATE = """\
+====
+Tags
+====
+
+.. toctree::
+ :hidden:
+
+{tag_links}
+
+{tags}
+"""
+
+TAG_TOCTREE_LINK_TEMPLATE = """\
+{name} </{doc_dirname}/tags/{slug}>
+"""
+
+COMMITS_PAGE_TEMPLATE = """\
+=======
+Commits
+=======
+
+.. toctree::
+ :glob:
+ :hidden:
+
+ *
+
+.. note::
+
+ To see commits, pick a :doc:`branch </{doc_dirname}/branches/index>`
+"""
+
+COMMIT_PAGE_TEMPLATE = """\
+{subject_line}
+{subject}
+{subject_line}
+
+.. contents::
+ :depth: 1
+ :local:
+ :backlinks: top
+
+{description}
+
+----
+Info
+----
+
+Hash
+ {commit_hexsha}
+
+Date
+ {commit_at}
+
+Parents
+{parents}
+
+Children
+{children}
+
+Branches
+{branches}
+
+Tags
+{tags}
+
+-------
+Changes
+-------
+
+.. contents::
+ :depth: 1
+ :local:
+ :backlinks: top
+
+{modifications}
+
+"""
+
+FILE_PAGE_TEMPLATE = """\
+{title_line}
+{title}
+{title_line}
+
+.. contents::
+ :depth: 1
+ :local:
+ :backlinks: top
+
+----
+Info
+----
+
+Parent directory
+ :doc:`{dirname}{parent_old} </{doc_dirname}/content/{escaped_dirname}index>`
+
+Last update
+ :ref:`{last_type} — {last_updated_at} <{path}-{last_commit_hash}>`
+{new_path}
+{old_path}
+
+------
+Source
+------
+
+{source_code}
+
+-------
+Changes
+-------
+
+.. contents::
+ :depth: 1
+ :local:
+ :backlinks: top
+
+{modifications}
+
+"""
+
+DIR_PAGE_TEMPLATE = """\
+{title_line}
+{title}
+{title_line}
+
+.. toctree::
+ :hidden:
+
+{entry_links}
+
+{parent_directory}
+
+Content
+{entries}
+"""
+
+DIR_ENTRY_FILE_TEMPLATE = """\
+- :doc:`{name}{old} </{doc_dirname}/content/{escaped_path}>`
+"""
+
+DIR_ENTRY_DIR_TEMPLATE = """\
+- :doc:`{name}/{old} </{doc_dirname}/content/{escaped_path}/index>`
+"""
+
+DIR_TOCTREE_FILE_TEMPLATE = """\
+{name}{old} </{doc_dirname}/content/{escaped_path}>
+"""
+
+DIR_TOCTREE_DIR_TEMPLATE = """\
+{name}/{old} </{doc_dirname}/content/{escaped_path}/index>
+"""
+
+DESCRIPTION_TEMPLATE = """\
+
+-----------
+Description
+-----------
+
+.. include:: {description_path}
+{kind}
+"""
+
+MODIFICATION_FOR_PATH_IN_COMMIT_TEMPLATE = """\
+{path}
+{path_line}
+
+.. note::
+
+ :doc:`View last source and history </{doc_dirname}/content/{escaped_path}>`
+
+Type
+ {type}
+{old_path}
+Stats
+ +{added} -{removed}
+
+{diff}
+"""
+
+MODIFICATION_FOR_COMMIT_IN_PATH_TEMPLATE = """\
+
+.. _{current_path}-{commit_hash}:
+
+{commit_subject}
+{commit_subject_line}
+
+Commit
+ Hash
+ :doc:`{commit_hash} </{doc_dirname}/commits/{commit_hash}>`
+ Date
+ {commit_at}
+
+Type
+ {type}
+{old_path}
+{new_path}
+Stats
+ +{added} -{removed}
+
+{diff}
+"""
+
+MODIFICATION_DIFF_TEMPLATE = """\
+
+.. code-block:: diff
+
+{diff}
+"""
+
+SOURCE_CODE_TEMPLATE = """\
+
+.. code-block::
+ :linenos:
+
+{source_code}
+"""
+
+
+BRANCH_PAGE_TEMPLATE = """\
+{name_line}
+{name}
+{name_line}
+{active}
+
+{commits}
+"""
+
+BRANCH_IS_ACTIVE_TEMPLATE = """\
+
+.. NOTE::
+ This is the active branch
+"""
+
+TAG_PAGE_TEMPLATE = """\
+{name_line}
+{name}
+{name_line}
+
+{message}
+
+{commits}
+"""
+
+
+OTHER_PATH_TEMPLATE = """\
+{keyword} path
+ :doc:`{path} </{doc_dirname}/content/{escaped_path}>`
+"""
+
+
+def format_date(dt):
+ return dt.strftime("%Y-%m-%d %H:%M:%S %z")
+
+
+def split_commit_message(message):
+ parts = message.split("\n", 1)
+ return [parts[0].strip(), parts[1].strip() if len(parts) > 1 else ""]
+
+
+def short_hexsha(hexsha):
+ return str(hexsha)[:8]
+
+
+def indent(text, prefix):
+ return "\n".join(prefix + line for line in text.splitlines())
+
+
+def render_tag(tag):
+ try:
+ message = escape_subject(split_commit_message(tag.tag.message)[0])
+ except AttributeError:
+ message = "(no message)"
+
+ return TAG_TEMPLATE.format(
+ name=tag.name,
+ slug=slugify(tag.name),
+ commit=render_commit(tag.commit),
+ doc_dirname=DOC_DIRNAME,
+ message="**{message}** — *{at}*".format(
+ message=message or "",
+ at=format_date(
+ from_timestamp(tag.tag.tagged_date, tag.tag.tagger_tz_offset)
+ )
+ if hasattr(tag.tag, "tagged_date")
+ else "(no date)",
+ ),
+ )
+
+
+def render_branch(branch, active_branch_name):
+ return BRANCH_TEMPLATE.format(
+ name=branch.name,
+ slug=slugify(branch.name),
+ commit=render_commit(branch.commit),
+ doc_dirname=DOC_DIRNAME,
+ active=" [ACTIVE BRANCH]" if branch.name == active_branch_name else "",
+ )
+
+
+def render_branch_short(name, is_head):
+ if (name, is_head) not in render_branch_short.cache:
+ render_branch_short.cache[(name, is_head)] = BRANCH_TEMPLATE_SHORT.format(
+ name=name,
+ slug=slugify(name),
+ doc_dirname=DOC_DIRNAME,
+ head=" (head)" if is_head else "",
+ )
+ return render_branch_short.cache[(name, is_head)]
+
+
+render_branch_short.cache = {}
+
+
+def render_tag_short(name, is_head):
+ if (name, is_head) not in render_tag_short.cache:
+ render_tag_short.cache[(name, is_head)] = TAG_TEMPLATE_SHORT.format(
+ name=name,
+ slug=slugify(name),
+ doc_dirname=DOC_DIRNAME,
+ head=" (head)" if is_head else "",
+ )
+ return render_tag_short.cache[(name, is_head)]
+
+
+render_tag_short.cache = {}
+
+
+def render_commit(commit):
+ if commit.hexsha not in render_commit.cache:
+ render_commit.cache[commit.hexsha] = COMMIT_TEMPLATE.format(
+ at=format_date(commit.committed_datetime),
+ subject=escape_subject(split_commit_message(commit.message)[0]),
+ hexsha=commit.hexsha,
+ short_hexsha=short_hexsha(commit.hexsha),
+ doc_dirname=DOC_DIRNAME,
+ )
+ return render_commit.cache[commit.hexsha]
+
+
+render_commit.cache = {}
+
+
+def render_index_pages(repo):
+ return {"index.rst": INDEX_PAGE_TEMPLATE.format(doc_dirname=DOC_DIRNAME)}
+
+
+def render_branches_pages(branches, active_branch_name):
+ rendered_branches = []
+ branch_links = []
+ for branch in branches:
+ rendered_branches.append(render_branch(branch, active_branch_name).strip())
+ branch_links.append(
+ BRANCH_TOCTREE_LINK_TEMPLATE.format(
+ doc_dirname=DOC_DIRNAME,
+ name=branch.name,
+ slug=slugify(branch.name),
+ active=" [ACTIVE]" if branch.name == active_branch_name else "",
+ ).strip()
+ )
+ return {
+ "branches/index.rst": BRANCHES_PAGE_TEMPLATE.format(
+ branches="\n\n".join(rendered_branches),
+ branch_links=indent("\n".join(branch_links), " "),
+ )
+ }
+
+
+def render_tags_pages(tags):
+ rendered_tags = []
+ tag_links = []
+ for tag in tags:
+ rendered_tags.append(render_tag(tag).strip())
+ tag_links.append(
+ TAG_TOCTREE_LINK_TEMPLATE.format(
+ doc_dirname=DOC_DIRNAME, name=tag.name, slug=slugify(tag.name)
+ ).strip()
+ )
+ return {
+ "tags/index.rst": TAGS_PAGE_TEMPLATE.format(
+ tags="\n\n".join(rendered_tags),
+ tag_links=indent("\n".join(tag_links), " "),
+ )
+ }
+
+
+def render_commits_pages(repo):
+ return {"commits/index.rst": COMMITS_PAGE_TEMPLATE.format(doc_dirname=DOC_DIRNAME)}
+
+
+def render_branch_pages(branch, commits, active_branch_name):
+ commits = "\n".join(render_commit(commit).strip() for commit in commits)
+ return {
+ f"branches/{slugify(branch.name)}.rst": BRANCH_PAGE_TEMPLATE.format(
+ name=branch.name,
+ name_line="=" * len(branch.name),
+ commits=indent(commits, "- "),
+ active=BRANCH_IS_ACTIVE_TEMPLATE
+ if branch.name == active_branch_name
+ else "",
+ )
+ }
+
+
+def render_tag_pages(tag, commits):
+ commits = "\n".join(render_commit(commit).strip() for commit in commits)
+ try:
+ message = tag.tag.message.strip()
+ except AttributeError:
+ message = "(no message)"
+ return {
+ f"tags/{slugify(tag.name)}.rst": TAG_PAGE_TEMPLATE.format(
+ name=tag.name,
+ name_line="=" * len(tag.name),
+ commits=indent(commits, "- "),
+ message=("::\n\n" + indent(message, " ")) if message else "",
+ )
+ }
+
+
+def render_commit_pages(commit, children, branches, tags):
+ subject, description = split_commit_message(commit.msg)
+ subject = escape_subject(subject)
+ parents = "\n".join(
+ render_commit(parent).strip() for parent in commit._c_object.parents
+ )
+ children = "\n".join(render_commit(child._c_object).strip() for child in children)
+ branches = "\n".join(
+ render_branch_short(branch.name, commit.hash == branch.commit.hexsha).strip()
+ for branch in branches
+ )
+ tags = " • ".join(
+ render_tag_short(tag.name, commit.hash == tag.commit.hexsha).strip()
+ for tag in tags
+ )
+ modifications = "\n\n".join(
+ render_modification_for_path_in_commit(modification).strip()
+ for modification in commit.modifications
+ )
+ return {
+ f"commits/{commit.hash}.rst": COMMIT_PAGE_TEMPLATE.format(
+ subject=subject,
+ subject_line="=" * len(subject),
+ description=render_commit_description(commit, description),
+ commit_hexsha=commit.hash,
+ commit_at=format_date(commit.committer_date),
+ parents=indent(parents, " - ") if parents else " (No parents)",
+ children=indent(children, " - ") if children else " (No children)",
+ branches=indent(branches, " - ") if branches else " (No branches)",
+ tags=indent(tags, " ") if tags else " (No tags)",
+ modifications=modifications,
+ ),
+ f"commits/descriptions/{commit.hash}": description,
+ }
+
+
+def render_file_pages(path, commits_and_modifications, current_tree):
+ commits_and_modifications = [
+ (commit, modification)
+ for commit, modification in commits_and_modifications
+ if not commit.merge
+ ]
+ modifications = "\n\n".join(
+ "\n"
+ + render_modification_for_commit_in_path(modification, commit, path).strip()
+ for commit, modification in commits_and_modifications
+ )
+ last_commit, last_modification = commits_and_modifications[0]
+ first_commit, first_modification = commits_and_modifications[-1]
+ basename = os.path.basename(path)
+ dirname = os.path.dirname(path)
+ suffixed_dirname = dirname + "/"
+ title = basename
+ if not path_in_tree(path, current_tree):
+ title += REMOVED
+ return {
+ f"content/{escape_path(path)}.rst": FILE_PAGE_TEMPLATE.format(
+ path=path,
+ title=title,
+ title_line="=" * len(title),
+ dirname=suffixed_dirname,
+ escaped_dirname=escape_path(suffixed_dirname),
+ modifications=modifications,
+ source_code=SOURCE_CODE_TEMPLATE.format(
+ source_code=indent(last_modification.source_code, " ")
+ )
+ if last_modification.source_code
+ else "(No source code)",
+ last_type=MODIFICATION_TYPES[last_modification.change_type.name],
+ last_updated_at=format_date(last_commit.committer_date),
+ last_commit_hash=last_commit.hash,
+ doc_dirname=DOC_DIRNAME,
+ old_path=render_old_path(
+ first_modification.old_path, DOC_DIRNAME, keyword="Previous"
+ )
+ if first_modification.old_path and first_modification.old_path != path
+ else "",
+ new_path=render_new_path(last_modification.new_path, DOC_DIRNAME)
+ if last_modification.new_path and last_modification.new_path != path
+ else "",
+ parent_old="" if path_in_tree(dirname, current_tree) else REMOVED,
+ )
+ }
+
+
+def render_dir_pages(path, entries, current_tree):
+ is_removed = not path_in_tree(path, current_tree)
+ rendered_entries = []
+ entry_links = []
+ for entry, is_dir in sorted(
+ entries, key=lambda entry: (not entry[1], entry[0].lower())
+ ):
+ rendered_entry = render_dir_entry(entry, is_dir, path, current_tree, is_removed)
+ if rendered_entry:
+ rendered_entries.append(rendered_entry.strip())
+
+ entry_path = os.path.join(path, entry)
+ entry_links.append(
+ (DIR_TOCTREE_DIR_TEMPLATE if is_dir else DIR_TOCTREE_FILE_TEMPLATE)
+ .format(
+ doc_dirname=DOC_DIRNAME,
+ name=entry,
+ escaped_path=escape_path(entry_path),
+ old="" if path_in_tree(entry_path, current_tree) else REMOVED,
+ )
+ .strip()
+ )
+ basename = os.path.basename(path)
+ title = (basename + "/") if basename else "`/`"
+ if is_removed:
+ title += REMOVED
+ dirname = os.path.dirname(path)
+ suffixed_dirname = dirname + "/"
+ return {
+ f"content/{escape_path(path)}/index.rst": DIR_PAGE_TEMPLATE.format(
+ title=title,
+ title_line="=" * len(title),
+ parent_directory="Parent directory\n :doc:`{dirname}{old} </{doc_dirname}/content/{escaped_dirname}index>`".format(
+ dirname=suffixed_dirname,
+ escaped_dirname=escape_path(suffixed_dirname),
+ doc_dirname=DOC_DIRNAME,
+ old="" if path_in_tree(dirname, current_tree) else REMOVED,
+ )
+ if path
+ else "",
+ entries=indent("\n".join(rendered_entries), " "),
+ entry_links=indent("\n".join(entry_links), " "),
+ )
+ }
+
+
+def render_dir_entry(name, is_dir, parent_dir, current_tree, include_removed):
+ path = os.path.join(parent_dir, name)
+ is_removed = not path_in_tree(path, current_tree)
+ if is_removed and not include_removed:
+ return None
+ return (DIR_ENTRY_DIR_TEMPLATE if is_dir else DIR_ENTRY_FILE_TEMPLATE).format(
+ name=name,
+ escaped_path=escape_path(path),
+ doc_dirname=DOC_DIRNAME,
+ old=REMOVED if is_removed else "",
+ )
+
+
+def render_commit_description(commit, description):
+ if not description:
+ return ""
+
+ kind = ""
+ if list(
+ rstcheck.check(
+ description, f"/{DOC_DIRNAME}/commits/descriptions/{commit.hash}"
+ )
+ ):
+ kind = " :literal:\n"
+
+ return DESCRIPTION_TEMPLATE.format(
+ description_path=f"descriptions/{commit.hash}", kind=kind
+ )
+
+
+def get_modification_paths(modification):
+ path = modification.new_path or modification.old_path
+ old_path = (
+ modification.old_path
+ if modification.new_path is not None
+ and modification.old_path is not None
+ and modification.new_path != modification.old_path
+ else None
+ )
+ return path, old_path
+
+
+def _render_changed_path(path, dirname, keyword):
+ return (
+ OTHER_PATH_TEMPLATE.format(
+ doc_dirname=dirname,
+ path=path,
+ keyword=keyword,
+ escaped_path=escape_path(path),
+ )
+ if path
+ else ""
+ )
+
+
+render_old_path = partial(_render_changed_path, keyword="Old")
+render_new_path = partial(_render_changed_path, keyword="New")
+
+
+def render_modification_for_path_in_commit(modification):
+ path, old_path = get_modification_paths(modification)
+ return MODIFICATION_FOR_PATH_IN_COMMIT_TEMPLATE.format(
+ path=path,
+ path_line="=" * len(path),
+ escaped_path=escape_path(path),
+ type=MODIFICATION_TYPES[modification.change_type.name],
+ old_path=render_old_path(old_path, DOC_DIRNAME),
+ added=modification.added or 0,
+ removed=modification.removed or 0,
+ diff=MODIFICATION_DIFF_TEMPLATE.format(diff=indent(modification.diff, " "))
+ if modification.diff
+ else "",
+ doc_dirname=DOC_DIRNAME,
+ )
+
+
+def render_modification_for_commit_in_path(modification, commit, current_path):
+ path, old_path = get_modification_paths(modification)
+ subject = escape_subject(split_commit_message(commit.msg)[0])
+ return MODIFICATION_FOR_COMMIT_IN_PATH_TEMPLATE.format(
+ current_path=current_path,
+ commit_subject=subject,
+ commit_subject_line="=" * len(subject),
+ commit_hash=commit.hash,
+ commit_at=format_date(commit.committer_date),
+ type=MODIFICATION_TYPES[modification.change_type.name],
+ old_path=render_old_path(old_path, DOC_DIRNAME)
+ if old_path and old_path != current_path
+ else "",
+ new_path=render_new_path(path, DOC_DIRNAME) if path != current_path else "",
+ added=modification.added or 0,
+ removed=modification.removed or 0,
+ diff=MODIFICATION_DIFF_TEMPLATE.format(diff=indent(modification.diff, " "))
+ if modification.diff
+ else "",
+ doc_dirname=DOC_DIRNAME,
+ )
+
+
+def render_to_file(content, name, basepath=BASEPATH):
+ path = os.path.join(basepath, name)
+ dir = os.path.dirname(path)
+ if dir not in render_to_file.dirs_ok:
+ os.makedirs(dir, exist_ok=True)
+ render_to_file.dirs_ok.add(dir)
+ with open(path, "w") as fd:
+ fd.write(content)
+
+
+render_to_file.dirs_ok = set()
+
+
+def render_to_files(rendered_pages, basepath=BASEPATH):
+ for page_name, content in rendered_pages.items():
+ if content:
+ render_to_file(content, page_name, basepath)
+
+
+def render(location, basepath=BASEPATH, clean=True):
+ if clean:
+ shutil.rmtree(BASEPATH, ignore_errors=True)
+
+ print(f"\nGit to Sphinx: {location}...\n")
+
+ print("Reading repository...", end="")
+ repo = RepositoryMining(location)
+ print("\rReading repository [ok]")
+
+ print("Rendering indexes:")
+ print(" - branches...", end="")
+ branches = list(repo.traverse_branches())
+ render_to_files(
+ render_branches_pages(branches, repo.git_repo.main_branch), basepath=basepath
+ )
+ print("\r - branches [ok]")
+ print(" - tags...", end="")
+ tags = list(repo.traverse_tags())
+ render_to_files(render_tags_pages(tags), basepath=basepath)
+ print("\r - tags [ok]")
+ print(" - commits...", end="")
+ render_to_files(render_commits_pages(repo), basepath=basepath)
+ print("\r - commits [ok]")
+ print(" - main...", end="")
+ render_to_files(render_index_pages(repo), basepath=basepath)
+ print("\r - main [ok]")
+
+ print("Rendering branches:")
+ commits_branches = defaultdict(list)
+ for branch in branches:
+ print(f" - {branch.name}...", end="")
+ commits = [branch.commit] + list(branch.commit.iter_parents())
+ render_to_files(
+ render_branch_pages(branch, commits, repo.git_repo.main_branch),
+ basepath=basepath,
+ )
+ for commit in commits:
+ commits_branches[commit.hexsha].append(branch)
+ print(f"\r - {branch.name} [ok]")
+
+ print("Rendering tags:")
+ commits_tags = defaultdict(list)
+ for tag in tags:
+ print(f" - {tag.name}...", end="")
+ commits = [tag.commit] + list(tag.commit.iter_parents())
+ render_to_files(render_tag_pages(tag, commits=commits), basepath=basepath)
+ for commit in commits:
+ commits_tags[commit.hexsha].append(tag)
+ print(f"\r - {tag.name} [ok]")
+
+ print("Building commits trees...", end="")
+ children = defaultdict(list)
+ revisions = branches + tags
+ nb_revisions = len(revisions)
+ commits = {}
+ for index, revision in enumerate(revisions, 1):
+ print(f"\rBuilding commits trees [{index}/{nb_revisions}]", end="")
+ rev_commits = list(repo.traverse_commits(revision=revision.name))
+ for commit in rev_commits:
+ if commit.hash in commits:
+ break
+ commits[commit.hash] = commit
+ for parent_hash in commit.parents:
+ if commit.hash in children[parent_hash]:
+ continue
+ children[parent_hash].append(commit.hash)
+ print("")
+
+ print("Rendering commits...", end="")
+ commits_by_file = defaultdict(list)
+ nb_commits = len(commits)
+ for index, (__, commit) in enumerate(commits.items(), 1):
+ print(f"\rRendering commits [{index}/{nb_commits}]", end="")
+ if (commit.hash not in commits_branches) and (commit.hash not in commits_tags):
+ # ignore commits not in branches or tags: they won't be rendered anywhere
+ continue
+ render_to_files(
+ render_commit_pages(
+ commit,
+ children=[commits[hash] for hash in children[commit.hash]],
+ branches=commits_branches.get(commit.hash) or [],
+ tags=commits_tags.get(commit.hash) or [],
+ ),
+ basepath=basepath,
+ )
+ for modification in commit.modifications:
+ if modification.new_path:
+ commits_by_file[modification.new_path].append((commit, modification))
+ if modification.old_path and modification.old_path != modification.new_path:
+ commits_by_file[modification.old_path].append((commit, modification))
+ print("")
+
+ print("Building content tree...", end="")
+ current_tree = {path: node for node, path in repo.traverse_tree()}
+ print("\rBuilding content tree [ok]")
+
+ print("Rendering files...", end="")
+ nb_files = len(commits_by_file)
+ dirs = defaultdict(set)
+ for index, path in enumerate(sorted(commits_by_file), 1):
+ print(f"\rRendering files [{index}/{nb_files}]", end="")
+
+ current, is_dir = path, False
+ while True:
+ dirname, basename = os.path.dirname(current), os.path.basename(current)
+ dirs[dirname].add((basename, is_dir))
+ if dirname:
+ current = dirname
+ is_dir = True
+ else:
+ break
+
+ render_to_files(
+ render_file_pages(path, commits_by_file[path], current_tree),
+ basepath=basepath,
+ )
+ print("")
+
+ print("Rendering dirs...", end="")
+ nb_dirs = len(dirs)
+ for index, dir in enumerate(sorted(dirs), 1):
+ print(f"\rRendering dirs [{index}/{nb_dirs}]", end="")
+ render_to_files(
+ render_dir_pages(dir, dirs[dir], current_tree), basepath=basepath
+ )
+
+ print(f"\n\nGit to Sphinx: {location} [ok]\n")
+
+
+if __name__ == "__main__":
+ assert len(sys.argv) > 1 and sys.argv[1], "Missing location"
+ render(sys.argv[1])