-
Notifications
You must be signed in to change notification settings - Fork 44
/
harbor.sh
executable file
·2762 lines (2506 loc) · 83 KB
/
harbor.sh
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
set -eo pipefail
# ========================================================================
# == Functions
# ========================================================================
show_version() {
echo "Harbor CLI version: $version"
}
show_help() {
show_version
echo "Usage: $0 <command> [options]"
echo
echo "Compose Setup Commands:"
echo " up|u [handle] - Start the containers"
echo " down|d - Stop and remove the containers"
echo " restart|r [handle] - Down then up"
echo " ps - List the running containers"
echo " logs|l <handle> - View the logs of the containers"
echo " exec <handle> [command] - Execute a command in a running service"
echo " pull <handle> - Pull the latest images"
echo " dive <handle> - Run the Dive CLI to inspect Docker images"
echo " run <handle> [command] - Run a one-off command in a service container"
echo " shell <handle> - Load shell in the given service main container"
echo " build <handle> - Build the given service"
echo " cmd <handle> - Print the docker compose command"
echo
echo "Setup Management Commands:"
echo " webui - Configure Open WebUI Service"
echo " llamacpp - Configure llamacpp service"
echo " tgi - Configure text-generation-inference service"
echo " litellm - Configure LiteLLM service"
echo " openai - Configure OpenAI API keys and URLs"
echo " vllm - Configure VLLM service"
echo " aphrodite - Configure Aphrodite service"
echo " tabbyapi - Configure TabbyAPI service"
echo " mistralrs - Configure mistral.rs service"
echo " cfd - Run cloudflared CLI"
echo " airllm - Configure AirLLM service"
echo " txtai - Configure txtai service"
echo " chatui - Configure HuggingFace ChatUI service"
echo " comfyui - Configure ComfyUI service"
echo " parler - Configure Parler service"
echo " omnichain - Work with Omnichain service"
echo
echo "Service CLIs:"
echo " ollama - Run Ollama CLI (docker). Service should be running."
echo " aider - Launch Aider CLI"
echo " aichat - Run aichat CLI"
echo " interpreter|opint - Launch Open Interpreter CLI"
echo " fabric - Run Fabric CLI"
echo " plandex - Launch Plandex CLI"
echo " cmdh - Run cmdh CLI"
echo " parllama - Launch Parllama - TUI for chatting with Ollama models"
echo " hf - Run the Harbor's Hugging Face CLI. Expanded with a few additional commands."
echo " hf dl - HuggingFaceModelDownloader CLI"
echo " hf parse-url - Parse file URL from Hugging Face"
echo " hf token - Get/set the Hugging Face Hub token"
echo " hf cache - Get/set the path to Hugging Face cache"
echo " hf find <query> - Open HF Hub with a query (trending by default)"
echo " hf path <spec> - Print a folder in HF cache for a given model spec"
echo " hf * - Anything else is passed to the official Hugging Face CLI"
echo
echo "Harbor CLI Commands:"
echo " open handle - Open a service in the default browser"
echo
echo " url <handle> - Get the URL for a service"
echo " url <handle> - Url on the local host"
echo " url [-a|--adressable|--lan] <handle> - (supposed) LAN URL"
echo " url [-i|--internal] <handle> - URL within Harbor's docker network"
echo
echo " qr <handle> - Print a QR code for a service"
echo
echo " t|tunnel <handle> - Expose given service to the internet"
echo " tunnel down|stop|d|s - Stop all running tunnels (including auto)"
echo " tunnels [ls|rm|add] - Manage services that will be tunneled on 'up'"
echo " tunnels rm <handle|index> - Remove, also accepts handle or index"
echo " tunnels add <handle> - Add a service to the tunnel list"
echo
echo " config [get|set|ls] - Manage the Harbor environment configuration"
echo " config ls - All config values in ENV format"
echo " config get <field> - Get a specific config value"
echo " config set <field> <value> - Get a specific config value"
echo " config reset - Reset Harbor configuration to default.env"
echo " config update - Merge upstream config changes from default.env"
echo
echo " defaults [ls|rm|add] - List default services"
echo " defaults rm <handle|index> - Remove, also accepts handle or index"
echo " defaults add <handle> - Add"
echo
echo " find <file> - Find a file in the caches visible to Harbor"
echo " ls|list [--active|-a] - List available/active Harbor services"
echo " ln|link [--short] - Create a symlink to the CLI, --short for 'h' link"
echo " unlink - Remove CLI symlinks"
echo " eject - Eject the Compose configuration, accepts same options as 'up'"
echo " help|--help|-h - Show this help message"
echo " version|--version|-v - Show the CLI version"
echo " gum - Run the Gum terminal commands"
echo " update [-l|--latest] - Update Harbor. --latest for the dev version"
echo " info - Show system information for debug/issues"
echo " how - Ask questions about Harbor CLI, uses cmdh under the hood"
echo " smi - Show NVIDIA GPU information"
echo " top - Run nvtop to monitor GPU usage"
echo
echo "Harbor Workspace Commands:"
echo " home - Show path to the Harbor workspace"
echo " vscode - Open Harbor Workspace in VS Code"
echo " fixfs - Fix file system ACLs for service volumes"
}
run_harbor_doctor() {
log_info "Running Harbor Doctor..."
# Check if Docker is installed and running
if command -v docker &> /dev/null && docker info &> /dev/null; then
log_info "${ok} Docker is installed and running"
else
log_error "${nok} Docker is not installed or not running. Please install or start Docker."
return 1
fi
# Check if Docker Compose is installed
if command -v docker-compose &> /dev/null; then
log_info "${ok} Docker Compose is installed"
else
log_error "${nok} Docker Compose is not installed. Please install Docker Compose."
return 1
fi
# Check if the .env file exists and is readable
if [ -f ".env" ] && [ -r ".env" ]; then
log_info "${ok} .env file exists and is readable"
else
log_error "${nok} .env file is missing or not readable. Please ensure it exists and has the correct permissions."
return 1
fi
# Check if the default.env file exists and is readable
if [ -f "default.env" ] && [ -r "default.env" ]; then
log_info "${ok} default.env file exists and is readable"
else
log_error "${nok} default.env file is missing or not readable. Please ensure it exists and has the correct permissions."
return 1
fi
# Check if the Harbor workspace directory exists
if [ -d "$harbor_home" ]; then
log_info "${ok} Harbor workspace directory exists"
else
log_error "${nok} Harbor workspace directory $harbor_home does not exist."
return 1
fi
# Check if CLI is linked
if [ -L "$(eval echo "$(env_manager get cli.path)")/$(env_manager get cli.name)" ]; then
log_info "${ok} CLI is linked"
else
log_error "${nok} CLI is not linked. Run 'harbor link' to create a symlink."
return 1
fi
log_info "Harbor Doctor checks completed successfully."
}
# shellcheck disable=SC2034
__anchor_fns=true
resolve_compose_files() {
# Find all .yml files in the specified base directory,
# but do not go into subdirectories
find "$base_dir" -maxdepth 1 -name "*.yml" |
# For each file, count the number of dots in the filename
# and prepend this count to the filename
awk -F. '{print NF-1, $0}' |
# Sort the files based on the
# number of dots, in ascending order
sort -n |
# Remove the dot count, leaving
# just the sorted filenames
cut -d' ' -f2-
}
compose_with_options() {
local base_dir="$PWD"
local compose_files=("$base_dir/compose.yml") # Always include the base compose file
local options=("${default_options[@]}")
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--dir=*)
base_dir="${1#*=}"
shift
;;
*)
options+=("$1")
shift
;;
esac
done
# Check for NVIDIA GPU and drivers
if command -v nvidia-smi &> /dev/null && docker info | grep -q "Runtimes:.*nvidia"; then
options+=("nvidia")
fi
for file in $(resolve_compose_files); do
if [ -f "$file" ]; then
local filename=$(basename "$file")
local match=false
# This is a "cross" file, only to be included
# if we're running all the mentioned services
if [[ $filename == *".x."* ]]; then
local cross="${filename#compose.x.}"
cross="${cross%.yml}"
# Convert dot notation to array
local filename_parts=(${cross//./ })
local all_matched=true
for part in "${filename_parts[@]}"; do
if [[ ! " ${options[*]} " =~ " ${part} " ]]; then
all_matched=false
break
fi
done
if $all_matched; then
compose_files+=("$file")
fi
# Either way, the processing
# for this file is done
continue
fi
# Check if file matches any of the options
for option in "${options[@]}"; do
if [[ $option == "*" ]]; then
match=true
break
fi
if [[ $filename == *".$option."* ]]; then
match=true
break
fi
done
# Include the file if:
# 1. It matches an option and is not an NVIDIA file
# 2. It matches an option, is an NVIDIA file, and NVIDIA is supported
# if $match && (! $is_nvidia_file || ($is_nvidia_file && $has_nvidia)); then
if $match ; then
compose_files+=("$file")
fi
fi
done
# Prepare docker compose command
local cmd="docker compose"
for file in "${compose_files[@]}"; do
cmd+=" -f $file"
done
# Return the command string
echo "$cmd"
}
resolve_compose_command() {
local is_human=false
case "$1" in
--human|-h)
shift
is_human=true
;;
esac
local cmd=$(compose_with_options "$@")
if $is_human; then
echo "$cmd" | sed "s|-f $harbor_home/|\n - |g"
else
echo "$cmd"
fi
}
harbor_up() {
$(compose_with_options "$@") up -d --wait
if [ "$default_autoopen" = "true" ]; then
open_service "$default_open"
fi
for service in "${default_tunnels[@]}"; do
establish_tunnel "$service"
done
}
run_hf_open() {
local search_term="${*// /+}"
local hf_url="https://huggingface.co/models?sort=trending&search=${search_term}"
sys_open "$hf_url"
}
link_cli() {
local target_dir=$(eval echo "$(env_manager get cli.path)")
local script_name=$(env_manager get cli.name)
local short_name=$(env_manager get cli.short)
local script_path="$harbor_home/harbor.sh"
local create_short_link=false
# Check for "--short" flag
for arg in "$@"; do
if [[ "$arg" == "--short" ]]; then
create_short_link=true
break
fi
done
# Determine which shell configuration file to update
local shell_profile=""
if [[ -f "$HOME/.zshrc" ]]; then
shell_profile="$HOME/.zshrc"
elif [[ -f "$HOME/.bash_profile" ]]; then
shell_profile="$HOME/.bash_profile"
elif [[ -f "$HOME/.bashrc" ]]; then
shell_profile="$HOME/.bashrc"
elif [[ -f "$HOME/.profile" ]]; then
shell_profile="$HOME/.profile"
else
if [[ "$OSTYPE" == "darwin"* ]]; then
shell_profile="$HOME/.zshrc"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
shell_profile="$HOME/.bashrc"
else
# We can't determine the shell profile
log_warn "Sorry, but Harbor can't determine which shell configuration file to update."
log_warn "Please link the CLI manually."
log_warn "Harbor supports: ~/.zshrc, ~/.bash_profile, ~/.bashrc, ~/.profile"
return 1
fi
fi
# Check if target directory exists in PATH
if ! echo "$PATH" | tr ':' '\n' | grep -q "$target_dir"; then
log_info "Creating $target_dir and adding it to PATH..."
mkdir -p "$target_dir"
# Update the shell configuration file
echo -e "\nexport PATH=\"\$PATH:$target_dir\"\n" >> "$shell_profile"
export PATH="$PATH:$target_dir"
echo "Updated $shell_profile with new PATH."
fi
# Create symlink
if ln -s "$script_path" "$target_dir/$script_name"; then
log_info "Symlink created: $target_dir/$script_name -> $script_path"
else
log_warn "Failed to create symlink. Please check permissions and try again."
return 1
fi
# Create short symlink if "--short" flag is present
if $create_short_link; then
if ln -s "$script_path" "$target_dir/$short_name"; then
log_info "Short symlink created: $target_dir/$short_name -> $script_path"
else
log_warn "Failed to create short symlink. Please check permissions and try again."
return 1
fi
fi
log_info "You may need to reload your shell or run 'source $shell_profile' for changes to take effect."
}
unlink_cli() {
local target_dir=$(eval echo "$(env_manager get cli.path)")
local script_name=$(env_manager get cli.name)
local short_name=$(env_manager get cli.short)
log_info "Removing symlinks..."
# Remove the main symlink
if [ -L "$target_dir/$script_name" ]; then
rm "$target_dir/$script_name"
log_info "Removed symlink: $target_dir/$script_name"
else
log_info "Main symlink does not exist or is not a symbolic link."
fi
# Remove the short symlink
if [ -L "$target_dir/$short_name" ]; then
rm "$target_dir/$short_name"
log_info "Removed short symlink: $target_dir/$short_name"
else
log_info "Short symlink does not exist or is not a symbolic link."
fi
}
get_container_name() {
local service_name="$1"
local container_name="$default_container_prefix.$service_name"
echo "$container_name"
}
get_service_port() {
local services
local target_name
local port
# Get list of running services
services=$(docker compose ps -a --services --filter "status=running")
# Check if any services are running
if [ -z "$services" ]; then
log_warn "No services are currently running."
return 1
fi
service_name="$1"
target_name=$(get_container_name "$1")
# Check if the specified service is running
if ! echo "$services" | grep -q "$service_name"; then
log_warn "Service '$1' is not currently running."
log_info "Running services:"
log_info "$services"
return 1
fi
# Get the port mapping for the service
if port=$(docker port "$target_name" | perl -nle 'print m{0.0.0.0:\K\d+}g' | head -n 1) && [ -n "$port" ]; then
echo "$port"
else
log_error "No port mapping found for service '$1': $port"
return 1
fi
}
get_service_url() {
local service_name="$1"
local port
if port=$(get_service_port "$service_name"); then
echo "http://localhost:$port"
return 0
else
log_error "Failed to get port for service '$service_name'"
return 1
fi
}
get_adressable_url() {
local service_name="$1"
local port
local ip_address
if port=$(get_service_port "$service_name"); then
if ip_address=$(get_ip); then
echo "http://$ip_address:$port"
return 0
else
log_error "Failed to get service '$service_name' IP address"
return 1
fi
else
log_error "Failed to get port for service '$service_name'"
return 1
fi
}
get_intra_url() {
local service_name="$1"
local container_name
local intra_host
local intra_port
container_name=$(get_container_name "$service_name")
intra_host=$container_name
if intra_port=$(docker port $container_name | awk -F'[ /]' '{print $1}' | sort -n | uniq); then
echo "http://$intra_host:$intra_port"
return 0
else
log_error "Failed to get internal port for service '$service_name'"
return 1
fi
}
get_url() {
local is_local=true
local is_adressable=false
local is_intra=false
local filtered_args=()
local arg
for arg in "$@"; do
case "$arg" in
--intra|-i|--internal)
is_local=false
is_adressable=false
is_intra=true
;;
--addressable|-a|--lan)
is_local=false
is_intra=false
is_adressable=true
;;
*)
filtered_args+=("$arg") # Add to filtered arguments
;;
esac
done
# If nothing specified - use a handle
# of the default service to open
if [ ${#filtered_args[@]} -eq 0 ] || [ -z "${filtered_args[0]}" ]; then
filtered_args[0]="$default_open"
fi
if $is_local; then
get_service_url "${filtered_args[@]}"
elif $is_adressable; then
get_adressable_url "${filtered_args[@]}"
elif $is_intra; then
get_intra_url "${filtered_args[@]}"
fi
}
print_qr() {
local url="$1"
$(compose_with_options "qrgen") run --rm qrgen "$url"
}
print_service_qr() {
local url=$(get_url -a "$1")
log_info "URL: $url"
print_qr "$url"
}
sys_info() {
show_version
echo "=========================="
get_services -a
echo "=========================="
docker info
}
sys_open() {
url=$1
# Open the URL in the default browser
if command -v xdg-open &> /dev/null; then
xdg-open "$url" # Linux
elif command -v open &> /dev/null; then
open "$url" # macOS
elif command -v start &> /dev/null; then
start "$url" # Windows
else
log_error "Unable to open browser. Please visit $url manually."
return 1
fi
}
open_service() {
local service_url
if service_url=$(get_url "$1"); then
sys_open "$service_url"
log_info "Opened $service_url in your default browser."
else
log_error "Failed to get service URL for '$1'"
return 1
fi
}
smi() {
if command -v nvidia-smi &> /dev/null; then
nvidia-smi
else
log_error "nvidia-smi not found."
fi
}
nvidia_top() {
if command -v nvtop &> /dev/null; then
nvtop
else
log_error "nvtop not found."
fi
}
eject() {
$(compose_with_options "$@") config
}
run_in_service() {
local service_name=""
local before_args=()
local after_args=()
local parsing_after=false
# Parse arguments
for arg in "$@"; do
if [[ -z $service_name ]]; then
if docker compose ps --services | grep -q "^${arg}$"; then
service_name="$arg"
parsing_after=true
else
before_args+=("$arg")
fi
elif $parsing_after; then
after_args+=("$arg")
fi
done
# Check if service name was found
if [[ -z $service_name ]]; then
echo "Error: No valid service name provided."
return 1
fi
# Check if the service is running
if docker compose ps --services --filter "status=running" | grep -q "^${service_name}$"; then
log_info "Service ${service_name} is running. Executing command..."
# Construct the command
local full_command=("${before_args[@]}" "${service_name}" "${after_args[@]}")
# Execute the command
# shellcheck disable=SC2068
docker compose exec ${full_command[@]}
else
log_error "Service ${service_name} is not running. Please start it with 'harbor up ${service_name}' first."
return 1
fi
}
set_colors() {
if [ -t 1 ] && command -v tput > /dev/null 2>&1 && tput setaf 1 > /dev/null 2>&1; then
c_r=$(tput setaf 1)
c_g=$(tput setaf 2)
c_nc=$(tput sgr0)
elif [ -t 1 ]; then
c_r='\033[0;31m'
c_g='\033[0;32m'
c_nc='\033[0m'
else
c_r=''
c_g=''
c_nc=''
fi
# Define symbols
ok="${c_g}✔${c_nc}"
nok="${c_r}✘${c_nc}"
}
ensure_env_file() {
local src_file="default.env"
local tgt_file=".env"
if [ ! -f "$tgt_file" ]; then
echo "Creating .env file..."
cp "$src_file" "$tgt_file"
fi
}
reset_env_file() {
log_warn "Resetting Harbor configuration..."
rm .env
ensure_env_file
}
merge_env_files() {
local default_file="default.env"
local target_file=".env"
# Check if both files exist
if [[ ! -f "$target_file" ]]; then
cp "$default_file" "$target_file"
echo "Copied $default_file to $target_file"
return
fi
# Create a temporary file
local temp_file=$(mktemp)
# Variable to track empty lines
local empty_lines=0
# Variable to track repeated lines
local prev_line=""
local repeat_count=0
# Read default.env line by line and merge with .env
while IFS= read -r line || [[ -n "$line" ]]; do
# Handle empty lines
if [[ -z "$line" ]]; then
((empty_lines++))
if ((empty_lines <= 2)); then
echo "$line" >> "$temp_file"
fi
prev_line=""
repeat_count=0
continue
else
empty_lines=0
fi
# Check for repeated lines
if [[ "$line" == "$prev_line" ]]; then
((repeat_count++))
if ((repeat_count <= 1)); then
echo "$line" >> "$temp_file"
fi
else
repeat_count=0
if [[ "$line" =~ ^[[:alnum:]_]+=.* ]]; then
var_name="${line%%=*}"
if grep -q "^$var_name=" "$target_file"; then
# If the variable exists in .env, use that value
grep "^$var_name=" "$target_file" >> "$temp_file"
else
# If the variable doesn't exist in .env, add the new line
echo "$line" >> "$temp_file"
fi
else
# For comments or other content, add the new line as is
echo "$line" >> "$temp_file"
fi
fi
prev_line="$line"
done < "$default_file"
# Remove trailing newlines from the temp file
if [[ "$(uname)" == "Darwin" ]]; then
sed -i '' -e :a -e '/^\n*$/{$d;N;ba' -e '}' "$temp_file"
else
sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' "$temp_file"
fi
# Move the temporary file to replace the target file
mv "$temp_file" "$target_file"
log_info "Merged content from $default_file into $target_file, preserving order and structure"
}
execute_and_process() {
local command_to_execute="$1"
local success_command="$2"
local error_message="$3"
# Execute the command and capture its output
command_output=$(eval "$command_to_execute" 2>&1)
exit_code=$?
# Check the exit code
if [ $exit_code -eq 0 ]; then
# Replace placeholder with command output, using | as delimiter
success_command_modified=$(echo "$success_command" | sed "s|{{output}}|$command_output|")
# If the command succeeded, pass the output to the success command
eval "$success_command_modified"
else
# If the command failed, print the custom error message and the output
log_warn "$error_message Exit code: $exit_code. Output:"
log_info "$command_output"
fi
}
swap_and_retry() {
local command=$1
shift
local args=("$@")
# Try original order
if "$command" "${args[@]}"; then
return 0
else
local exit_code=$?
# If failed and there are at least two arguments, try swapped order
if [ $exit_code -eq $scramble_exit_code ]; then
if [ ${#args[@]} -ge 2 ]; then
log_warn "'harbor ${args[0]} ${args[1]}' failed, trying 'harbor ${args[1]} ${args[0]}'..."
if "$command" "${args[1]}" "${args[0]}" "${args[@]:2}"; then
return 0
else
# Check for common user-caused exit codes
exit_code=$?
# Check common exit codes
case $exit_code in
0)
log_debug "Process completed successfully"
;;
1)
log_error "General error occurred"
;;
2)
log_error "Misuse of shell builtin"
;;
126)
log_error "Command invoked cannot execute (permission problem or not executable)"
;;
127)
log_error "Command not found"
;;
128)
log_error "Invalid exit argument"
;;
129)
log_warn "SIGHUP (Hangup) received"
;;
130)
log_info "SIGINT (Keyboard interrupt) received"
;;
131)
log_info "SIGQUIT (Keyboard quit) received"
;;
137)
log_info "SIGKILL (Kill signal) received"
;;
143)
log_info "SIGTERM (Termination signal) received"
;;
*)
log_info "Exit code: $exit_code"
return 1
;;
esac
fi
else
# Less than two arguments, retry is impossible
return 1
fi
fi
fi
}
set_default_log_levels() {
default_log_levels_DEBUG=0
default_log_levels_INFO=1
default_log_levels_WARN=2
default_log_levels_ERROR=3
}
get_default_log_level() {
local level="$1"
local var_name="default_log_levels_$level"
eval echo \$$var_name
}
log() {
local level="$1"
shift
local current_level=$(get_default_log_level "$level")
local set_level=$(get_default_log_level "$default_log_level")
# Check if the numeric value of the current log level is greater than or equal to the set default_log_level
if [[ $current_level -ge $set_level ]]; then
echo "$(date +'%H:%M:%S') [$level] $*" >&2
fi
}
# Convenience functions for different log levels
log_debug() { log "DEBUG" "$@"; }
log_info() { log "INFO" "$@"; }
log_warn() { log "WARN" "$@"; }
log_error() { log "ERROR" "$@"; }
# shellcheck disable=SC2034
__anchor_envm=true
env_manager() {
local env_file=".env"
local prefix="HARBOR_"
case "$1" in
get)
if [[ -z "$2" ]]; then
log_info "Usage: env_manager get <key>"
return 1
fi
local upper_key=$(echo "$2" | tr '[:lower:]' '[:upper:]' | tr '.' '_')
value=$(grep "^$prefix$upper_key=" "$env_file" | cut -d '=' -f2-)
value="${value#\"}" # Remove leading quote if present
value="${value%\"}" # Remove trailing quote if present
echo "$value"
;;
set)
if [[ -z "$2" ]]; then
log_info "Usage: env_manager set <key> <value>"
return 1
fi
local upper_key=$(echo "$2" | tr '[:lower:]' '[:upper:]' | tr '.' '_')
shift 2 # Remove 'set' and the key from the arguments
local value="$*" # Capture all remaining arguments as the value
if grep -q "^$prefix$upper_key=" "$env_file"; then
sed -i "s|^$prefix$upper_key=.*|$prefix$upper_key=\"$value\"|" "$env_file"
else
echo "$prefix$upper_key=\"$value\"" >> "$env_file"
fi
log_info "Set $prefix$upper_key to: \"$value\""
;;
list|ls)
grep "^$prefix" "$env_file" | sed "s/^$prefix//" | while read -r line; do
key=${line%%=*}
value=${line#*=}
value=$(echo "$value" | sed -E 's/^"(.*)"$/\1/') # Remove surrounding quotes for display
printf "%-30s %s\n" "$key" "$value"
done
;;
reset)
shift
run_gum confirm "Are you sure you want to reset Harbor configuration?" && reset_env_file || log_warn "Reset cancelled"
;;
update)
shift
merge_env_files
;;
--help|-h)
echo "Harbor configuration management"
echo
echo "Usage: harbor config {get|set|ls|list|reset|update} [key] [value]"
echo
echo "Commands:"
echo " get <key> - Get the value of a configuration key"
echo " set <key> <value> - Set the value of a configuration key"
echo " ls|list - List all configuration keys and values"
echo " reset - Reset Harbor configuration to default.env"
echo " update - Merge upstream config changes from default.env"
return 0
;;
*)
echo "Usage: harbor config {get|set|ls|reset} [key] [value]"
return $scramble_exit_code
;;
esac
}
env_manager_alias() {
local field=$1
shift
local get_command=""
local set_command=""
# Check if optional commands are provided
if [[ "$1" == "--on-get" ]]; then
get_command="$2"
shift 2
fi
if [[ "$1" == "--on-set" ]]; then
set_command="$2"
shift 2
fi
case $1 in
--help|-h)
echo "Harbor config: $field"
echo
echo "This field is a string, use the following actions to manage it:"
echo
echo " no arguments - Get the current value"
echo " <value> - Set a new value"
echo
return 0
;;
esac
if [ $# -eq 0 ]; then
env_manager get "$field"
if [ -n "$get_command" ]; then
eval "$get_command"
fi
else
env_manager set "$field" "$@"
if [ -n "$set_command" ]; then
eval "$set_command"
fi
fi
}
env_manager_arr() {
local field=$1
shift
local delimiter=";"
local get_command=""
local set_command=""