-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto-commit.sh
More file actions
executable file
·1419 lines (1227 loc) · 48.7 KB
/
auto-commit.sh
File metadata and controls
executable file
·1419 lines (1227 loc) · 48.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
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# Auto-commit script with conventional commit messages
# Commits one file at a time with appropriate message based on file type and change
# Automatically updates GitHub token before pushing
# Usage: ./auto-commit.sh [OPTIONS]
# Options:
# -s, --silent Silent mode (no prompts, use defaults or provided args)
# -l, --language LANG Set commit language: en, es, pt (default: en)
# -u, --username USER GitHub username for token updates
# -t, --update-tokens Update GitHub tokens (requires -u)
# -p, --preview Show preview before committing
# -h, --help Show this help message
#
# Examples:
# ./auto-commit.sh -s -l pt -u iago-costa -t
# ./auto-commit.sh --silent --language es --preview
# ./auto-commit.sh -s -l en
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# GitHub username (will be asked if not set)
GITHUB_USERNAME=""
# Commit message language
COMMIT_LANGUAGE="en"
# Script options
SILENT_MODE=false
SHOW_PREVIEW=false
UPDATE_TOKENS_ARG=false
# Common ignore patterns (applied even if not in .gitignore)
COMMON_IGNORE_PATTERNS=(
"node_modules"
".env"
".env.local"
".env.*.local"
"*.log"
".DS_Store"
"Thumbs.db"
"__pycache__"
"*.pyc"
".pytest_cache"
".venv"
"venv"
"dist"
"build"
".idea"
".vscode"
"*.swp"
"*.swo"
".cache"
".tmp"
"tmp"
)
# Function to check if file matches common ignore patterns
is_commonly_ignored() {
local file=$1
for pattern in "${COMMON_IGNORE_PATTERNS[@]}"; do
# Check if file path contains the pattern
if [[ "$file" == *"$pattern"* ]] || [[ "$file" == *"/$pattern/"* ]] || [[ "$file" == "$pattern/"* ]]; then
return 0 # File matches ignore pattern
fi
# Check wildcard patterns
if [[ "$pattern" == *"*"* ]]; then
# Convert pattern to regex-like matching
if [[ "$file" == $pattern ]]; then
return 0
fi
fi
done
return 1 # File doesn't match any ignore pattern
}
# Function to show help
show_help() {
echo "Auto-commit Script - Multi Repository"
echo ""
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " -s, --silent Silent mode (no prompts, use defaults or provided args)"
echo " -l, --language LANG Set commit language: en, es, pt (default: en)"
echo " -u, --username USER GitHub username for token updates"
echo " -t, --update-tokens Update GitHub tokens (requires -u)"
echo " -p, --preview Show preview before committing"
echo " -h, --help Show this help message"
echo ""
echo "Examples:"
echo " $0 -s -l pt -u iago-costa -t"
echo " $0 --silent --language es --preview"
echo " $0 -s -l en"
exit 0
}
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-s|--silent)
SILENT_MODE=true
shift
;;
-l|--language)
COMMIT_LANGUAGE="$2"
shift 2
;;
-u|--username)
GITHUB_USERNAME="$2"
shift 2
;;
-t|--update-tokens)
UPDATE_TOKENS_ARG=true
shift
;;
-p|--preview)
SHOW_PREVIEW=true
shift
;;
-h|--help)
show_help
;;
*)
echo "Unknown option: $1"
echo "Use -h or --help for usage information"
exit 1
;;
esac
done
# Validate language
case "$COMMIT_LANGUAGE" in
en|es|pt)
# Valid language
;;
*)
echo -e "${RED}Error: Invalid language '$COMMIT_LANGUAGE'. Use: en, es, or pt${NC}"
exit 1
;;
esac
# Language templates
declare -A LANG_TEMPLATES=(
["en_add"]="add"
["en_remove"]="remove"
["en_update"]="update"
["en_modify"]="modify"
["en_rename"]="rename"
["es_add"]="agregar"
["es_remove"]="eliminar"
["es_update"]="actualizar"
["es_modify"]="modificar"
["es_rename"]="renombrar"
["pt_add"]="adicionar"
["pt_remove"]="remover"
["pt_update"]="atualizar"
["pt_modify"]="modificar"
["pt_rename"]="renomear"
)
# Function to get action verb in selected language
get_action_verb() {
local action=$1
local key="${COMMIT_LANGUAGE}_${action}"
echo "${LANG_TEMPLATES[$key]}"
}
# Function to install GitHub CLI
install_gh_cli() {
echo -e "${YELLOW}GitHub CLI not found. Installing...${NC}\n"
# Detect OS and architecture
local os=""
local arch=""
local file_ext=""
local download_url=""
# Detect OS
case "$OSTYPE" in
linux-gnu*)
os="linux"
file_ext="tar.gz"
;;
darwin*)
os="macOS"
file_ext="zip"
;;
msys*|cygwin*|win32)
os="windows"
file_ext="zip"
;;
*)
echo -e "${RED}Unsupported OS: $OSTYPE${NC}"
return 1
;;
esac
# Detect architecture
local machine=$(uname -m)
case "$machine" in
x86_64|amd64)
arch="amd64"
;;
aarch64|arm64)
arch="arm64"
;;
i386|i686)
arch="386"
;;
armv7l)
arch="armv6"
;;
*)
echo -e "${RED}Unsupported architecture: $machine${NC}"
return 1
;;
esac
echo -e "${BLUE}Detected: $os ($arch)${NC}"
# Get latest version from GitHub API
echo -e "${BLUE}Fetching latest version...${NC}"
local latest_version=$(curl -s https://api.github.com/repos/cli/cli/releases/latest | grep '"tag_name"' | cut -d'"' -f4 | sed 's/v//')
if [[ -z "$latest_version" ]]; then
echo -e "${YELLOW}Could not fetch latest version, using default${NC}"
latest_version="2.61.0"
fi
echo -e "${GREEN}Latest version: $latest_version${NC}"
# Construct download URL
if [[ "$os" == "windows" ]]; then
download_url="https://github.com/cli/cli/releases/download/v${latest_version}/gh_${latest_version}_windows_${arch}.${file_ext}"
else
download_url="https://github.com/cli/cli/releases/download/v${latest_version}/gh_${latest_version}_${os}_${arch}.${file_ext}"
fi
echo -e "${BLUE}Downloading from: $download_url${NC}\n"
# Create temporary directory
temp_dir=$(mktemp -d)
cd "$temp_dir" || return 1
# Download gh CLI
if command -v wget &> /dev/null; then
wget -q --show-progress "$download_url" -O "gh.$file_ext"
elif command -v curl &> /dev/null; then
curl -L --progress-bar "$download_url" -o "gh.$file_ext"
else
echo -e "${RED}Neither wget nor curl found. Cannot download.${NC}"
cd - > /dev/null
rm -rf "$temp_dir"
return 1
fi
if [[ $? -ne 0 ]]; then
echo -e "${RED}Failed to download GitHub CLI${NC}"
cd - > /dev/null
rm -rf "$temp_dir"
return 1
fi
# Extract based on file type
echo -e "\n${BLUE}Extracting...${NC}"
if [[ "$file_ext" == "tar.gz" ]]; then
tar -xzf "gh.$file_ext"
elif [[ "$file_ext" == "zip" ]]; then
unzip -q "gh.$file_ext"
fi
# Install to ~/.local/bin (user local)
mkdir -p "$HOME/.local/bin"
# Find the gh binary
local gh_binary=$(find . -name "gh" -type f -executable | head -n 1)
if [[ -z "$gh_binary" ]]; then
# Try without executable check (for extracted files)
gh_binary=$(find . -path "*/bin/gh" | head -n 1)
fi
if [[ -z "$gh_binary" ]]; then
echo -e "${RED}Could not find gh binary in extracted files${NC}"
cd - > /dev/null
rm -rf "$temp_dir"
return 1
fi
cp "$gh_binary" "$HOME/.local/bin/"
chmod +x "$HOME/.local/bin/gh"
# Add to PATH if not already there
if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
export PATH="$HOME/.local/bin:$PATH"
# Update shell config files
for rcfile in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.profile"; do
if [[ -f "$rcfile" ]]; then
if ! grep -q "export PATH=\"\$HOME/.local/bin:\$PATH\"" "$rcfile"; then
echo 'export PATH="$HOME/.local/bin:$PATH"' >> "$rcfile"
fi
fi
done
fi
# Cleanup
cd - > /dev/null
rm -rf "$temp_dir"
echo -e "${GREEN}✓ GitHub CLI installed successfully to ~/.local/bin/gh${NC}\n"
return 0
}
# Function to authenticate with GitHub CLI
authenticate_gh() {
echo -e "${YELLOW}GitHub CLI authentication required...${NC}\n"
echo -e "${BLUE}Please follow the prompts to authenticate:${NC}\n"
gh auth login
if [[ $? -eq 0 ]]; then
echo -e "\n${GREEN}✓ Authentication successful${NC}\n"
return 0
else
echo -e "\n${RED}✗ Authentication failed${NC}\n"
return 1
fi
}
# Function to update GitHub token in repository
update_github_token() {
# Skip if gh is not available or user doesn't want to update tokens
if [[ "$GH_AVAILABLE" != true ]] || [[ "$UPDATE_TOKENS" != true ]]; then
return 1
fi
echo -e "${BLUE} → Updating GitHub token...${NC}"
# Check if .git/config exists
if [[ ! -f ".git/config" ]]; then
echo -e "${YELLOW} ⊘ .git/config not found, skipping token update${NC}"
return 1
fi
# Get token from gh CLI
local token=$(gh auth token -h github.com -u "$GITHUB_USERNAME" 2>/dev/null)
if [[ -z "$token" ]]; then
echo -e "${YELLOW} ⊘ Failed to get token from gh CLI, skipping token update${NC}"
return 1
fi
# Update .git/config
local success=false
if grep -q "url = https://$GITHUB_USERNAME:" .git/config 2>/dev/null; then
# Token already exists, replace it
sed -i "s|\($GITHUB_USERNAME:\)[^@]*@|\1$token@|" .git/config
echo -e "${GREEN} ✓ Token updated in .git/config${NC}"
success=true
elif grep -q "url = https://github.com/" .git/config 2>/dev/null; then
# No token yet, add it
sed -i "s|https://github.com/|https://$GITHUB_USERNAME:$token@github.com/|" .git/config
echo -e "${GREEN} ✓ Token added to .git/config${NC}"
success=true
else
echo -e "${YELLOW} ⊘ No GitHub HTTPS URL found in .git/config${NC}"
fi
if [[ "$success" == true ]]; then
return 0
else
return 1
fi
}
# Function to determine commit type based on file extension and change
get_commit_type() {
local file=$1
local status=$2
# Check if file is deleted
if [[ "$status" == "D" ]]; then
echo "chore"
return
fi
# Check file extension
case "$file" in
*.md|*.txt|README*)
echo "docs"
;;
*.sh)
echo "chore"
;;
*.py|*.js|*.ts|*.java|*.c|*.cpp|*.go|*.rs)
if [[ "$status" == "A" ]]; then
echo "feat"
else
echo "refactor"
fi
;;
*.json|*.yaml|*.yml|*.toml|*.xml)
echo "chore"
;;
*.css|*.scss|*.sass)
echo "style"
;;
*.epub|*.pdf|*.mobi|*.kfx|*.djvu)
echo "docs"
;;
*.zip|*.rar|*.7z|*.tar|*.gz|*.bz2)
echo "chore"
;;
*.gns3a|*.gns3|*.unl)
echo "chore"
;;
*.crt|*.key|*.pem)
echo "chore"
;;
*.html)
if [[ "$status" == "A" ]]; then
echo "feat"
else
echo "refactor"
fi
;;
*)
if [[ "$status" == "A" ]]; then
echo "feat"
else
echo "chore"
fi
;;
esac
}
# Function to get scope from file path
get_scope() {
local file=$1
local dir=$(dirname "$file")
# Extract meaningful scope from path
if [[ "$dir" == "." ]]; then
echo ""
else
# Get the most specific directory name
local scope=$(basename "$dir" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')
echo "$scope"
fi
}
# Function to generate subject based on file and action
generate_subject() {
local file=$1
local status=$2
local filename=$(basename "$file")
case "$status" in
A)
echo "$(get_action_verb 'add') $filename"
;;
D)
echo "$(get_action_verb 'remove') $filename"
;;
M)
echo "$(get_action_verb 'update') $filename"
;;
R*)
echo "$(get_action_verb 'rename') $filename"
;;
*)
echo "$(get_action_verb 'modify') $filename"
;;
esac
}
# Function to generate enhanced commit message with file content analysis
generate_enhanced_message() {
local file=$1
local status=$2
local type=$3
local scope=$4
local base_subject=$5
# Check if file exists and is readable
if [[ ! -f "$file" ]] || [[ ! -r "$file" ]]; then
echo "$base_subject"
return
fi
# Get file extension
local ext="${file##*.}"
# For programming language files, analyze code changes
case "$ext" in
py|js|ts|java|c|cpp|go|rs|rb|php|swift|kt|scala)
if [[ "$status" == "M" ]]; then
# Analyze the diff for code changes
local diff_output=$(git diff --cached "$file" 2>/dev/null)
if [[ -n "$diff_output" ]]; then
local added_functions=$(echo "$diff_output" | grep -E "^\+.*\b(function|def|func|fn|class|interface|struct|impl|async|const.*=.*=>)" | wc -l)
local removed_functions=$(echo "$diff_output" | grep -E "^-.*\b(function|def|func|fn|class|interface|struct|impl|async|const.*=.*=>)" | wc -l)
local added_imports=$(echo "$diff_output" | grep -E "^\+.*(import|require|use|include|from.*import)" | wc -l)
local removed_imports=$(echo "$diff_output" | grep -E "^-.*(import|require|use|include|from.*import)" | wc -l)
local added_comments=$(echo "$diff_output" | grep -E "^\+.*(//|#|/\*|\*|\"\"\")" | wc -l)
local additions=$(echo "$diff_output" | grep -c "^+[^+]" || echo "0")
local deletions=$(echo "$diff_output" | grep -c "^-[^-]" || echo "0")
# Build detailed message
local details=""
if [[ $added_functions -gt 0 ]] || [[ $removed_functions -gt 0 ]]; then
case "$COMMIT_LANGUAGE" in
en)
if [[ $added_functions -gt 0 ]]; then
details="add $added_functions function(s)"
fi
if [[ $removed_functions -gt 0 ]]; then
[[ -n "$details" ]] && details="$details, "
details="${details}remove $removed_functions function(s)"
fi
;;
es)
if [[ $added_functions -gt 0 ]]; then
details="agregar $added_functions función(es)"
fi
if [[ $removed_functions -gt 0 ]]; then
[[ -n "$details" ]] && details="$details, "
details="${details}eliminar $removed_functions función(es)"
fi
;;
pt)
if [[ $added_functions -gt 0 ]]; then
details="adicionar $added_functions função(ões)"
fi
if [[ $removed_functions -gt 0 ]]; then
[[ -n "$details" ]] && details="$details, "
details="${details}remover $removed_functions função(ões)"
fi
;;
esac
fi
if [[ $added_imports -gt 0 ]] || [[ $removed_imports -gt 0 ]]; then
case "$COMMIT_LANGUAGE" in
en)
if [[ $added_imports -gt 0 ]]; then
[[ -n "$details" ]] && details="$details, "
details="${details}add $added_imports import(s)"
fi
;;
es)
if [[ $added_imports -gt 0 ]]; then
[[ -n "$details" ]] && details="$details, "
details="${details}agregar $added_imports importación(es)"
fi
;;
pt)
if [[ $added_imports -gt 0 ]]; then
[[ -n "$details" ]] && details="$details, "
details="${details}adicionar $added_imports importação(ões)"
fi
;;
esac
fi
if [[ -n "$details" ]]; then
echo "$base_subject - $details"
else
case "$COMMIT_LANGUAGE" in
en)
echo "$base_subject (+$additions/-$deletions lines)"
;;
es)
echo "$base_subject (+$additions/-$deletions líneas)"
;;
pt)
echo "$base_subject (+$additions/-$deletions linhas)"
;;
esac
fi
return
fi
elif [[ "$status" == "A" ]]; then
# For new code files, analyze content
local functions=$(grep -E "\b(function|def|func|fn|class|interface|struct|impl|async|const.*=.*=>)" "$file" 2>/dev/null | wc -l)
local lines=$(wc -l < "$file" 2>/dev/null || echo "0")
if [[ $functions -gt 0 ]]; then
case "$COMMIT_LANGUAGE" in
en)
echo "$base_subject - $functions function(s), $lines lines"
;;
es)
echo "$base_subject - $functions función(es), $lines líneas"
;;
pt)
echo "$base_subject - $functions função(ões), $lines linhas"
;;
esac
return
else
case "$COMMIT_LANGUAGE" in
en)
echo "$base_subject ($lines lines)"
;;
es)
echo "$base_subject ($lines líneas)"
;;
pt)
echo "$base_subject ($lines linhas)"
;;
esac
return
fi
fi
;;
md|txt|rst|adoc)
# For documentation files
if [[ "$status" == "M" ]]; then
local additions=$(git diff --cached "$file" 2>/dev/null | grep -c "^+[^+]")
local deletions=$(git diff --cached "$file" 2>/dev/null | grep -c "^-[^-]")
if [[ $additions -gt 0 ]] || [[ $deletions -gt 0 ]]; then
case "$COMMIT_LANGUAGE" in
en)
echo "$base_subject (+$additions/-$deletions lines)"
;;
es)
echo "$base_subject (+$additions/-$deletions líneas)"
;;
pt)
echo "$base_subject (+$additions/-$deletions linhas)"
;;
esac
return
fi
elif [[ "$status" == "A" ]]; then
local lines=$(wc -l < "$file" 2>/dev/null || echo "0")
case "$COMMIT_LANGUAGE" in
en)
echo "$base_subject ($lines lines)"
;;
es)
echo "$base_subject ($lines líneas)"
;;
pt)
echo "$base_subject ($lines linhas)"
;;
esac
return
fi
;;
json|yaml|yml|toml|xml)
# For configuration files
if [[ "$status" == "M" ]]; then
local additions=$(git diff --cached "$file" 2>/dev/null | grep -c "^+[^+]")
local deletions=$(git diff --cached "$file" 2>/dev/null | grep -c "^-[^-]")
case "$COMMIT_LANGUAGE" in
en)
echo "$base_subject - update configuration (+$additions/-$deletions)"
;;
es)
echo "$base_subject - actualizar configuración (+$additions/-$deletions)"
;;
pt)
echo "$base_subject - atualizar configuração (+$additions/-$deletions)"
;;
esac
return
fi
;;
esac
# Default: return base subject
echo "$base_subject"
}
# Function to count files to commit in a repository
count_files_to_commit() {
local repo_path=$1
# Get absolute path to repository directory
local repo_dir=$(cd "$(dirname "$repo_path")" 2>/dev/null && pwd)
if [[ -z "$repo_dir" ]] || [[ ! -d "$repo_dir" ]]; then
echo "0"
return
fi
# Change to repository directory
cd "$repo_dir" || return 0
# Get all changed files
local changed_files=$(git status --porcelain)
if [[ -z "$changed_files" ]]; then
return 0
fi
local file_count=0
while IFS= read -r line; do
local status="${line:0:2}"
status=$(echo "$status" | tr -d ' ')
local file="${line:3}"
# Remove surrounding quotes
file="${file#\"}"
file="${file%\"}"
# Skip if file is empty
[[ -z "$file" ]] && continue
# Skip files that match common ignore patterns
if is_commonly_ignored "$file"; then
continue
fi
# Skip files that are ignored by git
if git check-ignore -q "$file" 2>/dev/null; then
continue
fi
# Skip .git directories
if [[ "$file" == ".git"* ]] || [[ "$file" == *"/.git"* ]] || [[ "$file" == *"/.git" ]]; then
continue
fi
# If it's a directory, count files inside
if [[ -d "$file" ]]; then
while IFS= read -r subfile; do
[[ -z "$subfile" ]] && continue
# Skip files inside .git directories
if [[ "$subfile" == *"/.git/"* ]] || [[ "$subfile" == ".git/"* ]]; then
continue
fi
# Skip files that match common ignore patterns
if is_commonly_ignored "$subfile"; then
continue
fi
# Skip files that are ignored by git
if git check-ignore -q "$subfile" 2>/dev/null; then
continue
fi
# Skip files larger than 100MB
local file_size=$(stat -f%z "$subfile" 2>/dev/null || stat -c%s "$subfile" 2>/dev/null)
local max_size=$((100 * 1024 * 1024))
if [[ $file_size -gt $max_size ]]; then
continue
fi
file_count=$((file_count + 1))
done < <(find "$file" -type f -not -path "*/.git/*")
else
# Skip files that match common ignore patterns
if is_commonly_ignored "$file"; then
continue
fi
# Skip files that are ignored by git (single file check)
if git check-ignore -q "$file" 2>/dev/null; then
continue
fi
# Skip files larger than 100MB
if [[ -f "$file" ]]; then
local file_size=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file" 2>/dev/null)
local max_size=$((100 * 1024 * 1024))
if [[ $file_size -gt $max_size ]]; then
continue
fi
fi
file_count=$((file_count + 1))
fi
done <<< "$changed_files"
echo "$file_count"
}
# Function to count commits to push
count_commits_to_push() {
local repo_path=$1
# Get absolute path to repository directory
local repo_dir=$(cd "$(dirname "$repo_path")" 2>/dev/null && pwd)
if [[ -z "$repo_dir" ]] || [[ ! -d "$repo_dir" ]]; then
echo "0"
return
fi
# Change to repository directory
cd "$repo_dir" || return 0
# Check if remote exists
if ! git remote | grep -q .; then
echo "0"
return
fi
# Get current branch
local current_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
if [[ -z "$current_branch" ]]; then
echo "0"
return
fi
# Count unpushed commits
local unpushed=$(git rev-list --count origin/"$current_branch"..HEAD 2>/dev/null)
if [[ -z "$unpushed" ]]; then
echo "0"
else
echo "$unpushed"
fi
}
# Function to add file to git, handling untracked directories
git_add_file() {
local file="$1"
# Try to add the file directly first
if git add -f -- "$file" 2>/dev/null; then
# Verify the file was actually staged
if git diff --cached --name-only | grep -qF "$file"; then
return 0
fi
fi
# If the file is inside an untracked directory tree, we need to find
# the top-level untracked directory and add it instead
# Get the first directory component
local first_dir=$(echo "$file" | cut -d'/' -f1)
# If the file is in a subdirectory, check if the top directory is tracked
if [[ "$file" == *"/"* ]] && [[ -d "$first_dir" ]]; then
# Check if this top-level directory is tracked
if ! git ls-files "$first_dir" | grep -q .; then
# Top directory is completely untracked, add it all at once
if git add -f "$first_dir" 2>/dev/null; then
# Verify our file was staged
if git diff --cached --name-only | grep -qF "$file"; then
return 0
fi
fi
fi
fi
# Try adding parent directories from bottom to top
local parent_dir=$(dirname "$file")
while [[ -n "$parent_dir" ]] && [[ "$parent_dir" != "." ]]; do
# Try adding this directory
if git add -f "$parent_dir" 2>/dev/null; then
# Check if our file was staged
if git diff --cached --name-only | grep -qF "$file"; then
return 0
fi
fi
# Move up one level
parent_dir=$(dirname "$parent_dir")
done
return 1
}
# Function to decode git quoted filenames (handles octal escape sequences)
decode_git_filename() {
local filename="$1"
# If the filename is quoted, remove quotes and decode escape sequences
if [[ "$filename" == \"*\" ]]; then
# Remove surrounding quotes
filename="${filename#\"}"
filename="${filename%\"}"
# Use printf to decode octal sequences like \303\207 (Ç)
# This handles UTF-8 encoded characters
printf '%b' "$filename"
else
# No encoding, return as-is
echo "$filename"
fi
}
# Function to process a single repository
process_repository() {
local repo_path=$1
# Get absolute path to repository directory
local repo_dir=$(cd "$(dirname "$repo_path")" 2>/dev/null && pwd)
if [[ -z "$repo_dir" ]] || [[ ! -d "$repo_dir" ]]; then
echo -e "${RED}✗ Repository directory not found: $repo_path${NC}\n"
return
fi
local repo_name=$(basename "$repo_dir")
echo -e "${GREEN}╔═══════════════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ Repository: ${YELLOW}$repo_name${NC}"
echo -e "${GREEN}║ Path: ${YELLOW}$repo_dir${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════════════════╝${NC}\n"
# Change to repository directory
cd "$repo_dir" || return
# Copy this script to the repository if it doesn't exist or update if it does
local script_name="auto-commit.sh"
local script_source="$original_dir/$script_name"
if [[ -f "$script_source" ]] && [[ "$PWD" != "$original_dir" ]]; then
echo -e "${BLUE} → Copying/updating auto-commit.sh to repository...${NC}"
if [[ -f "$script_name" ]]; then
# Check if files are different
if ! cmp -s "$script_source" "$script_name"; then
cp "$script_source" "$script_name"
chmod +x "$script_name"
# Commit the updated script
if git add -- "$script_name" > /dev/null 2>&1; then
if git commit -m "chore: update auto-commit.sh script" > /dev/null 2>&1; then
echo -e "${GREEN} ✓ Script updated and committed${NC}\n"
else
echo -e "${YELLOW} ⊘ Script updated but not committed (no changes or commit failed)${NC}\n"
fi
else
echo -e "${YELLOW} ⊘ Script updated but not added to git${NC}\n"
fi
else
echo -e "${GREEN} ✓ Script already up to date${NC}\n"
fi
else
# Script doesn't exist, create it
cp "$script_source" "$script_name"
chmod +x "$script_name"
# Commit the new script
if git add -- "$script_name" > /dev/null 2>&1; then
if git commit -m "chore: add auto-commit.sh script" > /dev/null 2>&1; then
echo -e "${GREEN} ✓ Script added and committed${NC}\n"
else
echo -e "${YELLOW} ⊘ Script added but not committed${NC}\n"
fi
else
echo -e "${YELLOW} ⊘ Script added but not added to git${NC}\n"
fi
fi
fi
# Update GitHub token (we're already in the repo directory)
update_github_token
echo ""
# Get all changed files
changed_files=$(git status --porcelain)
if [[ -z "$changed_files" ]]; then
echo -e "${YELLOW}No changes to commit in this repository${NC}\n"
return
fi
# Process each file
local count=0
local committed=0
while IFS= read -r line; do
# Parse git status output
status="${line:0:2}"
status=$(echo "$status" | tr -d ' ')
file="${line:3}"
# Decode git filename (handles quotes and escape sequences like \303\207)
file=$(decode_git_filename "$file")
# Skip if file is empty
[[ -z "$file" ]] && continue