Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
226 lines (181 loc) · 6.77 KB
/
Copy pathmain.py
File metadata and controls
226 lines (181 loc) · 6.77 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
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
import os
import sys
import locale
import pygit2
import readchar
import subprocess
from urllib.parse import quote
from rich.markup import escape
from rich.console import Console
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo, available_timezones
console = Console(highlight=False, soft_wrap=True)
timezones = {zone.lower(): zone for zone in available_timezones()}
time_format_str = os.getenv("TIME_FORMAT", "local")
if time_format_str.lower() == "original":
locale.setlocale(locale.LC_TIME, "POSIX")
elif time_format_str.lower() == "local":
locale.setlocale(locale.LC_TIME, "")
else:
try:
locale.setlocale(locale.LC_TIME, time_format_str)
except Exception as e:
console.print(f"[red]Error:[/red] {escape(str(e))}")
format = "language[_territory][.codeset][@modifier]"
setlocale_man_page = f"https://man7.org/linux/man-pages/man3/setlocale.3.html"
console.print(
f'TIME_FORMAT must be [green]"local"[/green] | [green]"original"[/green] | [green]"{escape(format)}"[/green]\n'
f"See [cyan][link={setlocale_man_page}#:~:text={quote(format)}]{setlocale_man_page}#:~:text={escape(format)}[/link][/cyan]"
)
sys.exit(1)
time_zone_str = os.getenv("TIME_ZONE", "original")
time_zone_str_lower = time_zone_str.lower()
if time_zone_str_lower == "original":
def date_time_string(epoch, offset):
dt = datetime.fromtimestamp(epoch, timezone(timedelta(minutes=offset)))
return dt.strftime("%c %z")
elif time_zone_str_lower == "local":
def date_time_string(epoch, offset):
dt = datetime.fromtimestamp(epoch, timezone(timedelta(minutes=offset)))
return dt.astimezone().strftime("%c %z")
else:
try:
time_zone_exact_case = (
timezones[time_zone_str_lower]
if time_zone_str_lower in timezones
else time_zone_str
)
time_zone = ZoneInfo(time_zone_exact_case)
except Exception as e:
console.print(f"[red]Error:[/red] {escape(str(e)[1:-1])}")
tz_db_wiki = "https://en.wikipedia.org/wiki/List_of_tz_database_time_zones"
console.print(
f'TIME_ZONE must be [green]"original"[/green] | [green]"local"[/green] | [cyan]IANA Time Zone Identifier[/cyan]\n'
f"See [cyan][link={tz_db_wiki}]{tz_db_wiki}[/link][/cyan]"
)
sys.exit(1)
def date_time_string(epoch, offset):
dt = datetime.fromtimestamp(epoch, timezone(timedelta(minutes=offset)))
return dt.astimezone(time_zone).strftime("%c %z")
def main():
dir = sys.argv[1] if len(sys.argv) > 1 else "."
list_all = os.getenv("LIST_ALL", "0") == "1"
try:
if dir != ".":
os.chdir(dir)
except Exception as e:
console.print(f"[red]Error:[/red] {escape(e.strerror)}: {escape(e.filename)}")
return
discovered_repo = pygit2.discover_repository(".")
if not discovered_repo:
console.print(
f"[red]Error:[/red] No git repository found at {escape(os.getcwd())} or any parent directory"
)
return
repo = pygit2.Repository(discovered_repo)
commit = None
try:
commit = repo.head.peel()
except Exception as e:
console.print(f"[red]Error:[/red] {escape(str(e))}")
return
try:
min_hash_len = len(
subprocess.check_output(
["git", "rev-parse", "--short", "HEAD"], text=True
).strip()
)
except Exception as e:
console.print(f"[red]Error:[/red] Unable to run git command. Is git installed?")
return
name = None
email = None
try:
name = subprocess.check_output(
["git", "config", "user.name"], text=True
).strip()
except Exception as e:
pass
try:
email = subprocess.check_output(
["git", "config", "user.email"], text=True
).strip()
except Exception as e:
pass
def show_commit(c):
message = c.message.strip().splitlines()
lines = []
lines.append((escape(f"[{str(c.id)[:min_hash_len]}]"), escape(message[0])))
author_name = (
f"[yellow]{escape(c.author.name)}[/yellow]"
if c.author.name == name
else escape(c.author.name)
)
author_email = (
f"[yellow]{escape(c.author.email)}[/yellow]"
if c.author.email == email
else escape(c.author.email)
)
committer_name = (
f"[yellow]{escape(c.committer.name)}[/yellow]"
if c.committer.name == name
else escape(c.committer.name)
)
committer_email = (
f"[yellow]{escape(c.committer.email)}[/yellow]"
if c.committer.email == email
else escape(c.committer.email)
)
lines.append(("[green]Author:[/green]", f"{author_name} <{author_email}>"))
lines.append(
(
"[green]Author Date:[/green]",
escape(date_time_string(c.author.time, c.author.offset)),
)
)
if c.author.name != c.committer.name or c.author.email != c.committer.email:
lines.append(
("[red]Committer:[/red]", f"{committer_name} <{committer_email}>")
)
if c.author.time != c.committer.time or c.author.offset != c.committer.offset:
lines.append(
(
"[red]Committer Date:[/red]",
escape(date_time_string(c.committer.time, c.committer.offset)),
)
)
max_key_len = max(15, min_hash_len + 2)
for key, value in commit.message_trailers.items():
lines.append((f"[blue]{escape(key)}:[/blue]", escape(value)))
max_key_len = max(max_key_len, len(key) + 1)
for key, value in lines:
spaces = " " * (max_key_len - console.measure(key).maximum)
console.print(f"{key}{spaces} {value}")
print()
print()
show_commit(commit)
try:
if list_all:
while True:
parents = commit.parent_ids
if parents:
commit = repo[parents[0]]
show_commit(commit)
else:
break
else:
while True:
key = readchar.readkey()
if key in (readchar.key.DOWN, readchar.key.SPACE, readchar.key.ENTER):
parents = commit.parent_ids
if parents:
commit = repo[parents[0]]
show_commit(commit)
else:
break
elif key == readchar.key.ESC:
break
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()