-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpre-commit
More file actions
executable file
·123 lines (104 loc) · 3.86 KB
/
pre-commit
File metadata and controls
executable file
·123 lines (104 loc) · 3.86 KB
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
#!python3
import logging
import subprocess
from datetime import date
from pathlib import Path
import frontmatter
from frontmatter.default_handlers import TOMLHandler
# Set up logging
logging.basicConfig(
filename="pre_commit.log",
level=logging.DEBUG,
format="%(asctime)s:%(levelname)s:%(message)s",
)
def get_commited_files() -> list:
"""Get the list of modified files. Keeps only .md files and ignore _index.md"""
"""return: list of .md file names"""
try:
cmd = "git diff --cached --name-only --diff-filter=M"
# cmd = "ls --color=never ./test/index.md"
files = subprocess.check_output(cmd.split()).decode().split()
target_files = [
f for f in files if f.endswith(".md") and not f.endswith("_index.md")
]
logging.debug(f"Modified .md files: {target_files}")
return target_files
except subprocess.CalledProcessError as e:
logging.error(f"Failed to get committed files: {e}")
return []
except Exception as e:
logging.error(f"Unexpected error: {e}")
return []
def get_last_modified_date(path: Path) -> date:
"""Get the last modified date of a file"""
"""path: Path object"""
"""return: date object"""
try:
last_modified_date = date.fromtimestamp(path.stat().st_mtime)
return last_modified_date
except FileNotFoundError:
logging.error(f"File not found: {path}")
return None
def get_post_content(path: Path) -> frontmatter.Post:
"""Get the content of a post"""
"""path: Path object"""
"""return: frontmatter.Post object"""
try:
file_content = path.read_text()
post = frontmatter.loads(file_content, handler=TOMLHandler())
logging.debug(f"Post content retrieved from {path}")
return post
except FileNotFoundError:
logging.error(f"File not found: {path}")
return None
except Exception as e:
logging.error(f"Unexpected error: {e}")
return None
def update_post_metadata(
post: frontmatter.Post, last_modified_date: date
) -> frontmatter.Post:
"""Update the metadata of a post"""
"""post: frontmatter.Post object"""
"""last_modified_date: date object"""
"""return: frontmatter.Post object"""
post.metadata["updated"] = last_modified_date
logging.debug(f"Post metadata updated with date {last_modified_date}")
return post
def save_post_content(path: Path, post: frontmatter.Post):
"""Save the content of a post"""
"""path: Path object"""
"""post: frontmatter.Post object"""
try:
path.write_text(frontmatter.dumps(post))
logging.debug(f"Post content saved to {path}")
except FileNotFoundError as e:
logging.error(f"Failed to save post content to {path}: {e}")
except Exception as e:
logging.error(f"Unexpected error: {e}")
def add_file_to_git_index(md_file: str):
"""Add a file to the Git index"""
"""md_file: file name"""
try:
subprocess.run(["git", "add", md_file])
logging.debug(f"File {md_file} added to Git index")
except subprocess.CalledProcessError as e:
logging.error(f"Failed to add file {md_file} to Git index: {e}")
except Exception as e:
logging.error(f"Unexpected error: {e}")
def main():
try:
for file in get_commited_files():
path = Path(file)
last_modified_date = get_last_modified_date(path)
if last_modified_date:
post = get_post_content(path)
if post:
post = update_post_metadata(post, last_modified_date)
save_post_content(path, post)
add_file_to_git_index(file)
except Exception as e:
logging.error(f"Error in main function: {e}")
if __name__ == "__main__":
logging.info("Starting pre-commit hook")
main()
logging.info("Pre-commit hook finished")