-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_commit_helper.py
More file actions
529 lines (474 loc) · 18.4 KB
/
Copy pathgit_commit_helper.py
File metadata and controls
529 lines (474 loc) · 18.4 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
"""
Author : Hanqing Qi
Date : 2023-11-10 15:15:52
LastEditors : Hanqing Qi
LastEditTime : 2023-11-16 12:26:51
FilePath : /Playground/git_commit_helper.py
Description :
"""
# -*- coding: utf-8 -*-
import subprocess
import curses
import re
import os
import emoji
IGNORED_WORDS = {
"and",
"or",
"but",
"the",
"a",
"in",
"with",
"to",
"of",
"on",
"at",
"from",
"by",
"as",
"for",
"into",
"through",
"during",
"including",
"until",
"against",
"among",
"throughout",
"despite",
"towards",
"upon",
"concerning",
"about",
"like",
"over",
"before",
"between",
"after",
"since",
"without",
"under",
"within",
"along",
"following",
"across",
"behind",
"beyond",
"plus",
"except",
}
EMOJIS = [
"📝 Add Documentation",
"📥 Add",
"🔨 Fix",
"💨 Hotfix",
"🔎 Need Testing",
"🍻 Pass Test",
"📖 Readme",
"🔥 Remove",
"🎉 Start",
"💾 Save",
"🔧 Update",
"🎲 Pass Unit Test",
"🚧 Work in Progress",
"🏗️",
]
# Check if the current directory is a git repository
def is_git_repository():
try:
subprocess.check_output(["git", "rev-parse", "--is-inside-work-tree"])
return True
except subprocess.CalledProcessError:
return False
#helper functions
def process_word_in_backtick(word, processing_words, tick_open, ext_regex):
if re.search(ext_regex, word):
tick_open = False
processing_words.append(word + "`")
else:
processing_words.append(word)
return processing_words, tick_open
def process_word_outside_backtick(word, processed_words, ignored_words, capitalize_mode, idx):
if capitalize_mode == "first" and idx == 0:
processed_words.append(word.capitalize())
elif capitalize_mode == "all":
processed_words.append(word if word.lower() in ignored_words else word.capitalize())
else:
processed_words.append(word.lower())
return processed_words
# Process the code string to match "`" pairs and apply capitalization
def process_code_string(title: str, ignored_words: set = None, capitalize_mode: str = "first") -> str:
if ignored_words is None:
ignored_words = IGNORED_WORDS
words = title.split()
processed_words = []
processing_words = []
tick_open = False
ext_regex = re.compile(r"\.[a-zA-Z0-9]+$") # Regular expression to match file extensions
for idx, word in enumerate(words):
# Check for a starting backtick `
if word.startswith("`"):
if tick_open:
param = processing_words.pop(0)
processed_words.append(param + "`")
for pword in processing_words:
processed_words.append(pword if pword.lower() in ignored_words else pword.capitalize())
processing_words.clear()
tick_open = False
if word.endswith("`"):
processed_words.append(word)
continue
elif re.search(ext_regex, word):
processed_words.append(word + "`")
continue
else:
tick_open = True
processing_words.append(word)
continue
# Check for an ending backtick `
elif word.endswith("`"):
tick_open = False
processing_words.append(word)
for pword in processing_words:
processed_words.append(pword)
processing_words.clear()
continue
if tick_open:
processing_words, tick_open = process_word_in_backtick(word, processing_words, tick_open, ext_regex)
else:
processed_words = process_word_outside_backtick(word, processed_words, ignored_words, capitalize_mode, idx)
# If at the end of the title but tick is still open
if tick_open:
param = processing_words.pop(0)
processed_words.append(param + "`")
for pword in processing_words:
processed_words.append(pword if pword.lower() in ignored_words else pword.capitalize())
processing_words.clear()
# If the capitalization mode is 'first', then add a period at the end if needed
if capitalize_mode == "first" and not processed_words[-1].endswith("."):
processed_words[-1] += "."
return " ".join(processed_words)
# Get directories and files in the current path
def get_directories_and_files(path):
try:
# List directories first, then files
return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))] + [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
except PermissionError:
return []
#helper functions
def clear_menu(stdscr, entries, y):
for i in range(len(entries)):
stdscr.move(y + i, 0)
stdscr.clrtoeol()
stdscr.refresh()
def handle_key_press(key, current_selection, entries, depth):
if key == curses.KEY_UP and current_selection > 0:
return current_selection - 1
elif key == curses.KEY_DOWN and current_selection < len(entries) - 1:
return current_selection + 1
elif key == curses.KEY_RIGHT:
return "dive"
elif key == curses.KEY_LEFT and depth > 0:
return "go_back"
elif key in [10, 13]: # Enter key
return "select"
elif key == 27: # Escape key
return "exit"
# Recursive function to show the file selection menu
def show_menu(stdscr, y, x, base_path, current_path, depth=0):
entries = get_directories_and_files(current_path)
current_selection = 0
color_pair_normal = curses.color_pair(6)
color_pair_selected = curses.color_pair(4) | curses.A_BOLD # Bold text for selected item
while True:
for idx, entry in enumerate(entries):
if idx == current_selection:
stdscr.attron(color_pair_selected)
else:
stdscr.attron(color_pair_normal)
stdscr.addstr(y + idx, x + (depth * 25), entry)
stdscr.attroff(color_pair_selected)
stdscr.attroff(color_pair_normal)
stdscr.refresh()
key = stdscr.getch()
action = handle_key_press(key, current_selection, entries, depth)
if action == current_selection - 1:
current_selection -= 1
elif action == current_selection + 1:
current_selection += 1
elif action == "dive":
new_path = os.path.join(current_path, entries[current_selection])
if os.path.isdir(new_path):
selected = show_menu(stdscr, y, x, base_path, new_path, depth + 1)
if selected:
clear_menu(stdscr, entries, y)
return selected
elif action == "go_back":
clear_menu(stdscr, entries, y)
return None
elif action == "select":
clear_menu(stdscr, entries, y)
return os.path.relpath(os.path.join(current_path, entries[current_selection]), base_path)
elif action == "exit":
clear_menu(stdscr, entries, y)
if depth == 0:
return None
else:
return
# Insert the selected path into the input string
def insert_selected_path(input_str, selected_path, cursor_x, prompt_length):
return (input_str[: cursor_x - prompt_length] + "`" + selected_path + "`" + " " + input_str[cursor_x - prompt_length :]), cursor_x + len(selected_path) + 3
# Menu to prompt the user to select an commit type with emojis
def custom_menu(stdscr, menu_title, menu_items, y=1):
curses.curs_set(0) # Hide cursor
current_selection = 0
color_pair_selected = curses.color_pair(4) | curses.A_BOLD
color_pair_normal = curses.color_pair(6)
while True:
# stdscr.clear()
# Display menu title on the y line
stdscr.attron(curses.color_pair(5))
stdscr.addstr(y, 0, menu_title)
stdscr.attroff(curses.color_pair(5))
for idx, entry in enumerate(menu_items):
if idx == current_selection:
stdscr.attron(color_pair_selected)
else:
stdscr.attron(color_pair_normal)
# Display each menu item below the title
stdscr.addstr(y + idx + 1, 0, entry) # +1 to account for the title line
stdscr.attroff(color_pair_selected)
stdscr.attroff(color_pair_normal)
key = stdscr.getch()
if key == curses.KEY_UP and current_selection > 0:
current_selection -= 1
elif key == curses.KEY_DOWN and current_selection < len(menu_items) - 1:
current_selection += 1
elif key in [curses.KEY_ENTER, ord("\n")]:
# Clear the menu display area
for i in range(len(menu_items) + 1): # +1 to include the title line
stdscr.move(y + i, 0)
stdscr.clrtoeol()
stdscr.refresh()
break # User made a selection
stdscr.refresh()
return menu_items[current_selection]
# Get input from the user
def get_input(stdscr, y, prompt, color_pair, emoji=False):
stdscr.move(y, 0) # Move to the new line for each prompt
max_y, max_x = stdscr.getmaxyx() # Get window dimensions
stdscr.clrtoeol() # Clear the line
stdscr.attron(color_pair)
stdscr.addstr(prompt)
stdscr.attroff(color_pair)
stdscr.refresh()
input_str = ""
if emoji:
commit_type = custom_menu(stdscr, "Select Commit Type: ", EMOJIS)
input_str = commit_type + " " + input_str
cursor_x = len(input_str) + len(prompt)
stdscr.addstr(y, len(prompt), input_str)
else:
cursor_x = len(prompt)
# Show the cursor
curses.curs_set(1)
cursor_line = y
while True:
key = stdscr.getch()
if key in [curses.KEY_BACKSPACE, 127, 8]: # Handle backspace for different terminals
# Delete a character at the cursor position and move cursor left
input_str = input_str[: cursor_x - len(prompt) - 1] + input_str[cursor_x - len(prompt) :]
cursor_x -= 1
elif key == curses.KEY_LEFT:
cursor_x = max(len(prompt), cursor_x - 1)
elif key == curses.KEY_RIGHT:
cursor_x = min(len(prompt) + len(input_str), cursor_x + 1)
elif 32 <= key <= 126:
char = chr(key)
input_str = input_str[: cursor_x - len(prompt)] + char + input_str[cursor_x - len(prompt) :]
cursor_x += 1
elif key == curses.KEY_DOWN:
# Open the menu at the current directory
base_path = os.getcwd() # Store the base path
selected_option = show_menu(stdscr, cursor_line + 1, 0, base_path, base_path)
if selected_option:
input_str, cursor_x = insert_selected_path(input_str, selected_option, cursor_x, len(prompt))
elif key == 10: # Enter key
break
# Improved Cursor Position Calculation and Movement
cursor_line_offset = (cursor_x + (1 if emoji else 0)) // max_x # Calculate how many lines the cursor has moved down
cursor_line = y + cursor_line_offset # Calculate the new cursor line
cursor_column = (cursor_x + (1 if emoji else 0)) % max_x # Calculate the cursor's column
# Clear necessary lines
for i in range(y, cursor_line + 1):
stdscr.move(i, 0)
stdscr.clrtoeol()
# Redraw prompt and input
stdscr.move(y, 0)
stdscr.attron(color_pair)
stdscr.addstr(prompt)
stdscr.attroff(color_pair)
stdscr.addstr(input_str)
# Ensure cursor is within bounds
cursor_line = min(cursor_line, max_y - 1) # Ensure cursor does not go beyond the last line
cursor_column = min(cursor_column, max_x - 1) # Ensure cursor does not go beyond the last column
# Move the cursor to the calculated position
stdscr.move(cursor_line, cursor_column)
stdscr.refresh()
# try:
# stdscr.move(y, cursor_x + 1 if emoji else cursor_x) # Move the cursor to the correct position with emoji offset
# except curses.error:
# stdscr.move(y + 1, cursor_x + 1 - max_x if emoji else cursor_x - max_x)
return input_str.strip(), cursor_line
# Run a git command and display the output
def run_git_command(stdscr, command):
try:
# Run the Git command
result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# Display the success message along with any output from the command
# stdscr.attron(curses.color_pair(2)) # Assuming color_pair(2) is for success messages
curses.use_default_colors()
if result.stdout:
stdscr.move(stdscr.getyx()[0] + 1, 0)
stdscr.addstr(result.stdout)
if result.stderr:
stdscr.move(stdscr.getyx()[0] + 1, 0)
stdscr.addstr(result.stderr)
# stdscr.attroff(curses.color_pair(2))
stdscr.refresh()
# stdscr.getch()
return True
except subprocess.CalledProcessError as e:
# Handle errors specifically from the subprocess
stdscr.attron(curses.color_pair(3)) # Assuming color_pair(3) is for error messages
stdscr.move(stdscr.getyx()[0] + 1, 0)
stdscr.addstr("\nGit command failed: ")
stdscr.addstr("Error - " + str(e.stderr))
stdscr.attroff(curses.color_pair(3))
stdscr.refresh()
# stdscr.getch()
return False
except Exception as e:
# Handle other exceptions
stdscr.attron(curses.color_pair(3)) # Assuming color_pair(3) is for error messages
stdscr.move(stdscr.getyx()[0] + 1, 0)
stdscr.addstr("\nUnexpected error occurred:")
stdscr.addstr(str(e))
stdscr.attroff(curses.color_pair(3))
stdscr.refresh()
# stdscr.getch()
return False
# The main function
def main(stdscr, prompts, confirmations):
# check if the current directory is a git repository
if not is_git_repository():
raise Exception("Not a git repository")
# Initialize colors
curses.use_default_colors()
if curses.has_colors():
curses.start_color()
curses.init_pair(1, 3, 8) # Yellow
curses.init_pair(2, 2, 8) # Green
curses.init_pair(3, 1, 8) # Red
curses.init_pair(4, 9, 8) # Orange
curses.init_pair(5, 4, 8) # Purple
curses.init_pair(6, -1, 8) # White
color_pair = curses.color_pair(1)
else:
raise Exception("Terminal does not support color")
# Get inputs for all prompts
responses = []
y = 0 # Start at the top of the screen
for prompt in prompts:
response, new_y = get_input(stdscr, y, prompt, color_pair, True if y == 0 else False)
if response == "":
response = "-"
responses.append(response)
y += (new_y + 1) # Move to the next line for the next prompt
# Optionally, display all the entered texts after the inputs
# stdscr.clear()
responses[0] = process_code_string(responses[0], capitalize_mode="all")
responses[1] = process_code_string(responses[1])
for i, response in enumerate(responses):
# Apply green color to the prompt
stdscr.attron(curses.color_pair(2))
stdscr.addstr(i + y, 0, confirmations[i])
stdscr.attroff(curses.color_pair(2))
# Print the response in the default color
stdscr.addstr(response + "\n")
# Check if user wants to commit the changes
stdscr.attron(curses.color_pair(5))
stdscr.addstr("Commit these changes? (y/n): ")
stdscr.attroff(curses.color_pair(5))
stdscr.refresh()
terminated = False
while True:
commit_key = stdscr.getch()
if commit_key in [ord("y"), ord("Y")]:
# Add all files to the staging area
add_command = ["git", "add", "."]
result = run_git_command(stdscr, add_command)
# result = True
if not result:
return
# Run the git commit command
commit_command = ["git", "commit", "-m", responses[0], "-m", responses[1]]
result = run_git_command(stdscr, commit_command)
# result = True
if not result:
return
stdscr.attron(curses.color_pair(2))
stdscr.addstr("\nChanges committed successfully.")
stdscr.attroff(curses.color_pair(2))
stdscr.refresh()
# Now ask for push
stdscr.attron(curses.color_pair(5))
stdscr.addstr("\nPush the committed changes? (y/n): ")
stdscr.attroff(curses.color_pair(5))
stdscr.refresh()
while True:
terminated = True
push_key = stdscr.getch()
if push_key in [ord("y"), ord("Y")]:
# User wants to push
# Run the git push command
push_command = ["git", "push"]
result = run_git_command(stdscr, push_command)
# result = True
if not result:
return
stdscr.attron(curses.color_pair(2))
stdscr.addstr("\nChanges pushed successfully.")
stdscr.attroff(curses.color_pair(2))
break
elif push_key in [ord("n"), ord("N")]:
# User does not want to commit
stdscr.attron(curses.color_pair(3))
stdscr.addstr("\nOperation cancelled by the user.")
stdscr.attroff(curses.color_pair(3))
break
else:
# Invalid key
continue
elif commit_key in [ord("n"), ord("N")]:
# User does not want to commit
stdscr.attron(curses.color_pair(3))
stdscr.addstr("\nOperation cancelled by the user.")
stdscr.attroff(curses.color_pair(3))
break
else:
# Invalid key
if terminated and (commit_key in [10, 13] or commit_key == curses.KEY_ENTER):
break
continue
stdscr.refresh()
try:
prompts = ["Enter commit title: ", "Enter commit message: "]
confirmations = ["Commit title: ", "Commit message: "]
curses.wrapper(main, prompts, confirmations)
print("\033[32m" + "\nSuccess." + "\033[0m")
except KeyboardInterrupt:
print("\033[31m" + "\nOperation cancelled by the user." + "\033[0m")
except Exception as e:
print("\033[31m" + "\n" + str(e) + "\033[0m")