-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub_word_drawer.py
More file actions
executable file
·539 lines (473 loc) · 15.9 KB
/
Copy pathgithub_word_drawer.py
File metadata and controls
executable file
·539 lines (473 loc) · 15.9 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
#!/usr/bin/env python3
"""
GitHub Word Drawer - Creates commit patterns to draw words on GitHub contribution graph.
This script takes a word as input and creates a new git branch with commits
that form the word pattern on the GitHub contribution graph (7 rows × N columns).
"""
import argparse
import subprocess
import sys
from datetime import datetime, timedelta
from typing import List, Dict
# ASCII art patterns for letters (7 rows high, variable width)
LETTER_PATTERNS = {
'A': [
" ███ ",
"█ █",
"█ █",
"█████",
"█ █",
"█ █",
" "
],
'B': [
"████ ",
"█ █",
"█ █",
"████ ",
"█ █",
"█ █",
"████ "
],
'C': [
" ███ ",
"█ █",
"█ ",
"█ ",
"█ ",
"█ █",
" ███ "
],
'D': [
"████ ",
"█ █",
"█ █",
"█ █",
"█ █",
"█ █",
"████ "
],
'E': [
"█████",
"█ ",
"█ ",
"████ ",
"█ ",
"█ ",
"█████"
],
'F': [
"█████",
"█ ",
"█ ",
"████ ",
"█ ",
"█ ",
"█ "
],
'G': [
" ███ ",
"█ █",
"█ ",
"█ ███",
"█ █",
"█ █",
" ███ "
],
'H': [
"█ █",
"█ █",
"█ █",
"█████",
"█ █",
"█ █",
"█ █"
],
'I': [
"█████",
" █ ",
" █ ",
" █ ",
" █ ",
" █ ",
"█████"
],
'J': [
"█████",
" █",
" █",
" █",
" █",
"█ █",
" ███ "
],
'K': [
"█ █",
"█ █ ",
"█ █ ",
"██ ",
"█ █ ",
"█ █ ",
"█ █"
],
'L': [
"█ ",
"█ ",
"█ ",
"█ ",
"█ ",
"█ ",
"█████"
],
'M': [
"█ █",
"██ ██",
"█ █ █",
"█ █",
"█ █",
"█ █",
"█ █"
],
'N': [
"█ █",
"██ █",
"█ █ █",
"█ ██",
"█ █",
"█ █",
"█ █"
],
'O': [
" ███ ",
"█ █",
"█ █",
"█ █",
"█ █",
"█ █",
" ███ "
],
'P': [
"████ ",
"█ █",
"█ █",
"████ ",
"█ ",
"█ ",
"█ "
],
'Q': [
" ███ ",
"█ █",
"█ █",
"█ █",
"█ █ █",
"█ █ ",
" ████"
],
'R': [
"████ ",
"█ █",
"█ █",
"████ ",
"█ █ ",
"█ █ ",
"█ █"
],
'S': [
" ███ ",
"█ █",
"█ ",
" ███ ",
" █",
"█ █",
" ███ "
],
'T': [
"█████",
" █ ",
" █ ",
" █ ",
" █ ",
" █ ",
" █ "
],
'U': [
"█ █",
"█ █",
"█ █",
"█ █",
"█ █",
"█ █",
" ███ "
],
'V': [
"█ █",
"█ █",
"█ █",
"█ █",
"█ █",
" █ █ ",
" █ "
],
'W': [
"█ █",
"█ █",
"█ █",
"█ █",
"█ █ █",
"██ ██",
"█ █"
],
'X': [
"█ █",
" █ █ ",
" █ ",
" █ ",
" █ ",
" █ █ ",
"█ █"
],
'Y': [
"█ █",
"█ █",
" █ █ ",
" █ ",
" █ ",
" █ ",
" █ "
],
'Z': [
"█████",
" █",
" █ ",
" █ ",
" █ ",
"█ ",
"█████"
],
' ': [
" ",
" ",
" ",
" ",
" ",
" ",
" "
]
}
class GitHubWordDrawer:
def __init__(self, word: str, start_date: str = None, commits_per_date: int = 5):
self.word = word.upper()
self.start_date = self._parse_start_date(start_date)
self.commits_per_date = commits_per_date
def _parse_start_date(self, start_date: str) -> datetime:
"""Parse start date or use a date from one year ago."""
if start_date:
return datetime.strptime(start_date, "%Y-%m-%d")
else:
# Start from a Sunday one year ago to align with GitHub's week start
one_year_ago = datetime.now() - timedelta(days=365)
days_since_sunday = one_year_ago.weekday() + 1
if days_since_sunday == 7:
days_since_sunday = 0
return one_year_ago - timedelta(days=days_since_sunday)
def _create_pattern_grid(self) -> List[List[bool]]:
"""Create a 2D grid representing the commit pattern."""
if not self.word:
return []
# Get patterns for each letter
letter_patterns = []
for char in self.word:
if char in LETTER_PATTERNS:
letter_patterns.append(LETTER_PATTERNS[char])
else:
letter_patterns.append(LETTER_PATTERNS[' ']) # Default to space
# Calculate total width
total_width = sum(len(pattern[0]) for pattern in letter_patterns) + len(letter_patterns) - 1
# Create the grid (7 rows for days of week)
grid = [[False for _ in range(total_width)] for _ in range(7)]
# Fill the grid
col_offset = 0
for pattern in letter_patterns:
pattern_width = len(pattern[0])
for row in range(7):
for col in range(pattern_width):
if pattern[row][col] == '█':
grid[row][col_offset + col] = True
col_offset += pattern_width + 1 # Add spacing between letters
return grid
def _get_commit_dates(self, grid: List[List[bool]]) -> List[datetime]:
"""Convert grid pattern to commit dates."""
commit_dates = []
if not grid or not grid[0]:
return commit_dates
num_weeks = len(grid[0])
for week in range(num_weeks):
for day in range(7): # 0=Sunday, 1=Monday, ..., 6=Saturday
if grid[day][week]:
commit_date = self.start_date + timedelta(weeks=week, days=day)
commit_dates.append(commit_date)
return sorted(commit_dates)
def create_branch(self, branch_name: str = None) -> str:
"""Create a new git branch."""
if not branch_name:
branch_name = f"word-{self.word.lower().replace(' ', '-')}"
try:
# Check if branch exists
result = subprocess.run(['git', 'branch', '--list', branch_name],
capture_output=True, text=True)
if branch_name in result.stdout:
print(f"Branch '{branch_name}' already exists. Switching to it.")
subprocess.run(['git', 'checkout', branch_name], check=True)
else:
subprocess.run(['git', 'checkout', '-b', branch_name], check=True)
print(f"Created and switched to branch '{branch_name}'")
return branch_name
except subprocess.CalledProcessError as e:
print(f"Error creating branch: {e}")
sys.exit(1)
def create_commits(self, commit_dates: List[datetime]):
"""Create commits for each date in the pattern."""
if not commit_dates:
print("No commit dates generated. Check your word pattern.")
return
total_commits = len(commit_dates) * self.commits_per_date
print(f"Creating {total_commits} commits ({self.commits_per_date} per date)...")
# Create a simple file to commit
commit_file = "word_pattern.txt"
commit_counter = 0
for date_idx, commit_date in enumerate(commit_dates):
for commit_num in range(self.commits_per_date):
commit_counter += 1
# Create/update file content
with open(commit_file, 'w') as f:
f.write(f"Commit {commit_counter}/{total_commits} for word: {self.word}\n")
f.write(f"Date: {commit_date.strftime('%Y-%m-%d')}\n")
f.write(f"Commit {commit_num + 1} of {self.commits_per_date} for this date\n")
f.write(f"Drawing pattern on GitHub contribution graph\n")
# Stage the file
subprocess.run(['git', 'add', commit_file], check=True)
# Create commit with specific date and time (spread commits throughout the day)
hours = (commit_num * 24) // self.commits_per_date
minutes = (commit_num * 60) % 60
commit_datetime = commit_date.replace(hour=hours, minute=minutes, second=0)
commit_message = f"Draw '{self.word}' - commit {commit_counter}/{total_commits}"
date_str = commit_datetime.strftime('%Y-%m-%d %H:%M:%S')
env = {
'GIT_AUTHOR_DATE': date_str,
'GIT_COMMITTER_DATE': date_str
}
subprocess.run(['git', 'commit', '-m', commit_message],
env=env, check=True)
print(f"Successfully created {total_commits} commits for '{self.word}'")
def draw_preview(self):
"""Print a preview of how the word will look."""
grid = self._create_pattern_grid()
if not grid:
print("No pattern to display")
return
print(f"\nPreview of '{self.word}' pattern:")
print("=" * (len(grid[0]) + 2))
for row in grid:
line = "|"
for cell in row:
line += "█" if cell else " "
line += "|"
print(line)
print("=" * (len(grid[0]) + 2))
print(f"Pattern size: {len(grid)} rows × {len(grid[0])} columns")
def run(self, preview_only: bool = False):
"""Main execution method."""
print(f"Drawing word: '{self.word}'")
grid = self._create_pattern_grid()
commit_dates = self._get_commit_dates(grid)
self.draw_preview()
if not commit_dates:
print("No commits to create. Exiting.")
return
total_commits = len(commit_dates) * self.commits_per_date
if preview_only:
print(f"Preview mode: Would create {total_commits} commits ({self.commits_per_date} per date)")
return
print(f"\nWill create {total_commits} commits ({self.commits_per_date} per date) starting from {self.start_date.strftime('%Y-%m-%d')}")
response = input("Continue? (y/N): ").strip().lower()
if response != 'y':
print("Cancelled.")
return
branch_name = self.create_branch()
self.create_commits(commit_dates)
print(f"\nDone! Your word '{self.word}' has been drawn on branch '{branch_name}'")
print("Push to GitHub to see the contribution graph pattern.")
@staticmethod
def clear_word_branches():
"""Delete all branches with 'word-' prefix."""
try:
# Get all local branches
result = subprocess.run(['git', 'branch'], capture_output=True, text=True, check=True)
branches = [line.strip().lstrip('* ') for line in result.stdout.splitlines()]
# Filter word- branches
word_branches = [branch for branch in branches if branch.startswith('word-')]
if not word_branches:
print("No word-* branches found to delete.")
return
print(f"Found {len(word_branches)} word-* branches:")
for branch in word_branches:
print(f" - {branch}")
response = input(f"\nDelete all {len(word_branches)} word-* branches? (y/N): ").strip().lower()
if response != 'y':
print("Cancelled.")
return
# Get current branch to avoid deleting it while checked out
current_result = subprocess.run(['git', 'branch', '--show-current'],
capture_output=True, text=True, check=True)
current_branch = current_result.stdout.strip()
# Switch to master/main if currently on a word- branch
if current_branch.startswith('word-'):
# Try master first, then main
try:
subprocess.run(['git', 'checkout', 'master'], check=True, capture_output=True)
print("Switched to master branch")
except subprocess.CalledProcessError:
try:
subprocess.run(['git', 'checkout', 'main'], check=True, capture_output=True)
print("Switched to main branch")
except subprocess.CalledProcessError:
print("Warning: Could not switch to master or main branch")
print("Please manually switch branches before running clear-branches")
return
# Delete branches
deleted_count = 0
for branch in word_branches:
try:
subprocess.run(['git', 'branch', '-D', branch], check=True, capture_output=True)
deleted_count += 1
print(f"Deleted branch: {branch}")
except subprocess.CalledProcessError as e:
print(f"Failed to delete branch {branch}: {e}")
print(f"\nSuccessfully deleted {deleted_count}/{len(word_branches)} word-* branches")
except subprocess.CalledProcessError as e:
print(f"Error clearing branches: {e}")
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description="Draw words on GitHub contribution graph")
parser.add_argument("word", nargs="?", help="Word to draw (letters and spaces only)")
parser.add_argument("--start-date", help="Start date (YYYY-MM-DD), defaults to one year ago")
parser.add_argument("--preview", action="store_true", help="Show preview only, don't create commits")
parser.add_argument("--commits-per-date", type=int, default=5, help="Number of commits per date (default: 5)")
parser.add_argument("--clear-branches", action="store_true", help="Delete all word-* branches and exit")
args = parser.parse_args()
# Handle clear-branches option
if args.clear_branches:
GitHubWordDrawer.clear_word_branches()
return
# Check if word is provided when not using clear-branches
if not args.word:
parser.error("word argument is required unless using --clear-branches")
# Validate word contains only letters and spaces
if not all(c.isalpha() or c.isspace() for c in args.word):
print("Error: Word can only contain letters and spaces")
sys.exit(1)
drawer = GitHubWordDrawer(args.word, args.start_date, args.commits_per_date)
drawer.run(args.preview)
if __name__ == "__main__":
main()