mkdocs-git-authors-plugin 1.0.0__tar.gz → 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. {mkdocs_git_authors_plugin-1.0.0/src/mkdocs_git_authors_plugin.egg-info → mkdocs_git_authors_plugin-1.1.0}/PKG-INFO +1 -1
  2. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/pyproject.toml +1 -1
  3. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/cache.py +4 -5
  4. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/git/runner.py +20 -5
  5. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/paths.py +28 -7
  6. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/plugin.py +145 -52
  7. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0/src/mkdocs_git_authors_plugin.egg-info}/PKG-INFO +1 -1
  8. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin.egg-info/SOURCES.txt +2 -1
  9. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/tests/test_faster_builds.py +0 -26
  10. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/tests/test_git_runner.py +6 -0
  11. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/tests/test_paths.py +17 -8
  12. mkdocs_git_authors_plugin-1.1.0/tests/test_submodules.py +264 -0
  13. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/LICENSE +0 -0
  14. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/README.md +0 -0
  15. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/setup.cfg +0 -0
  16. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/__init__.py +0 -0
  17. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/aggregate.py +0 -0
  18. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/authors_file.py +0 -0
  19. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/ci.py +0 -0
  20. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/config.py +0 -0
  21. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/git/__init__.py +0 -0
  22. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/git/porcelain.py +0 -0
  23. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/model.py +0 -0
  24. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin/render.py +0 -0
  25. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin.egg-info/dependency_links.txt +0 -0
  26. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin.egg-info/entry_points.txt +0 -0
  27. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin.egg-info/requires.txt +0 -0
  28. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/src/mkdocs_git_authors_plugin.egg-info/top_level.txt +0 -0
  29. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/tests/test_aggregation.py +0 -0
  30. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/tests/test_authors_file.py +0 -0
  31. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/tests/test_blame_parser.py +0 -0
  32. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/tests/test_build.py +0 -0
  33. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/tests/test_ci.py +0 -0
  34. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/tests/test_plugin_events.py +0 -0
  35. {mkdocs_git_authors_plugin-1.0.0 → mkdocs_git_authors_plugin-1.1.0}/tests/test_render.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mkdocs-git-authors-plugin
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: Mkdocs plugin to display git authors of a page
5
5
  Author-email: Tim Vink <vinktim@gmail.com>
6
6
  License: MIT
@@ -12,7 +12,7 @@ authors = [
12
12
  ]
13
13
  keywords = ["mkdocs", "git", "contributors", "committers", "authors", "plugin"]
14
14
  urls = {Homepage = "https://github.com/timvink/mkdocs-git-authors-plugin"}
15
- version = "1.0.0"
15
+ version = "1.1.0"
16
16
  requires-python = ">=3.11"
17
17
  dependencies = ["mkdocs>=1.5"]
18
18
  classifiers = [
@@ -7,6 +7,8 @@ import stat
7
7
  from collections.abc import Iterable
8
8
  from pathlib import Path
9
9
 
10
+ from mkdocs_git_authors_plugin.paths import directories_up_to
11
+
10
12
  _FILTER = re.compile(r"(?:^|\s)filter=", re.MULTILINE)
11
13
 
12
14
 
@@ -30,11 +32,8 @@ def file_key(path: Path) -> tuple | None:
30
32
 
31
33
  def attributes_files(path: Path, root: Path) -> list[Path]:
32
34
  """The .gitattributes files that may apply to path, from root down to its directory."""
33
- directory, root = Path(os.path.realpath(path.parent)), Path(os.path.realpath(root))
34
- if root != directory and root not in directory.parents:
35
- return [root / ".gitattributes"]
36
- parts = directory.relative_to(root).parts
37
- return [root.joinpath(*parts[:i], ".gitattributes") for i in range(len(parts) + 1)]
35
+ directories = directories_up_to(path.parent, root) or [Path(os.path.realpath(root))]
36
+ return [directory / ".gitattributes" for directory in reversed(directories)]
38
37
 
39
38
 
40
39
  def assigns_filter(paths: Iterable[Path]) -> bool:
@@ -3,7 +3,7 @@
3
3
  import hashlib
4
4
  import os
5
5
  import subprocess
6
- from collections.abc import Iterable
6
+ from collections.abc import Iterable, Sequence
7
7
  from pathlib import Path
8
8
  from typing import NamedTuple
9
9
 
@@ -43,12 +43,21 @@ def commit_count(root: Path) -> int:
43
43
 
44
44
 
45
45
  def blame(
46
- file: Path, *, cwd: Path, ignore_revs: Path | None = None, copy_detection: int = 0
46
+ file: Path,
47
+ *,
48
+ cwd: Path,
49
+ ignore_revs: Path | Sequence[str] | None = None,
50
+ copy_detection: int = 0,
47
51
  ) -> str:
48
- """`git blame --porcelain` output for file, ignoring whitespace changes."""
52
+ """
53
+ `git blame --porcelain` output for file, ignoring whitespace changes and
54
+ the commits in an ignore_revs file or list.
55
+ """
49
56
  args = ["blame", "--porcelain", "--encoding=UTF-8", "-w", *["-C"] * copy_detection]
50
- if ignore_revs is not None:
57
+ if isinstance(ignore_revs, Path):
51
58
  args += ["--ignore-revs-file", str(ignore_revs)]
59
+ elif ignore_revs is not None:
60
+ args += [f"--ignore-rev={rev}" for rev in ignore_revs]
52
61
  return run_git(*args, "--", str(file), cwd=cwd)
53
62
 
54
63
 
@@ -109,6 +118,8 @@ class RepoState(NamedTuple):
109
118
  """
110
119
  attributes: tuple[Path, ...]
111
120
  """Attributes files outside the work tree."""
121
+ hash_length: int
122
+ """The length of commit hashes: 40 for SHA-1, 64 for SHA-256."""
112
123
 
113
124
 
114
125
  def repo_state(root: Path) -> RepoState:
@@ -148,6 +159,9 @@ def repo_state(root: Path) -> RepoState:
148
159
  ),
149
160
  ),
150
161
  attributes=(common_dir / "info" / "attributes", attributes_file),
162
+ hash_length=64
163
+ if values.get("extensions.objectformat", ["sha1"])[-1] == "sha256"
164
+ else 40,
151
165
  )
152
166
 
153
167
 
@@ -169,7 +183,8 @@ def is_untracked_new(file: Path, *, cwd: Path) -> bool:
169
183
  """
170
184
  if not file.is_file():
171
185
  return False
172
- args = ["ls-files", "--others", "--exclude-standard"]
186
+ # Literal, so names like ":page.md" or "[a].md" are not pathspec magic or globs
187
+ args = ["--literal-pathspecs", "ls-files", "--others", "--exclude-standard"]
173
188
  try:
174
189
  run_git("rev-parse", "--verify", "-q", "HEAD", cwd=cwd)
175
190
  except GitError:
@@ -24,21 +24,42 @@ def git_path(
24
24
  if not edit_uri:
25
25
  return None
26
26
  edit_uri = edit_uri.split("#")[0].split("?")[0]
27
- root = root.resolve()
28
27
  for base in (docs_dir, root):
29
28
  candidate = (base / edit_uri).resolve()
30
- if candidate.is_file() and root in candidate.parents:
29
+ if candidate.is_file() and is_inside(candidate.parent, root):
31
30
  return candidate
32
31
  return None
33
32
 
34
33
 
34
+ def directories_up_to(directory: str | Path, root: str | Path) -> list[Path] | None:
35
+ """
36
+ directory and its parents up to and including root, resolving symlinks;
37
+ None if root is not among them. Directories are compared by identity, so
38
+ different spellings of a path on a case-insensitive file system match.
39
+ """
40
+ directories = []
41
+ for parent in (path := Path(os.path.realpath(directory)), *path.parents):
42
+ directories.append(parent)
43
+ try:
44
+ if os.path.samefile(parent, root):
45
+ return directories
46
+ except OSError: # a directory that does not exist
47
+ continue
48
+ return None
49
+
50
+
35
51
  def is_inside(path: str | Path, root: str | Path) -> bool:
36
52
  """Whether path is root or lies inside it, resolving symlinks."""
37
- path, root = (os.path.normcase(os.path.realpath(p)) for p in (path, root))
38
- try:
39
- return os.path.commonpath([path, root]) == root
40
- except ValueError: # different drives on Windows
41
- return False
53
+ return directories_up_to(path, root) is not None
54
+
55
+
56
+ def nested_repository(path: Path, root: Path) -> Path | None:
57
+ """
58
+ The innermost directory below root that holds path and has a `.git` entry,
59
+ like a git submodule; None if there is none.
60
+ """
61
+ directories = directories_up_to(path.parent, root) or [root]
62
+ return next((d for d in directories[:-1] if (d / ".git").exists()), None)
42
63
 
43
64
 
44
65
  def is_excluded(src_path: str, globs: Iterable[str]) -> bool:
@@ -1,5 +1,6 @@
1
1
  import logging
2
2
  import os
3
+ import string
3
4
  from collections.abc import Callable, Iterable, Sequence
4
5
  from concurrent.futures import ThreadPoolExecutor
5
6
  from dataclasses import dataclass, field, replace
@@ -33,7 +34,12 @@ from mkdocs_git_authors_plugin.git.porcelain import (
33
34
  )
34
35
  from mkdocs_git_authors_plugin.git.runner import GitError
35
36
  from mkdocs_git_authors_plugin.model import Author, PageStats, SiteStats
36
- from mkdocs_git_authors_plugin.paths import git_path, is_excluded, is_inside
37
+ from mkdocs_git_authors_plugin.paths import (
38
+ git_path,
39
+ is_excluded,
40
+ is_inside,
41
+ nested_repository,
42
+ )
37
43
 
38
44
  logger = logging.getLogger("mkdocs.plugins")
39
45
 
@@ -42,11 +48,30 @@ class Fallback:
42
48
  """No git history is available: the tags are replaced with nothing."""
43
49
 
44
50
 
51
+ @dataclass
52
+ class Repo:
53
+ """A repository with pages: the main one, or a submodule or other nested repository."""
54
+
55
+ root: Path
56
+ fingerprint: tuple = ()
57
+ """Repository-wide inputs of `git blame` output and commit messages."""
58
+ blame_key: tuple = ()
59
+ """What `git blame` output depends on, besides the blamed file and its attributes."""
60
+ replace_refs: str = ""
61
+ attributes: tuple[Path, ...] = ()
62
+ """Attributes files outside the work tree."""
63
+ ignore_revs: Path | tuple[str, ...] | None = None
64
+ """The ignore_commits file, or its hashes when it also has hashes of another length."""
65
+ use_cache: bool = True
66
+ """False when attributes assign a filter driver, whose output cannot be tracked."""
67
+
68
+
45
69
  @dataclass
46
70
  class BuildState:
47
- """What one build knows about the git repository."""
71
+ """What one build knows about the git repositories."""
48
72
 
49
73
  root: Path
74
+ """The main repository, which contains docs_dir."""
50
75
  ignore_revs: Path | None
51
76
  docs_dir: Path
52
77
  authors_file: Path | None = None
@@ -57,14 +82,8 @@ class BuildState:
57
82
  site: SiteStats = field(default_factory=lambda: site_stats([]))
58
83
  now: datetime = field(default_factory=lambda: _now())
59
84
  """The date of uncommitted lines, the same for all pages of a build."""
60
- fingerprint: tuple = ()
61
- """Repository-wide inputs of `git blame` output and commit messages."""
62
- blame_key: tuple = ()
63
- """What `git blame` output depends on, besides the blamed file and its attributes."""
64
- replace_refs: str = ""
65
- global_attributes: tuple[Path, ...] = ()
66
- use_cache: bool = True
67
- """False when attributes assign a filter driver, whose output cannot be tracked."""
85
+ repos: dict[Path, Repo] = field(default_factory=dict)
86
+ """The repository of each blamed path."""
68
87
  co_author_keys: set[tuple] = field(default_factory=set)
69
88
  """The co-author cache keys used in this build."""
70
89
 
@@ -84,7 +103,7 @@ class GitAuthorsPlugin(BasePlugin[GitAuthorsPluginConfig]):
84
103
  self._blame_cache: dict[Path, tuple[tuple, str]] = {}
85
104
  """`git blame` output and the key it is valid for, by path."""
86
105
  self._co_authors: dict[tuple, list[tuple[str, str]]] = {}
87
- """Co-authors by (repository fingerprint, commit SHA)."""
106
+ """Co-authors by (fingerprint of the commit's repository, commit SHA)."""
88
107
 
89
108
  def on_startup(
90
109
  self, command: Literal["build", "gh-deploy", "serve"], dirty: bool, **kwargs
@@ -207,7 +226,9 @@ class GitAuthorsPlugin(BasePlugin[GitAuthorsPluginConfig]):
207
226
  authors = []
208
227
  case BuildState() as build:
209
228
  stats, ranked = self._page_authors(page.file, build)
210
- authors = render.authors_to_dicts(ranked, stats, build.site, self.config)
229
+ authors = render.authors_to_dicts(
230
+ ranked, stats, build.site, self.config
231
+ )
211
232
  page.meta.setdefault("git_authors", authors)
212
233
  page.meta.setdefault("git_authors_names", ", ".join(a["name"] for a in authors))
213
234
  return markdown
@@ -286,11 +307,6 @@ class GitAuthorsPlugin(BasePlugin[GitAuthorsPluginConfig]):
286
307
  def _site_stats(self, files: Iterable[File], build: BuildState) -> SiteStats:
287
308
  """Blame all documentation pages in files that are not excluded."""
288
309
  build.now = _now()
289
- state = runner.repo_state(build.root)
290
- build.replace_refs = state.replace_refs
291
- build.global_attributes = state.attributes
292
- build.fingerprint, build.blame_key = self._keys(build, state)
293
- build.use_cache = True
294
310
  build.co_author_keys = set()
295
311
  paths: dict[Path, None] = {}
296
312
  for file in files:
@@ -303,6 +319,7 @@ class GitAuthorsPlugin(BasePlugin[GitAuthorsPluginConfig]):
303
319
  )
304
320
  elif file.is_documentation_page():
305
321
  paths[path] = None
322
+ build.repos = self._repos(paths, build)
306
323
  pages = self._pages_stats(list(paths), build)
307
324
  # Forget pages and commits that are no longer in the site
308
325
  self._blame_cache = {
@@ -315,27 +332,62 @@ class GitAuthorsPlugin(BasePlugin[GitAuthorsPluginConfig]):
315
332
  }
316
333
  return site_stats(pages, build.profiles)
317
334
 
335
+ def _repos(self, paths: Iterable[Path], build: BuildState) -> dict[Path, Repo]:
336
+ """
337
+ The repository of each path: the main one, or the submodule or other
338
+ nested repository it is in, so git sees the file's own history.
339
+ """
340
+ roots: dict[Path, Path | None] = {}
341
+ """The repository root of each directory with a .git entry; None if git rejects it."""
342
+ repos: dict[Path, Repo] = {}
343
+ result = {}
344
+ for path in paths:
345
+ root, below = None, path
346
+ # Past broken .git entries, up to the main repository
347
+ while root is None and (nested := nested_repository(below, build.root)):
348
+ if nested not in roots:
349
+ try:
350
+ roots[nested] = runner.repo_root(nested)
351
+ except GitError:
352
+ roots[nested] = None
353
+ root, below = roots[nested], nested
354
+ root = root or build.root
355
+ if root not in repos:
356
+ repos[root] = Repo(root)
357
+ self._update_keys(repos[root], build)
358
+ result[path] = repos[root]
359
+ return result
360
+
318
361
  def _pages_stats(self, paths: Sequence[Path], build: BuildState) -> list[PageStats]:
319
362
  """
320
363
  Blame paths, running git in parallel, and count their lines in order.
321
- Blame output is reused while the file, its attributes and
322
- build.blame_key are unchanged.
364
+ Blame output is reused while the file, its attributes and its
365
+ repository's blame_key are unchanged.
323
366
  """
324
- attributes = {path: attributes_files(path, build.root) for path in paths}
325
- if build.use_cache and assigns_filter(
326
- {
327
- *build.global_attributes,
328
- *(a for files in attributes.values() for a in files),
329
- }
330
- ):
331
- build.use_cache = False
367
+ repos = {build.repos[path].root: build.repos[path] for path in paths}
368
+ attributes = {
369
+ path: attributes_files(path, build.repos[path].root) for path in paths
370
+ }
371
+ for repo in repos.values():
372
+ repo.use_cache = not assigns_filter(
373
+ {
374
+ *repo.attributes,
375
+ *(
376
+ a
377
+ for p in paths
378
+ if build.repos[p] is repo
379
+ for a in attributes[p]
380
+ ),
381
+ }
382
+ )
332
383
  keys = {
333
- path: _page_key(path, attributes[path], build.blame_key) for path in paths
384
+ path: _page_key(path, attributes[path], build.repos[path].blame_key)
385
+ for path in paths
334
386
  }
335
387
  blames = {
336
388
  path: _Blame(cached[1])
337
389
  for path in paths
338
- if build.use_cache
390
+ if build.repos[path].use_cache
339
391
  and (cached := self._blame_cache.get(path))
340
392
  and cached[0] == keys[path]
341
393
  }
@@ -344,10 +396,14 @@ class GitAuthorsPlugin(BasePlugin[GitAuthorsPluginConfig]):
344
396
  _run_blame, build=build, copy_detection=self.config.copy_detection
345
397
  )
346
398
  blames |= zip(missing, self._map(blame, missing))
347
- if build.use_cache and missing:
399
+ if cacheable := [path for path in missing if build.repos[path].use_cache]:
348
400
  # Only store output if nothing changed while git ran
349
- _, blame_key = self._keys(build, runner.repo_state(build.root))
350
- for path in missing:
401
+ blame_keys = {
402
+ root: self._keys(root, runner.repo_state(root), build.ignore_revs)[1]
403
+ for root in {build.repos[path].root: None for path in cacheable}
404
+ }
405
+ for path in cacheable:
406
+ blame_key = blame_keys[build.repos[path].root]
351
407
  if (
352
408
  blames[path].output is not None
353
409
  and keys[path][0] is not None
@@ -356,42 +412,59 @@ class GitAuthorsPlugin(BasePlugin[GitAuthorsPluginConfig]):
356
412
  self._blame_cache[path] = (keys[path], blames[path].output)
357
413
 
358
414
  lines = {path: self._blame_lines(path, blames[path], build) for path in paths}
359
- co_authors = {}
415
+ # By repository, as each submodule has its own commits
416
+ co_authors: dict[Path, dict[str, list[tuple[str, str]]]] = {}
360
417
  if self.config.add_co_authors:
361
- shas = {line.sha for page in lines.values() for line in page}
362
- co_authors = self._load_co_authors(
363
- {sha for sha in shas if not is_uncommitted(sha)}, build
364
- )
418
+ shas: dict[Path, set[str]] = {root: set() for root in repos}
419
+ for path in paths:
420
+ shas[build.repos[path].root].update(
421
+ line.sha for line in lines[path] if not is_uncommitted(line.sha)
422
+ )
423
+ co_authors = {
424
+ root: self._load_co_authors(shas[root], repo, build)
425
+ for root, repo in repos.items()
426
+ }
365
427
  return [
366
428
  page_stats(
367
429
  path,
368
430
  lines[path],
369
- co_authors,
431
+ co_authors.get(build.repos[path].root, {}),
370
432
  ignore_authors=self.config.ignore_authors,
371
433
  count_empty_lines=self.config.count_empty_lines,
372
434
  )
373
435
  for path in paths
374
436
  ]
375
437
 
376
- def _keys(self, build: BuildState, state: runner.RepoState) -> tuple[tuple, tuple]:
438
+ def _update_keys(self, repo: Repo, build: BuildState) -> None:
439
+ state = runner.repo_state(repo.root)
440
+ repo.replace_refs = state.replace_refs
441
+ repo.attributes = state.attributes
442
+ repo.ignore_revs = _ignore_revs(build.ignore_revs, state.hash_length)
443
+ repo.fingerprint, repo.blame_key = self._keys(
444
+ repo.root, state, build.ignore_revs
445
+ )
446
+
447
+ def _keys(
448
+ self, root: Path, state: runner.RepoState, ignore_revs: Path | None
449
+ ) -> tuple[tuple, tuple]:
377
450
  """The repository fingerprint, and the key of blame output without the page."""
378
451
  fingerprint = (
379
- build.root,
452
+ root,
380
453
  state.config,
381
454
  state.mailmap_blob,
382
455
  state.replace_refs,
383
456
  tuple(
384
457
  (file, file_key(file))
385
- for file in (build.root / ".mailmap", *state.attributes)
458
+ for file in (root / ".mailmap", *state.attributes)
386
459
  ),
387
460
  )
388
- files = (*state.files, build.ignore_revs) if build.ignore_revs else state.files
461
+ files = (*state.files, ignore_revs) if ignore_revs else state.files
389
462
  blame_key = (
390
463
  fingerprint,
391
464
  state.head,
392
465
  state.index,
393
466
  self.config.copy_detection,
394
- build.ignore_revs,
467
+ ignore_revs,
395
468
  tuple((file, file_key(file)) for file in files),
396
469
  )
397
470
  return fingerprint, blame_key
@@ -422,10 +495,10 @@ class GitAuthorsPlugin(BasePlugin[GitAuthorsPluginConfig]):
422
495
  return []
423
496
 
424
497
  def _load_co_authors(
425
- self, shas: set[str], build: BuildState
498
+ self, shas: set[str], repo: Repo, build: BuildState
426
499
  ) -> dict[str, list[tuple[str, str]]]:
427
- """The co-authors of each commit, reading all unknown commit messages at once."""
428
- keys = {sha: (build.fingerprint, sha) for sha in shas}
500
+ """The co-authors of each commit in repo, reading all unknown commit messages at once."""
501
+ keys = {sha: (repo.fingerprint, sha) for sha in shas}
429
502
  build.co_author_keys.update(keys.values())
430
503
  co_authors = {
431
504
  sha: self._co_authors[key]
@@ -433,9 +506,9 @@ class GitAuthorsPlugin(BasePlugin[GitAuthorsPluginConfig]):
433
506
  if key in self._co_authors
434
507
  }
435
508
  if missing := shas - co_authors.keys():
436
- messages = runner.commit_messages(missing, cwd=build.root)
509
+ messages = runner.commit_messages(missing, cwd=repo.root)
437
510
  # Messages read while replaced commits changed may be outdated
438
- store = runner.replace_refs(build.root) == build.replace_refs
511
+ store = runner.replace_refs(repo.root) == repo.replace_refs
439
512
  for sha in sorted(missing):
440
513
  if sha not in messages:
441
514
  (logger.warning if self.config.strict else logger.info)(
@@ -462,18 +535,38 @@ class GitAuthorsPlugin(BasePlugin[GitAuthorsPluginConfig]):
462
535
 
463
536
 
464
537
  def _run_blame(path: Path, *, build: BuildState, copy_detection: int) -> _Blame:
465
- """Run git for one page; safe to call from several threads."""
538
+ """Run git for one page in its own repository; safe to call from several threads."""
539
+ repo = build.repos[path]
466
540
  try:
467
541
  return _Blame(
468
542
  runner.blame(
469
543
  path,
470
- cwd=build.root,
471
- ignore_revs=build.ignore_revs,
544
+ cwd=repo.root,
545
+ ignore_revs=repo.ignore_revs,
472
546
  copy_detection=copy_detection,
473
547
  )
474
548
  )
475
549
  except GitError:
476
- return _Blame(None, runner.is_untracked_new(path, cwd=build.root))
550
+ return _Blame(None, runner.is_untracked_new(path, cwd=repo.root))
551
+
552
+
553
+ def _ignore_revs(file: Path | None, hash_length: int) -> Path | tuple[str, ...] | None:
554
+ """
555
+ The ignore_commits file for a repository with hashes of hash_length. git
556
+ skips unknown hashes, but rejects those of another length (SHA-1 or
557
+ SHA-256): then leave them out and return the other hashes.
558
+ """
559
+ if file is None:
560
+ return None
561
+ lines = file.read_text(encoding="utf-8", errors="replace").splitlines()
562
+ revs = [rev for line in lines if (rev := line.split("#")[0].strip())]
563
+ other = 64 if hash_length == 40 else 40
564
+ kept = tuple(
565
+ rev
566
+ for rev in revs
567
+ if not (len(rev) == other and all(c in string.hexdigits for c in rev))
568
+ )
569
+ return file if len(kept) == len(revs) else kept
477
570
 
478
571
 
479
572
  def _page_key(path: Path, attributes: Sequence[Path], blame_key: tuple) -> tuple:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mkdocs-git-authors-plugin
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: Mkdocs plugin to display git authors of a page
5
5
  Author-email: Tim Vink <vinktim@gmail.com>
6
6
  License: MIT
@@ -29,4 +29,5 @@ tests/test_faster_builds.py
29
29
  tests/test_git_runner.py
30
30
  tests/test_paths.py
31
31
  tests/test_plugin_events.py
32
- tests/test_render.py
32
+ tests/test_render.py
33
+ tests/test_submodules.py
@@ -16,32 +16,6 @@ from mkdocs_git_authors_plugin.git import runner
16
16
  NOW = datetime(2030, 6, 1, 12, tzinfo=timezone(timedelta(hours=2)))
17
17
 
18
18
 
19
- @pytest.fixture
20
- def git_calls(monkeypatch):
21
- """Count the pages blamed and the commit message lookups."""
22
- calls = {"blame": [], "log": 0}
23
- blame, commit_messages = runner.blame, runner.commit_messages
24
-
25
- def spy_blame(file, **kwargs):
26
- calls["blame"].append(file.name)
27
- return blame(file, **kwargs)
28
-
29
- def spy_commit_messages(shas, **kwargs):
30
- calls["log"] += 1
31
- return commit_messages(shas, **kwargs)
32
-
33
- monkeypatch.setattr(runner, "blame", spy_blame)
34
- monkeypatch.setattr(runner, "commit_messages", spy_commit_messages)
35
-
36
- def take():
37
- taken = sorted(calls["blame"]), calls["log"]
38
- calls["blame"].clear()
39
- calls["log"] = 0
40
- return taken
41
-
42
- return take
43
-
44
-
45
19
  @pytest.fixture
46
20
  def site(git_repo):
47
21
  """Several pages with co-authors, uncommitted lines, a new page and an ignored page."""
@@ -145,3 +145,9 @@ def test_is_untracked_new_outside_repository(git_repo, tmp_path_factory):
145
145
  outside = tmp_path_factory.mktemp("outside") / "page.md"
146
146
  outside.write_text("Hello\n")
147
147
  assert not runner.is_untracked_new(outside, cwd=git_repo.root)
148
+
149
+
150
+ def test_is_untracked_new_takes_names_literally(git_repo):
151
+ git_repo.commit("[a].md", "Hello\n")
152
+ git_repo.write("a.md", "Hello\n")
153
+ assert not runner.is_untracked_new(git_repo.root / "[a].md", cwd=git_repo.root)
@@ -1,13 +1,17 @@
1
1
  """Mapping pages to files with git history, and excluding pages."""
2
2
 
3
- import ntpath
4
3
  import os
5
4
  import sys
6
5
 
7
6
  import pytest
8
7
  from mkdocs.structure.files import File
9
8
 
10
- from mkdocs_git_authors_plugin.paths import git_path, is_excluded, is_inside
9
+ from mkdocs_git_authors_plugin.paths import (
10
+ git_path,
11
+ is_excluded,
12
+ is_inside,
13
+ nested_repository,
14
+ )
11
15
 
12
16
 
13
17
  @pytest.fixture
@@ -62,6 +66,17 @@ def test_git_path_of_in_memory_file(project, make_generated_file):
62
66
  )
63
67
 
64
68
 
69
+ def test_nested_repository(project):
70
+ (project / "docs" / "sub" / ".git").mkdir(parents=True)
71
+ sub = (project / "docs" / "sub").resolve()
72
+ assert (
73
+ nested_repository(project / "docs" / "sub" / "deep" / "page.md", project) == sub
74
+ )
75
+ assert nested_repository(project / "docs" / "sub" / "page.md", project) == sub
76
+ assert nested_repository(project / "docs" / "page.md", project) is None
77
+ assert nested_repository(project.parent / "outside.py", project) is None
78
+
79
+
65
80
  def test_is_inside(project):
66
81
  assert is_inside(project, project)
67
82
  assert is_inside(project / "docs", project)
@@ -74,12 +89,6 @@ def test_is_inside_resolves_symlinks(project):
74
89
  assert is_inside(project.parent / "docs_link", project)
75
90
 
76
91
 
77
- def test_is_inside_different_windows_drives(monkeypatch):
78
- monkeypatch.setattr(os, "path", ntpath)
79
- assert is_inside("C:\\docs", "C:\\")
80
- assert not is_inside("D:\\docs", "C:\\repo")
81
-
82
-
83
92
  @pytest.mark.parametrize(
84
93
  "src_path, globs, excluded",
85
94
  [
@@ -0,0 +1,264 @@
1
+ """Pages inside git submodules are blamed in the submodule's own repository (#82)."""
2
+
3
+ import logging
4
+ import os
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ from mkdocs_git_authors_plugin import plugin
11
+ from mkdocs_git_authors_plugin.git import runner
12
+
13
+ TIM = ("Tim", "tim@abc.com")
14
+ SUB = ("Sub", "sub@abc.com")
15
+ ANN = ("Ann", "ann@abc.com")
16
+ NOT_COMMITTED = ("Not Committed Yet", "not.committed.yet")
17
+
18
+
19
+ def page_authors(run, uri):
20
+ return sorted(
21
+ (a["name"], a["email"], a["lines"])
22
+ for a in run.pages[uri].context["git_info"]["page_authors"]
23
+ )
24
+
25
+
26
+ @pytest.fixture
27
+ def project(git_repo, add_submodule):
28
+ """docs/index.md in the main repository, docs/sub/page.md in a submodule."""
29
+ git_repo.commit("docs/index.md", "a\nb\n", author="Tim <tim@abc.com>")
30
+ sub = add_submodule(git_repo, "docs/sub", [("page.md", "x\n", "Sub <sub@abc.com>")])
31
+ # Not committed in the main repository, which still points at the first commit
32
+ sub.commit(
33
+ "page.md", "y\n", author="Tim <tim@abc.com>", co_authors=("Ann <ann@abc.com>",)
34
+ )
35
+ return git_repo, sub
36
+
37
+
38
+ @pytest.mark.parametrize("add_co_authors", [False, True])
39
+ def test_page_gets_submodule_authors(project, run_plugin, add_co_authors):
40
+ repo, _ = project
41
+ run = run_plugin(repo.root, add_co_authors=add_co_authors)
42
+ expected = [(*SUB, 1), (*TIM, 1)]
43
+ if add_co_authors:
44
+ expected.insert(0, (*ANN, 1))
45
+ assert page_authors(run, "sub/page.md") == expected
46
+ assert page_authors(run, "index.md") == [(*TIM, 2)]
47
+
48
+
49
+ def test_site_totals_combine_repositories(project, run_plugin):
50
+ repo, _ = project
51
+ site = run_plugin(repo.root, add_co_authors=True).plugin._build.site
52
+ assert site.lines == {"tim@abc.com": 3, "sub@abc.com": 1, "ann@abc.com": 1}
53
+ assert site.total_lines == 4
54
+
55
+
56
+ def test_uncommitted_and_new_files(project, run_plugin, caplog):
57
+ repo, sub = project
58
+ sub.write("page.md", "z\n", mode="a")
59
+ sub.write("new.md", "new\n")
60
+ sub.write(".gitignore", "ignored.md\n")
61
+ sub.write("ignored.md", "ignored\n")
62
+ with caplog.at_level(logging.INFO, logger="mkdocs.plugins"):
63
+ run = run_plugin(repo.root, add_co_authors=True)
64
+ assert page_authors(run, "sub/page.md") == [
65
+ (*ANN, 1),
66
+ (*NOT_COMMITTED, 1),
67
+ (*SUB, 1),
68
+ (*TIM, 1),
69
+ ]
70
+ assert page_authors(run, "sub/new.md") == [(*NOT_COMMITTED, 1)]
71
+ assert page_authors(run, "sub/ignored.md") == []
72
+ assert [r.message for r in caplog.records] == [
73
+ f"[git-authors-plugin] {sub.root / 'ignored.md'} has not been committed yet. Lines are not counted"
74
+ ]
75
+
76
+
77
+ def test_parallel_output_is_identical(project, run_plugin, monkeypatch):
78
+ repo, sub = project
79
+ sub.write("page.md", "z\n", mode="a")
80
+ monkeypatch.setattr(plugin, "_now", lambda: plugin.datetime(2030, 1, 1))
81
+ runs = [
82
+ {
83
+ uri: page.context
84
+ for uri, page in run_plugin(
85
+ repo.root, add_co_authors=True, enable_parallel_processing=parallel
86
+ ).pages.items()
87
+ }
88
+ for parallel in (True, False)
89
+ ]
90
+ assert runs[0] == runs[1]
91
+
92
+
93
+ def test_serve_cache_is_per_repository(project, run_plugin, make_plugin, git_calls):
94
+ repo, sub = project
95
+ serve = make_plugin(add_co_authors=True)
96
+
97
+ def rebuild():
98
+ run = run_plugin(repo.root, plugin=serve, command="serve")
99
+ return git_calls(), run
100
+
101
+ assert rebuild()[0] == (["index.md", "page.md"], 2)
102
+ assert rebuild()[0] == ([], 0)
103
+
104
+ # A new commit in the submodule only affects its pages
105
+ sub.commit("page.md", "w\n", author="Sub <sub@abc.com>")
106
+ (blamed, logs), run = rebuild()
107
+ assert (blamed, logs) == (["page.md"], 1)
108
+ assert page_authors(run, "sub/page.md") == [(*ANN, 1), (*SUB, 2), (*TIM, 1)]
109
+
110
+ sub.write(".mailmap", "Subby <sub@abc.com>\n")
111
+ (blamed, _), run = rebuild()
112
+ assert blamed == ["page.md"]
113
+ assert ("Subby", "sub@abc.com", 2) in page_authors(run, "sub/page.md")
114
+
115
+ # Committing the new submodule commit in the main repository only affects its pages
116
+ repo.commit(message="update submodule")
117
+ assert rebuild()[0] == (["index.md"], 0)
118
+
119
+
120
+ def test_ignore_commits_in_all_repositories(project, run_plugin):
121
+ """git blame skips the full hashes it does not know, such as the other repository's."""
122
+ repo, sub = project
123
+ bot = "Bot <bot@abc.com>"
124
+ ignored = [
125
+ repo.commit("docs/index.md", "a.1\nb.1\n", author=bot, mode="w"),
126
+ sub.commit("page.md", "x.1\ny.1\n", author=bot, mode="w"),
127
+ ]
128
+ repo.write("ignore-revs", "".join(f"{sha}\n" for sha in ignored))
129
+ run = run_plugin(repo.root, ignore_commits="ignore-revs")
130
+ assert page_authors(run, "index.md") == [(*TIM, 2)]
131
+ assert page_authors(run, "sub/page.md") == [(*SUB, 1), (*TIM, 1)]
132
+
133
+
134
+ def test_nested_repository(git_repo, init_repo, run_plugin):
135
+ """A repository below the main one, without being a submodule."""
136
+ git_repo.commit("docs/index.md", "a\n")
137
+ init_repo(git_repo.root / "docs" / "nested").commit(
138
+ "page.md", "n\n", author="Sub <sub@abc.com>"
139
+ )
140
+ run = run_plugin(git_repo.root)
141
+ assert page_authors(run, "nested/page.md") == [(*SUB, 1)]
142
+ assert page_authors(run, "index.md") == [(*TIM, 1)]
143
+
144
+
145
+ def test_invalid_nested_repository(git_repo, run_plugin):
146
+ """Directories with a broken or empty .git are blamed in the main repository."""
147
+ git_repo.commit("docs/vendored/page.md", "a\n")
148
+ git_repo.write("docs/vendored/.git", "gitdir: /does/not/exist\n")
149
+ git_repo.write("docs/empty/.git/.keep", "")
150
+ git_repo.commit("docs/empty/page.md", "b\n")
151
+ run = run_plugin(git_repo.root)
152
+ assert page_authors(run, "empty/page.md") == [(*TIM, 1)]
153
+ assert page_authors(run, "vendored/page.md") == [(*TIM, 1)]
154
+
155
+
156
+ def test_generated_page_with_edit_path_in_submodule(
157
+ project, run_plugin, make_generated_file
158
+ ):
159
+ repo, _ = project
160
+
161
+ def other_on_files(files):
162
+ file = make_generated_file("generated.md", "")
163
+ file.edit_uri = "sub/page.md"
164
+ files.append(file)
165
+
166
+ run = run_plugin(repo.root, other_on_files=other_on_files)
167
+ assert page_authors(run, "generated.md") == [(*SUB, 1), (*TIM, 1)]
168
+
169
+
170
+ def test_broken_repository_inside_submodule(project, run_plugin):
171
+ repo, sub = project
172
+ sub.commit("vendor/page.md", "v\n", author="Sub <sub@abc.com>")
173
+ sub.write("vendor/.git", "gitdir: /does/not/exist\n")
174
+ run = run_plugin(repo.root)
175
+ assert page_authors(run, "sub/vendor/page.md") == [(*SUB, 1)]
176
+
177
+
178
+ def test_build(project, write_mkdocs_yml, build):
179
+ repo, sub = project
180
+ sub.write("new.md", "{{ git_page_authors }}\n")
181
+ sub.write("page.md", "{{ git_page_authors }}\n", mode="a")
182
+ config = write_mkdocs_yml(
183
+ repo.root, strict=True, plugins=[{"git-authors": {"add_co_authors": True}}]
184
+ )
185
+ site, output = build(config)
186
+ assert "has not been committed yet" not in output
187
+ page = (site / "sub" / "page" / "index.html").read_text()
188
+ for name in ("Ann", "Sub", "Tim", "Not Committed Yet"):
189
+ assert name in page
190
+ assert "Not Committed Yet" in (site / "sub" / "new" / "index.html").read_text()
191
+
192
+
193
+ def test_git_runs_in_the_page_repository(project, run_plugin, monkeypatch):
194
+ repo, sub = project
195
+ sub.write("new.md", "new\n")
196
+ calls = {}
197
+ run_git = runner.run_git
198
+
199
+ def spy(*args, cwd):
200
+ command = next(arg for arg in args if not arg.startswith("-"))
201
+ if args[-1].endswith(".md"):
202
+ calls[command, Path(args[-1]).name] = (Path(args[-1]).is_absolute(), cwd)
203
+ return run_git(*args, cwd=cwd)
204
+
205
+ monkeypatch.setattr(runner, "run_git", spy)
206
+ run_plugin(repo.root)
207
+ main, submodule = (Path(os.path.realpath(r.root)) for r in (repo, sub))
208
+ assert calls == {
209
+ ("blame", "index.md"): (True, main),
210
+ ("blame", "page.md"): (True, submodule),
211
+ ("blame", "new.md"): (True, submodule),
212
+ ("ls-files", "new.md"): (True, submodule),
213
+ }
214
+
215
+
216
+ def test_case_alias_of_the_project_path(project, run_plugin):
217
+ """On a case-insensitive file system, paths may be spelled unlike git spells them."""
218
+ repo, _ = project
219
+ alias = repo.root.parent / repo.root.name.swapcase()
220
+ if not alias.exists():
221
+ pytest.skip("the file system is case-sensitive")
222
+ run = run_plugin(alias, add_co_authors=True)
223
+ assert run.plugin._build.root.name != alias.name
224
+ assert page_authors(run, "sub/page.md") == [(*ANN, 1), (*SUB, 1), (*TIM, 1)]
225
+ assert page_authors(run, "index.md") == [(*TIM, 2)]
226
+
227
+
228
+ def test_filter_attributes_bypass_the_cache_of_their_repository(
229
+ project, run_plugin, make_plugin, git_calls
230
+ ):
231
+ repo, sub = project
232
+ serve = make_plugin()
233
+
234
+ def rebuild():
235
+ run_plugin(repo.root, plugin=serve, command="serve")
236
+ return git_calls()
237
+
238
+ rebuild()
239
+ sub.write(".gitattributes", "*.md filter=lfs\n")
240
+ assert rebuild() == (["page.md"], 0)
241
+ assert rebuild() == (["page.md"], 0)
242
+
243
+
244
+ def test_ignore_commits_with_sha1_and_sha256_repositories(git_repo, run_plugin):
245
+ """git rejects hashes of the other length, so each repository gets its own."""
246
+ git_repo.write(".gitignore", "docs/nested/\n")
247
+ git_repo.commit("docs/index.md", "a\n")
248
+ nested = type(git_repo)(git_repo.root / "docs" / "nested")
249
+ nested.root.mkdir()
250
+ try:
251
+ nested.git("init", "-q", "--object-format=sha256")
252
+ except subprocess.CalledProcessError: # pragma: no cover - git before 2.29
253
+ pytest.skip("git does not support SHA-256 repositories")
254
+ nested.commit("page.md", "n\n", author="Sub <sub@abc.com>")
255
+ bot = "Bot <bot@abc.com>"
256
+ ignored = [
257
+ git_repo.commit("docs/index.md", "a.1\n", author=bot, mode="w"),
258
+ nested.commit("page.md", "n.1\n", author=bot, mode="w"),
259
+ ]
260
+ assert [len(sha) for sha in ignored] == [40, 64]
261
+ git_repo.write("ignore-revs", "# Bots\n" + "".join(f"{sha}\n" for sha in ignored))
262
+ run = run_plugin(git_repo.root, ignore_commits="ignore-revs")
263
+ assert page_authors(run, "index.md") == [(*TIM, 1)]
264
+ assert page_authors(run, "nested/page.md") == [(*SUB, 1)]