-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathtxt.py
More file actions
87 lines (64 loc) · 2.7 KB
/
txt.py
File metadata and controls
87 lines (64 loc) · 2.7 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
import os
import re
from datetime import datetime
from pathlib import Path
from typing import Iterable
from dateutil.parser import parse
from neoteroi.mkdocs.contribs.domain import ContributionsReader, Contributor
def _read_lines_strip_comments(file_path: Path):
with open(str(file_path), mode="rt", encoding="utf8") as file:
lines = file.readlines()
lines = (re.sub("#.+$", "", x).strip() for x in lines)
return [line for line in lines if line]
class TXTContributionsReader(ContributionsReader):
"""
A ContributionsReader that can read contributors information described in .txt
files.
"""
_contrib_rx = re.compile(
r"(?P<name>[^\<]+)<(?P<email>[^\>]+)>\s\((?P<count>[^\>]+)\)"
)
_last_mod_time_rx = re.compile(
r"^\s*Last\smodified\stime:\s(?P<value>.+)$", re.IGNORECASE | re.MULTILINE
)
def _parse_value(self, value: str) -> tuple[str, str, int]:
match = self._contrib_rx.search(value)
if match:
values = match.groupdict()
name = values["name"].strip()
email = values["email"].strip()
count = int(values["count"])
else:
name, email, count = ("", "", -1)
return name, email, count
def _get_txt_file_path(self, file_path: Path) -> Path:
path_without_extension = os.path.splitext(file_path)[0]
return Path(path_without_extension + ".contribs.txt")
def _get_contributors_from_txt_file(self, file_path: Path) -> Iterable[Contributor]:
for line in _read_lines_strip_comments(file_path):
name, email, count = self._parse_value(line)
if name and email:
yield Contributor(name, email, count)
def get_contributors(self, file_path: Path) -> list[Contributor]:
"""
Obtains the list of contributors from a txt file with the given path.
The file contents should look like:
Charlie Brown <charlie.brown@peanuts.com> (3)
Having each line with such pattern:
Name <email> (Contributions Count)
and supporting comments using hashes:
# Example comment
"""
txt_path = self._get_txt_file_path(file_path)
if not txt_path.exists():
return []
return list(self._get_contributors_from_txt_file(txt_path))
def get_last_modified_date(self, file_path: Path) -> datetime:
"""Reads the last commit date of a file."""
txt_path = self._get_txt_file_path(file_path)
if not txt_path.exists():
raise FileNotFoundError()
match = self._last_mod_time_rx.search(txt_path.read_text("utf8"))
if match:
return parse(match.groups()[0])
return datetime.min