-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
244 lines (204 loc) · 7.6 KB
/
Copy pathmain.py
File metadata and controls
244 lines (204 loc) · 7.6 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
from datetime import timedelta
from datetime import datetime
import argparse
import numpy as np
import subprocess
import math
import cv2
import os
import re
def parse_args():
parser = argparse.ArgumentParser(
description='Print images into your GitHub contributions graph'
)
parser.add_argument(
'--image', '-i',
required=True,
help='Path to source image (7px tall, black/white only)'
)
parser.add_argument(
'--start-date', '-s',
required=True,
help='Start date in YYYY-MM-DD format (must be a Sunday)'
)
parser.add_argument(
'--commits-per-pixel', '-c',
type=int,
default=220,
help='Commits per dark pixel (default: 220)'
)
parser.add_argument(
'--commits-per-blank', '-b',
type=int,
default=0,
help='Commits per blank pixel (default: 0)'
)
parser.add_argument(
'--dry-run', '-n',
action='store_true',
help='Preview without making commits'
)
return parser.parse_args()
def print_preview(img, args, start_date):
"""Print ASCII preview of the contribution graph, chunked by year."""
height, width = img.shape
# Print settings summary
print("Settings:")
print(f" Image: {args.image}")
print(f" Start date: {start_date.strftime('%Y-%m-%d')} ({start_date.strftime('%A')})")
print(f" Commits/pixel: {args.commits_per_pixel}")
print(f" Commits/blank: {args.commits_per_blank}")
print(f" Image dimensions: {width}x{height}")
print()
# Calculate date range
end_date = start_date + timedelta(days=width * 7 - 1)
# Get all years spanned
years = list(range(start_date.year, end_date.year + 1))
print("Preview:")
for year_idx, year in enumerate(years):
year_start = datetime(year, 1, 1)
year_end = datetime(year, 12, 31)
# Find column range for this year
if year_start <= start_date:
first_col = 0
else:
days_diff = (year_start - start_date).days
first_col = days_diff // 7
if year_end >= end_date:
last_col = width - 1
else:
days_diff = (year_end - start_date).days
last_col = days_diff // 7
print(f" {year}:")
for row in range(7):
line = " "
row_has_content = False
for col in range(first_col, last_col + 1):
day_date = start_date + timedelta(days=col * 7 + row)
if year_start <= day_date <= year_end and start_date <= day_date <= end_date:
pixel = img[row][col]
line += "█" if pixel == 255 else "░"
row_has_content = True
else:
line += " "
if row_has_content:
print(line.rstrip())
if year_idx < len(years) - 1:
print()
def confirm_proceed():
"""Ask user to confirm before proceeding."""
response = input("\nProceed? [y/n]: ").strip().lower()
return response in ('y', 'yes')
def calc_total_commits(img, commits_per_pixel, commits_per_blank):
"""Calculate total number of commits needed."""
total = 0
for row in img:
for pixel in row:
total += commits_per_pixel if pixel == 255 else commits_per_blank
return total
def print_progress(current, total, day, total_days, date):
"""Print progress bar with stats."""
bar_width = 30
pct = current / total if total > 0 else 1
filled = int(bar_width * pct)
bar = "█" * filled + "░" * (bar_width - filled)
date_str = date.strftime("%Y-%m-%d")
line = f"\r[{bar}] {pct*100:5.1f}% | Day {day}/{total_days} | {current}/{total} commits | {date_str}"
print(line, end="", flush=True)
def write_progress_log(filename, img, current_day, current_commit, total_commits, total_days, commit_day):
"""Write progress log with ASCII preview showing current position."""
height, width = img.shape
pct = (current_commit / total_commits * 100) if total_commits > 0 else 100
# Current position in image
current_row = current_day % 7
current_col = current_day // 7
lines = []
lines.append(f"Progress: {pct:.1f}%")
lines.append(f"Commits: {current_commit}/{total_commits}")
lines.append(f"Day: {current_day}/{total_days}")
lines.append(f"Date: {commit_day.strftime('%Y-%m-%d')}")
lines.append("")
# ASCII preview with position marker
for row in range(height):
line = ""
for col in range(width):
# Check if this cell has been processed
cell_day = col * 7 + row
if cell_day < current_day:
# Already processed - show the pixel
pixel = img[row][col]
line += "█" if pixel == 255 else "░"
elif cell_day == current_day:
# Current position - mark it
line += "▓"
else:
# Not yet processed
line += "·"
lines.append(line)
with open(filename, 'w') as f:
f.write('\n'.join(lines))
def git_commit_all(message, dry_run):
if dry_run: return
return subprocess.check_output(['git', 'commit', '-am', message])
def git_set_date(date, dry_run):
if dry_run: return
formatted_date = date.strftime("--date=\"%Y.%m.%d %H:%M\"")
return subprocess.check_output(['git', 'commit', '--amend', '--no-edit', formatted_date])
def git_push(dry_run):
if dry_run: return
return subprocess.check_output(['git', 'push'])
def get_number_from_str(inp_str):
num = re.findall(r'\d+', inp_str)
return num[0]
def ind_to_coord(i, w):
return math.floor(i % w), math.floor(i / w)
def main():
args = parse_args()
# Parse start date
start_date = datetime.strptime(args.start_date, '%Y-%m-%d')
img = cv2.imread(args.image, 0)
# Show preview
print_preview(img, args, start_date)
# Handle dry-run or confirmation
if args.dry_run:
print("\n[DRY RUN] No commits will be made")
return
if not confirm_proceed():
print("Aborted.")
return
total_days = len(img) * len(img[0])
total_commits = calc_total_commits(img, args.commits_per_pixel, args.commits_per_blank)
current_day = 0
current_commit = 0
commit_day = start_date
days_since_push = 0
has_unpushed = False
# For each day
for i in range(total_days):
coord = ind_to_coord(current_day, 7)
pixel = img[coord[0]][coord[1]]
commit_number = args.commits_per_pixel if pixel == 255 else args.commits_per_blank
for j in range(commit_number):
current_commit += 1
write_progress_log('log.txt', img, current_day, current_commit, total_commits, total_days, commit_day)
git_commit_all(f'{current_commit}/{total_commits}', args.dry_run)
git_set_date(commit_day, args.dry_run)
print_progress(current_commit, total_commits, current_day + 1, total_days, commit_day)
has_unpushed = True
current_day += 1
commit_day = commit_day + timedelta(days=1)
days_since_push += 1
# Push every 7 days
if days_since_push >= 7 and has_unpushed:
git_push(args.dry_run)
days_since_push = 0
has_unpushed = False
# Final push for any remaining commits
if has_unpushed:
git_push(args.dry_run)
print() # Newline after progress bar
print(f"Done! {current_commit} commits over {total_days} days.")
if __name__ == '__main__':
# Delete any previous contents of log.txt
open('log.txt', 'w').close()
main()