-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitbuilder
More file actions
6874 lines (5896 loc) · 237 KB
/
gitbuilder
File metadata and controls
6874 lines (5896 loc) · 237 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
# GitBuilder - GitHub repository management and build automation tool
# Author: Cascade
# Prompt Engineer: VR51
# Version: 2.0.2
# Created: 2025-04-11
# Updated: 2025-12-07
# License: GNU General Public License v3.0
# Donate: https://paypal.me/vr51/
#
# Copyright (C) 2025 VR51
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
set -euo pipefail
set -o noclobber # Prevent accidental file overwrites
IFS=$'\n\t'
# Fix backspace/delete key handling in read prompts
stty erase '^?' 2>/dev/null || true
# =============================================================================
# VERSION AND HELP
# =============================================================================
VERSION="2.0.2"
GITHUB_REPO="https://github.com/vr51/GitBuilder"
show_help() {
# Read help from HELP file if it exists, otherwise show basic help
local help_file="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/HELP"
if [ -f "$help_file" ]; then
# Show the quick reference section (up to the detailed sections)
sed -n '1,/^=.*HELP SECTIONS INDEX/p' "$help_file" | head -n -1
echo ""
echo "For detailed help, run: gitbuilder (then press H)"
echo "Or view the full HELP file: less $help_file"
else
cat << EOF
GitBuilder v${VERSION} - GitHub repository management and build automation tool
Usage: $(basename "$0") [OPTIONS]
Options:
-h, --help Show this help message and exit
-v, --version Show version information
-l, --list List all repositories and exit
-b, --build ID Build repository with given ID
-u, --update Update all repository commit dates
--backup FILE Backup database to FILE
--restore FILE Restore database from FILE
--check-update Check for GitBuilder updates
Examples:
$(basename "$0") # Start interactive mode
$(basename "$0") -l # List repositories
$(basename "$0") -b 1 # Build repository ID 1
$(basename "$0") --backup ~/backup.sql
Environment Variables:
GITBUILDER_JOBS Number of parallel build jobs (default: auto-detect)
EDITOR Preferred text editor for notes
For more information, see: $GITHUB_REPO
EOF
fi
}
show_version() {
echo "GitBuilder v${VERSION}"
echo "Copyright (C) 2025 VR51"
echo "License: GNU GPL v3.0"
}
# Parse command line arguments early (before any initialization)
parse_early_args() {
case "${1:-}" in
-h|--help)
show_help
exit 0
;;
-v|--version)
show_version
exit 0
;;
esac
}
# Check for help/version before anything else
parse_early_args "$@"
# Required commands and their corresponding packages
declare -A REQUIRED_PACKAGES=(
[sqlite3]="sqlite3"
[curl]="curl"
[jq]="jq"
[git]="git"
[make]="make"
[cmake]="cmake"
[file]="file"
[ccache]="ccache"
)
# Configuration
DB_DIR="$HOME/.local/share/gitbuilder"
DB_FILE="$DB_DIR/repos.db"
SRC_DIR="$HOME/.local/share/gitbuilder/src"
GITHUB_API="https://api.github.com"
# Build optimization: detect CPU cores for parallel builds
# Use all cores by default, can be overridden by setting GITBUILDER_JOBS
CPU_CORES=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)
# Ensure we have a valid number, default to 4 if detection fails
[[ ! "$CPU_CORES" =~ ^[0-9]+$ ]] && CPU_CORES=4
PARALLEL_JOBS="${GITBUILDER_JOBS:-$CPU_CORES}"
[[ ! "$PARALLEL_JOBS" =~ ^[0-9]+$ || "$PARALLEL_JOBS" -lt 1 ]] && PARALLEL_JOBS=4
export PARALLEL_JOBS
# RAM disk configuration
RAMDISK_DIR="$HOME/.local/share/gitbuilder/ramdisk"
RAMDISK_MOUNT_POINT="$RAMDISK_DIR/build"
RAMDISK_MIN_FREE_MB=2048 # Minimum free RAM required (2GB)
RAMDISK_ACTIVE=false
# Gitbuildfiles directory (relative to script location)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
GITBUILDFILES_DIR="$SCRIPT_DIR/gitbuildfiles"
HELP_FILE="$SCRIPT_DIR/HELP"
# Additional directories
BUILD_HISTORY_DIR="$DB_DIR/history"
BUILD_PROFILES_DIR="$DB_DIR/profiles"
BINARY_BACKUPS_DIR="$DB_DIR/binary_backups"
DESKTOP_LAUNCHERS_DIR="$HOME/.local/share/applications"
PLUGINS_DIR="$SCRIPT_DIR/plugins"
# Binary backup configuration
BINARY_BACKUP_LIMIT=3 # Maximum backups per repository
CONFIG_FILE="$DB_DIR/config"
BACKUP_DIR="$DB_DIR/backups"
# GitBuilder's own desktop launcher
GITBUILDER_DESKTOP_FILE="$DESKTOP_LAUNCHERS_DIR/gitbuilder.desktop"
GITBUILDER_LAUNCHER_EXISTS=false
# Ensure directories exist
mkdir -p "$DB_DIR" "$SRC_DIR" "$GITBUILDFILES_DIR" "$BUILD_HISTORY_DIR" "$BUILD_PROFILES_DIR" "$BINARY_BACKUPS_DIR" "$PLUGINS_DIR" "$BACKUP_DIR"
# Set secure permissions on database directory
chmod 700 "$DB_DIR" 2>/dev/null || true
# =============================================================================
# THEME SYSTEM
# =============================================================================
# Default theme (can be overridden in config file)
THEME="default"
# Theme definitions
declare -A THEME_DEFAULT=(
[RED]='\033[0;31m'
[GREEN]='\033[0;32m'
[YELLOW]='\033[1;33m'
[BLUE]='\033[0;34m'
[CYAN]='\033[0;36m'
[MAGENTA]='\033[0;35m'
[WHITE]='\033[1;37m'
[GRAY]='\033[0;90m'
[NC]='\033[0m'
)
declare -A THEME_OCEAN=(
[RED]='\033[38;5;203m'
[GREEN]='\033[38;5;114m'
[YELLOW]='\033[38;5;221m'
[BLUE]='\033[38;5;39m'
[CYAN]='\033[38;5;87m'
[MAGENTA]='\033[38;5;141m'
[WHITE]='\033[38;5;255m'
[GRAY]='\033[38;5;245m'
[NC]='\033[0m'
)
declare -A THEME_FOREST=(
[RED]='\033[38;5;167m'
[GREEN]='\033[38;5;71m'
[YELLOW]='\033[38;5;179m'
[BLUE]='\033[38;5;67m'
[CYAN]='\033[38;5;73m'
[MAGENTA]='\033[38;5;139m'
[WHITE]='\033[38;5;253m'
[GRAY]='\033[38;5;243m'
[NC]='\033[0m'
)
declare -A THEME_MONO=(
[RED]='\033[1;37m'
[GREEN]='\033[1;37m'
[YELLOW]='\033[1;37m'
[BLUE]='\033[0;37m'
[CYAN]='\033[0;37m'
[MAGENTA]='\033[0;37m'
[WHITE]='\033[1;37m'
[GRAY]='\033[0;90m'
[NC]='\033[0m'
)
# Apply theme
apply_theme() {
local theme_name="${1:-default}"
local -n theme_ref
case "$theme_name" in
ocean) theme_ref=THEME_OCEAN ;;
forest) theme_ref=THEME_FOREST ;;
mono) theme_ref=THEME_MONO ;;
*) theme_ref=THEME_DEFAULT ;;
esac
RED="${theme_ref[RED]}"
GREEN="${theme_ref[GREEN]}"
YELLOW="${theme_ref[YELLOW]}"
BLUE="${theme_ref[BLUE]}"
CYAN="${theme_ref[CYAN]}"
MAGENTA="${theme_ref[MAGENTA]:-\033[0;35m}"
WHITE="${theme_ref[WHITE]:-\033[1;37m}"
GRAY="${theme_ref[GRAY]:-\033[0;90m}"
NC="${theme_ref[NC]}"
}
# Load configuration file
load_config() {
if [ -f "$CONFIG_FILE" ]; then
# shellcheck source=/dev/null
source "$CONFIG_FILE"
fi
apply_theme "$THEME"
}
# Save configuration
save_config() {
cat >| "$CONFIG_FILE" << EOF
# GitBuilder Configuration File
# Generated: $(date -Iseconds)
# Theme: default, ocean, forest, mono
THEME="$THEME"
# Auto-update check interval (days, 0 to disable)
AUTO_UPDATE_CHECK_DAYS="${AUTO_UPDATE_CHECK_DAYS:-7}"
# Desktop notifications (true/false)
NOTIFICATIONS_ENABLED="${NOTIFICATIONS_ENABLED:-true}"
# Default build profile
DEFAULT_PROFILE="${DEFAULT_PROFILE:-}"
# Build queue auto-start (true/false)
BUILD_QUEUE_AUTOSTART="${BUILD_QUEUE_AUTOSTART:-false}"
# Preferred text editor for notes
PREFERRED_EDITOR="${PREFERRED_EDITOR:-}"
EOF
chmod 600 "$CONFIG_FILE"
}
# Get preferred editor
get_editor() {
# Check if user has set a preferred editor
if [ -n "${PREFERRED_EDITOR:-}" ] && command -v "$PREFERRED_EDITOR" >/dev/null 2>&1; then
echo "$PREFERRED_EDITOR"
return 0
fi
# Check common editors in order of preference
local editors=("nano" "vim" "vi" "emacs" "gedit" "kate" "code" "subl")
for editor in "${editors[@]}"; do
if command -v "$editor" >/dev/null 2>&1; then
echo "$editor"
return 0
fi
done
# No editor found
echo ""
}
# List installed editors
list_installed_editors() {
local editors=("nano" "vim" "vi" "emacs" "micro" "ne" "joe" "gedit" "kate" "xed" "pluma" "mousepad" "code" "subl" "atom")
local installed=()
for editor in "${editors[@]}"; do
if command -v "$editor" >/dev/null 2>&1; then
installed+=("$editor")
fi
done
echo "${installed[@]}"
}
# Change editor preference
change_editor() {
local current_editor
current_editor=$(get_editor)
echo -e "\n${BLUE}Text Editor Settings${NC}"
echo "============================================"
echo -e "Current editor: ${GREEN}${current_editor:-none}${NC}"
echo -e "Preferred editor: ${CYAN}${PREFERRED_EDITOR:-auto-detect}${NC}"
echo ""
# List installed editors
echo -e "${YELLOW}Installed editors:${NC}"
local installed
installed=$(list_installed_editors)
if [ -z "$installed" ]; then
echo -e "${RED}No text editors found!${NC}"
else
local i=1
for editor in $installed; do
if [ "$editor" = "$current_editor" ]; then
echo -e " $i) ${GREEN}$editor${NC} (current)"
else
echo " $i) $editor"
fi
((i++))
done
fi
echo ""
echo "============================================"
echo ""
echo "Options:"
echo " Enter editor name to set as preferred"
echo " Enter 'auto' to use auto-detection"
echo " Enter 'install' to install nano"
echo " Press Enter to cancel"
echo ""
read -rp "Choice: " choice
case "$choice" in
"")
echo -e "${YELLOW}Cancelled${NC}"
;;
auto)
PREFERRED_EDITOR=""
save_config
success "Editor set to auto-detect"
;;
install)
if install_packages nano; then
if command -v nano >/dev/null 2>&1; then
PREFERRED_EDITOR="nano"
save_config
success "nano installed and set as preferred editor"
else
error "Failed to install nano"
fi
fi
;;
*)
if command -v "$choice" >/dev/null 2>&1; then
PREFERRED_EDITOR="$choice"
save_config
success "Preferred editor set to: $choice"
else
error "Editor '$choice' not found. Please install it first."
fi
;;
esac
read -rp "Press Enter to continue..."
}
# Initialize config with defaults if not exists
[ ! -f "$CONFIG_FILE" ] && save_config
# Load configuration
load_config
# ANSI color codes (set by theme, these are fallback defaults)
RED="${RED:-\033[0;31m}"
GREEN="${GREEN:-\033[0;32m}"
YELLOW="${YELLOW:-\033[1;33m}"
BLUE="${BLUE:-\033[0;34m}"
CYAN="${CYAN:-\033[0;36m}"
NC="${NC:-\033[0m}"
# Check for required commands and offer to install missing ones
check_requirements() {
local missing=0
local missing_pkgs=()
for cmd in "${!REQUIRED_PACKAGES[@]}"; do
if ! command -v "$cmd" >/dev/null 2>&1; then
echo -e "${YELLOW}Missing command: $cmd${NC}"
missing_pkgs+=("${REQUIRED_PACKAGES[$cmd]}")
missing=1
fi
done
if [ $missing -eq 1 ]; then
echo -e "\nThe following packages need to be installed:"
printf '%s\n' "${missing_pkgs[@]}"
read -rp "Would you like to install them now? (y/N): " choice
if [[ $choice =~ ^[Yy]$ ]]; then
install_packages "${missing_pkgs[@]}"
else
error "Required packages must be installed to continue."
fi
fi
}
# Check for and install build dependencies
check_build_dependencies() {
local repo_id="$1"
local dependencies
# Get dependencies from database
dependencies=$(sqlite3 "$DB_FILE" "SELECT dependencies FROM build_configs WHERE repo_id = $repo_id;")
if [ -z "$dependencies" ]; then
return 0 # No dependencies specified
fi
echo -e "\n${BLUE}Checking build dependencies...${NC}"
# Convert space-separated string to array
IFS=' ' read -r -a deps_array <<< "$dependencies"
local missing=0
local missing_deps=()
# Check each dependency
for dep in "${deps_array[@]}"; do
if ! dpkg -l | grep -q "$dep"; then
echo -e "${YELLOW}Missing dependency: $dep${NC}"
missing_deps+=("$dep")
missing=1
else
echo -e "${GREEN}Dependency found: $dep${NC}"
fi
done
if [ $missing -eq 1 ]; then
echo -e "\nThe following dependencies need to be installed:"
printf '%s\n' "${missing_deps[@]}"
read -rp "Would you like to install them now? (y/N): " choice
if [[ $choice =~ ^[Yy]$ ]]; then
if install_packages "${missing_deps[@]}"; then
echo -e "${GREEN}Dependencies installed successfully${NC}"
else
return 1
fi
else
echo -e "${YELLOW}Warning: Missing dependencies may cause build to fail${NC}"
read -rp "Continue anyway? (y/N): " continue_choice
if [[ ! $continue_choice =~ ^[Yy]$ ]]; then
return 1
fi
fi
else
echo -e "${GREEN}All dependencies are installed${NC}"
fi
return 0
}
# Initialize SQLite database
init_db() {
# Drop the old table if it exists (only during initialization)
if [ ! -f "$DB_FILE" ]; then
sqlite3 "$DB_FILE" "DROP TABLE IF EXISTS repositories;"
sqlite3 "$DB_FILE" "DROP TABLE IF EXISTS build_configs;"
fi
# Create the repositories table
sqlite3 "$DB_FILE" <<EOF
CREATE TABLE IF NOT EXISTS repositories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
url TEXT NOT NULL,
last_commit TEXT,
last_commit_check TEXT,
last_built TEXT,
build_success INTEGER,
binary_path TEXT,
build_type TEXT,
build_file_path TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
deleted INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS build_configs (
repo_id INTEGER,
configure_flags TEXT,
make_flags TEXT,
cmake_flags TEXT,
dependencies TEXT,
strip_debug INTEGER DEFAULT 0,
use_ramdisk INTEGER DEFAULT 0,
FOREIGN KEY(repo_id) REFERENCES repositories(id)
);
CREATE TABLE IF NOT EXISTS repository_notes (
repo_id INTEGER PRIMARY KEY,
notes TEXT,
FOREIGN KEY(repo_id) REFERENCES repositories(id)
);
CREATE TABLE IF NOT EXISTS build_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER,
started_at TEXT DEFAULT CURRENT_TIMESTAMP,
finished_at TEXT,
success INTEGER,
duration_seconds INTEGER,
download_seconds INTEGER,
compile_seconds INTEGER,
download_size_bytes INTEGER,
log_file TEXT,
build_profile TEXT,
FOREIGN KEY(repo_id) REFERENCES repositories(id)
);
CREATE TABLE IF NOT EXISTS build_profiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE NOT NULL,
description TEXT,
configure_flags TEXT,
make_flags TEXT,
cmake_flags TEXT,
strip_debug INTEGER DEFAULT 0,
use_ramdisk INTEGER DEFAULT 0,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS build_queue (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER,
profile_id INTEGER,
priority INTEGER DEFAULT 0,
status TEXT DEFAULT 'pending',
added_at TEXT DEFAULT CURRENT_TIMESTAMP,
started_at TEXT,
FOREIGN KEY(repo_id) REFERENCES repositories(id),
FOREIGN KEY(profile_id) REFERENCES build_profiles(id)
);
CREATE TABLE IF NOT EXISTS repo_dependencies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER,
depends_on_repo_id INTEGER,
FOREIGN KEY(repo_id) REFERENCES repositories(id),
FOREIGN KEY(depends_on_repo_id) REFERENCES repositories(id)
);
CREATE TABLE IF NOT EXISTS binary_backups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER,
backup_path TEXT NOT NULL,
original_path TEXT NOT NULL,
version_label TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(repo_id) REFERENCES repositories(id)
);
CREATE TABLE IF NOT EXISTS desktop_launchers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER,
desktop_file_path TEXT NOT NULL,
icon_path TEXT,
menu_category TEXT DEFAULT 'Development',
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(repo_id) REFERENCES repositories(id)
);
EOF
# Add new columns if they don't exist (for upgrading existing databases)
sqlite3 "$DB_FILE" "PRAGMA table_info(repositories);" | grep -q "last_commit_check" || \
sqlite3 "$DB_FILE" "ALTER TABLE repositories ADD COLUMN last_commit_check TEXT;"
sqlite3 "$DB_FILE" "PRAGMA table_info(repositories);" | grep -q "build_type" || \
sqlite3 "$DB_FILE" "ALTER TABLE repositories ADD COLUMN build_type TEXT;"
sqlite3 "$DB_FILE" "PRAGMA table_info(repositories);" | grep -q "build_file_path" || \
sqlite3 "$DB_FILE" "ALTER TABLE repositories ADD COLUMN build_file_path TEXT;"
sqlite3 "$DB_FILE" "PRAGMA table_info(build_configs);" | grep -q "dependencies" || \
sqlite3 "$DB_FILE" "ALTER TABLE build_configs ADD COLUMN dependencies TEXT;"
sqlite3 "$DB_FILE" "PRAGMA table_info(build_configs);" | grep -q "strip_debug" || \
sqlite3 "$DB_FILE" "ALTER TABLE build_configs ADD COLUMN strip_debug INTEGER DEFAULT 0;"
sqlite3 "$DB_FILE" "PRAGMA table_info(build_configs);" | grep -q "use_ramdisk" || \
sqlite3 "$DB_FILE" "ALTER TABLE build_configs ADD COLUMN use_ramdisk INTEGER DEFAULT 0;"
# Add new build timing columns to build_history
sqlite3 "$DB_FILE" "PRAGMA table_info(build_history);" | grep -q "download_seconds" || \
sqlite3 "$DB_FILE" "ALTER TABLE build_history ADD COLUMN download_seconds INTEGER;"
sqlite3 "$DB_FILE" "PRAGMA table_info(build_history);" | grep -q "compile_seconds" || \
sqlite3 "$DB_FILE" "ALTER TABLE build_history ADD COLUMN compile_seconds INTEGER;"
sqlite3 "$DB_FILE" "PRAGMA table_info(build_history);" | grep -q "download_size_bytes" || \
sqlite3 "$DB_FILE" "ALTER TABLE build_history ADD COLUMN download_size_bytes INTEGER;"
# Create secondary_binaries table for storing all discovered binaries
sqlite3 "$DB_FILE" <<EOF
CREATE TABLE IF NOT EXISTS secondary_binaries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_id INTEGER NOT NULL,
binary_path TEXT NOT NULL,
binary_name TEXT,
discovered_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(repo_id) REFERENCES repositories(id),
UNIQUE(repo_id, binary_path)
);
EOF
}
# Handle errors gracefully
error() {
echo -e "\n${RED}Error: $1${NC}\n"
echo "Press 'R' to return to menu..."
read -r key
if [[ $key =~ ^[Rr]$ ]]; then
return 0
fi
return 1
}
# Trap errors and handle them gracefully
trap 'trap_error $?' ERR
trap_error() {
if [ "$1" != "1" ]; then # Don't show error for normal exit
echo -e "\n${RED}An unexpected error occurred. Error code: $1${NC}"
echo -e "Press 'R' to return to menu..."
read -r key
if [[ $key =~ ^[Rr]$ ]]; then
return 0
fi
fi
return 1
}
# Cleanup trap for RAM disk on exit
trap 'cleanup_ramdisk 2>/dev/null' EXIT
# Display success message
success() {
echo -e "\n${GREEN}Success: $1${NC}"
if [ "${2:-}" = "wait" ]; then
echo -e "\nPress any key to continue..."
read -r -n 1
fi
}
# =============================================================================
# SECURITY HELPER FUNCTIONS
# =============================================================================
# Escape string for safe SQL insertion (prevents SQL injection)
sql_escape() {
local input="$1"
# Escape single quotes by doubling them
echo "${input//\'/\'\'}"
}
# Validate that input is a positive integer (for IDs)
is_valid_id() {
local input="$1"
[[ "$input" =~ ^[0-9]+$ ]] && [ "$input" -gt 0 ]
}
# Sanitize path to prevent directory traversal
sanitize_path() {
local path="$1"
# Remove any .. sequences and normalize
realpath -m "$path" 2>/dev/null || echo "$path"
}
# =============================================================================
# SYSTEM HELPER FUNCTIONS
# =============================================================================
# Install packages using the system package manager
# Usage: install_packages package1 package2 ...
# Returns: 0 on success, 1 on failure
install_packages() {
local packages=("$@")
if [ ${#packages[@]} -eq 0 ]; then
return 0
fi
echo -e "${BLUE}Installing packages: ${packages[*]}${NC}"
if command -v apt-get >/dev/null 2>&1; then
sudo apt-get update && sudo apt-get install -y "${packages[@]}"
elif command -v dnf >/dev/null 2>&1; then
sudo dnf install -y "${packages[@]}"
elif command -v pacman >/dev/null 2>&1; then
sudo pacman -S --noconfirm "${packages[@]}"
elif command -v zypper >/dev/null 2>&1; then
sudo zypper install -y "${packages[@]}"
else
error "Could not detect package manager. Please install packages manually: ${packages[*]}"
return 1
fi
}
# Format a date string consistently
# Usage: format_date "date_string" [format]
# format: "short" = YYYY-MM-DD, "long" = YYYY-MM-DD HH:MM (default)
format_date() {
local date_str="$1"
local format="${2:-long}"
if [ -z "$date_str" ] || [ "$date_str" = "Unknown" ]; then
echo "${date_str:-Unknown}"
return
fi
local fmt_string
if [ "$format" = "short" ]; then
fmt_string="+%Y-%m-%d"
else
fmt_string="+%Y-%m-%d %H:%M"
fi
date -d "$date_str" "$fmt_string" 2>/dev/null || echo "$date_str"
}
# Execute multiple SQL statements in a transaction
# Usage: db_transaction "SQL statement 1; SQL statement 2; ..."
# Returns: 0 on success, 1 on failure (transaction rolled back)
db_transaction() {
local sql="$1"
sqlite3 "$DB_FILE" "BEGIN TRANSACTION; $sql COMMIT;" 2>/dev/null
local status=$?
if [ $status -ne 0 ]; then
sqlite3 "$DB_FILE" "ROLLBACK;" 2>/dev/null
return 1
fi
return 0
}
# =============================================================================
# RAM DISK FUNCTIONS
# =============================================================================
# Get available RAM in MB
get_available_ram_mb() {
local available_kb
available_kb=$(grep MemAvailable /proc/meminfo 2>/dev/null | awk '{print $2}')
if [ -z "$available_kb" ]; then
# Fallback for systems without MemAvailable
available_kb=$(free | awk '/^Mem:/{print $7}')
fi
echo $((available_kb / 1024))
}
# Check if RAM disk can be used
can_use_ramdisk() {
local required_mb="${1:-$RAMDISK_MIN_FREE_MB}"
local available_mb
available_mb=$(get_available_ram_mb)
if [ "$available_mb" -ge "$required_mb" ]; then
return 0
else
return 1
fi
}
# Setup RAM disk for building
# tmpfs dynamically allocates RAM as needed - size is just a soft limit
setup_ramdisk() {
local size_mb="${1:-0}" # 0 means use percentage-based calculation
# Check if already mounted
if mountpoint -q "$RAMDISK_MOUNT_POINT" 2>/dev/null; then
echo -e "${YELLOW}RAM disk already mounted at $RAMDISK_MOUNT_POINT${NC}"
RAMDISK_ACTIVE=true
return 0
fi
# Calculate size if not specified or 0
if [ "$size_mb" -eq 0 ] 2>/dev/null || [ -z "$size_mb" ]; then
local available_mb
available_mb=$(get_available_ram_mb)
# Use 75% of available RAM as soft limit (tmpfs only uses what it needs)
size_mb=$((available_mb * 75 / 100))
# Minimum 1GB, no maximum - let the system manage it
[ "$size_mb" -lt 1024 ] && size_mb=1024
fi
# Create mount point directory
mkdir -p "$RAMDISK_MOUNT_POINT"
# Mount tmpfs (doesn't require root if user has permissions, otherwise use sudo)
# Note: tmpfs only allocates RAM as files are written, the size is just a limit
if mount -t tmpfs -o size=${size_mb}M,mode=0755 tmpfs "$RAMDISK_MOUNT_POINT" 2>/dev/null; then
echo -e "${GREEN}RAM disk mounted at $RAMDISK_MOUNT_POINT (up to ${size_mb}MB available)${NC}"
RAMDISK_ACTIVE=true
return 0
else
# Explain why sudo is needed
echo -e "${YELLOW}Mounting RAM disk requires elevated privileges.${NC}"
echo -e "${CYAN}Sudo is needed to create a temporary filesystem in RAM for faster builds.${NC}"
echo -e "${CYAN}This is safe and the RAM disk will be automatically unmounted after the build.${NC}"
if sudo mount -t tmpfs -o size=${size_mb}M,mode=0755,uid=$(id -u),gid=$(id -g) tmpfs "$RAMDISK_MOUNT_POINT"; then
echo -e "${GREEN}RAM disk mounted at $RAMDISK_MOUNT_POINT (up to ${size_mb}MB available)${NC}"
RAMDISK_ACTIVE=true
return 0
else
echo -e "${RED}Failed to mount RAM disk. Building on regular disk.${NC}"
RAMDISK_ACTIVE=false
return 1
fi
fi
}
# Cleanup RAM disk after building
cleanup_ramdisk() {
if [ "$RAMDISK_ACTIVE" = true ] && mountpoint -q "$RAMDISK_MOUNT_POINT" 2>/dev/null; then
# Sync any pending writes
sync
# Unmount - try without sudo first
if umount "$RAMDISK_MOUNT_POINT" 2>/dev/null; then
echo -e "${GREEN}RAM disk unmounted successfully${NC}"
RAMDISK_ACTIVE=false
return 0
else
echo -e "${YELLOW}Unmounting RAM disk requires elevated privileges.${NC}"
echo -e "${CYAN}Sudo is needed to safely release the temporary RAM filesystem.${NC}"
if sudo umount "$RAMDISK_MOUNT_POINT" 2>/dev/null; then
echo -e "${GREEN}RAM disk unmounted successfully${NC}"
RAMDISK_ACTIVE=false
return 0
else
echo -e "${YELLOW}Warning: Could not unmount RAM disk. It will be cleaned up on reboot.${NC}"
return 1
fi
fi
fi
return 0
}
# Offer RAM disk option to user
offer_ramdisk() {
local repo_id="$1"
local available_mb
available_mb=$(get_available_ram_mb)
local potential_size=$((available_mb * 75 / 100))
if can_use_ramdisk; then
echo -e "\n${CYAN}RAM Disk Available${NC}"
echo -e "Available RAM: ${GREEN}${available_mb}MB${NC} (will use up to ${potential_size}MB as needed)"
echo -e "Building on RAM disk can significantly speed up compilation."
echo -e "${GRAY}Note: tmpfs only uses RAM as files are written, not all at once.${NC}"
echo ""
read -rp "Use RAM disk for this build? (y/N): " use_ram
if [[ "$use_ram" =~ ^[Yy]$ ]]; then
# Let setup_ramdisk calculate optimal size (75% of available RAM)
if setup_ramdisk 0; then
return 0
fi
fi
else
echo -e "${YELLOW}Note: Insufficient RAM for RAM disk build (${available_mb}MB available, ${RAMDISK_MIN_FREE_MB}MB required)${NC}"
fi
return 1
}
# Format duration in seconds to human-readable format (e.g., "5m 32s", "1h 23m")
format_duration() {
local seconds="$1"
if [ -z "$seconds" ] || [ "$seconds" -le 0 ] 2>/dev/null; then
echo "-"
return
fi
local hours=$((seconds / 3600))
local minutes=$(((seconds % 3600) / 60))
local secs=$((seconds % 60))
if [ "$hours" -gt 0 ]; then
printf "%dh %dm" "$hours" "$minutes"
elif [ "$minutes" -gt 0 ]; then
printf "%dm %ds" "$minutes" "$secs"
else
printf "%ds" "$secs"
fi
}
# Format bytes to human-readable format (e.g., "1.5 MB", "256 KB")
format_bytes() {
local bytes="$1"
if [ -z "$bytes" ] || [ "$bytes" -le 0 ] 2>/dev/null; then
echo "-"
return
fi
if [ "$bytes" -ge 1073741824 ]; then
printf "%.1f GB" "$(echo "scale=1; $bytes / 1073741824" | bc)"
elif [ "$bytes" -ge 1048576 ]; then
printf "%.1f MB" "$(echo "scale=1; $bytes / 1048576" | bc)"
elif [ "$bytes" -ge 1024 ]; then
printf "%.1f KB" "$(echo "scale=1; $bytes / 1024" | bc)"
else
printf "%d B" "$bytes"
fi
}
# =============================================================================
# UNIFIED TABLE SYSTEM
# =============================================================================
# Global arrays for table data - populated by fetch_repo_data()
declare -a _TABLE_HEADERS=()
declare -a _TABLE_COL_DATA=() # Flat array: col0_row0, col0_row1, ..., col1_row0, col1_row1, ...
declare -g _TABLE_NUM_COLS=0
declare -g _TABLE_NUM_ROWS=0
# Fetch repository data from database and populate table arrays
# Arguments:
# $1 - date_format: "full" (YYYY-MM-DD HH:MM) or "short" (MM-DD)
fetch_repo_data() {
local date_format="${1:-full}"
# Reset global arrays
_TABLE_HEADERS=("ID" "Name" "URL" "Last Commit" "Last Built" "Duration" "Binary")
_TABLE_COL_DATA=()
_TABLE_NUM_COLS=7
_TABLE_NUM_ROWS=0
# Temporary arrays for each column
local -a tmp_id=() tmp_name=() tmp_url=() tmp_commit=() tmp_built=() tmp_duration=() tmp_binary=()
while IFS='|' read -r id name url last_commit last_built binary_path; do
tmp_id+=("$id")
tmp_name+=("$name")
tmp_url+=("$url")
# Format the last commit date (always include year)
local formatted_commit=""
if [ -n "$last_commit" ] && [ "$last_commit" != "Unknown" ]; then
if [ "$date_format" = "short" ]; then
formatted_commit=$(date -d "$last_commit" "+%Y-%m-%d" 2>/dev/null || echo "${last_commit:0:10}")
else
formatted_commit=$(date -d "$last_commit" "+%Y-%m-%d %H:%M" 2>/dev/null || echo "$last_commit")
fi
else
formatted_commit="${last_commit:-Unknown}"
fi
tmp_commit+=("$formatted_commit")
# Format the last built date (always include year)
local formatted_built=""
if [ -n "$last_built" ]; then
if [ "$date_format" = "short" ]; then
formatted_built=$(date -d "$last_built" "+%Y-%m-%d" 2>/dev/null || echo "${last_built:0:10}")
else
formatted_built=$(date -d "$last_built" "+%Y-%m-%d %H:%M" 2>/dev/null || echo "$last_built")
fi
else
formatted_built="Never"
fi
tmp_built+=("$formatted_built")
# Get last build duration from build_history
local duration_seconds
duration_seconds=$(sqlite3 "$DB_FILE" "SELECT duration_seconds FROM build_history WHERE repo_id = $id ORDER BY finished_at DESC LIMIT 1;" 2>/dev/null)
local formatted_duration="-"
if [ -n "$duration_seconds" ] && [ "$duration_seconds" -gt 0 ] 2>/dev/null; then
formatted_duration=$(format_duration "$duration_seconds")
fi
tmp_duration+=("$formatted_duration")
# Binary status
local binary_status="No"
if [ -n "$binary_path" ] && [ -x "$binary_path" ]; then
binary_status="Yes"