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
"""Persist in-progress commit messages in the repository COMMIT_EDITMSG file."""
from __future__ import annotations
from pathlib import Path
from pygit2 import Commit, GitError, Repository
def commit_editmsg_path(repo_path: Path) -> Path:
return repo_path / "COMMIT_EDITMSG"
def _read_draft_text(repo_path: Path) -> str:
path = commit_editmsg_path(repo_path)
if not path.is_file():
return ""
try:
text = path.read_text(encoding="utf-8")
except OSError:
return ""
for line in text.splitlines():
stripped = line.strip()
if stripped and not stripped.startswith("#"):
return stripped
return ""
def load_commit_draft(repo_path: Path, repo: Repository | None = None) -> str:
draft = _read_draft_text(repo_path)
if not draft or repo is None:
return draft
try:
head_message = repo.head.peel(Commit).message.strip()
except GitError:
return draft
if draft.strip() == head_message:
return ""
return draft
def save_commit_draft(repo_path: Path, message: str) -> None:
path = commit_editmsg_path(repo_path)
try:
if message:
path.write_text(f"{message}\n", encoding="utf-8")
elif path.is_file():
path.unlink()
except OSError:
return