forked from cfgnunes/nautilus-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.common-functions.sh
More file actions
3976 lines (3517 loc) · 128 KB
/
Copy path.common-functions.sh
File metadata and controls
3976 lines (3517 loc) · 128 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
#!/usr/bin/env bash
# shellcheck disable=SC2001
# =============================================================================
# PROJECT: Enhanced File Manager Actions for Linux
# AUTHOR: Cristiano Fraga G. Nunes
# REPOSITORY: https://github.com/cfgnunes/nautilus-scripts
# LICENSE: MIT License
# VERSION: 29.3.4
# =============================================================================
# This file contains shared functions and constants sourced by all scripts.
set -u
# -----------------------------------------------------------------------------
# SECTION: Constants ----
# -----------------------------------------------------------------------------
ACCESSED_RECENTLY_LINKS_TO_KEEP=10
FIELD_SEPARATOR=$'\r' # The main field separator.
GUI_BOX_HEIGHT=550 # Height of the GUI dialog boxes.
GUI_BOX_WIDTH=900 # Width of the GUI dialog boxes.
GUI_INFO_WIDTH=400 # Width of the GUI small dialog boxes.
I18N_DIR="$ROOT_DIR/.po" # Directory containing PO files for translation.
IGNORE_FIND_PATH="*.git/*" # Path to ignore in the 'find' command.
PREFIX_ERROR_LOG_FILE="Errors" # Basename of 'Error' log file.
PREFIX_OUTPUT_DIR="Output" # Basename of 'Output' directory.
# Temporary directories.
TEMP_DIR=$(mktemp --directory)
TEMP_DIR_ITEMS_TO_REMOVE="$TEMP_DIR/items_to_remove"
TEMP_DIR_LOGS="$TEMP_DIR/logs"
TEMP_DIR_FILENAME_LOCKS="$TEMP_DIR/filename_locks"
TEMP_DIR_STORAGE_TEXT="$TEMP_DIR/storage_text"
TEMP_DIR_TASK="$TEMP_DIR/task"
# Temporary files.
TEMP_CONTROL_BATCH_ENABLED="$TEMP_DIR/control_batch_enabled"
TEMP_CONTROL_DISPLAY_LOCKED="$TEMP_DIR/control_display_locked"
TEMP_CONTROL_WAIT_BOX_DELAY="$TEMP_DIR/control_wait_box_delay"
TEMP_CONTROL_WAIT_BOX_FIFO="$TEMP_DIR/control_wait_box_fifo"
TEMP_DATA_TEXT_BOX="$TEMP_DIR/data_text_box"
# Message tags for displaying status messages on terminal.
MSG_ERROR="[\033[0;31mFAILED\033[0m]"
MSG_INFO="[\033[0;32m INFO \033[0m]"
# Defines the priority order of package managers.
PKG_MANAGER_PRIORITY=(
"brew"
"nix"
"apt-get"
"rpm-ostree"
"dnf"
"pacman"
"zypper"
"guix"
)
readonly \
ACCESSED_RECENTLY_LINKS_TO_KEEP \
FIELD_SEPARATOR \
GUI_BOX_HEIGHT \
GUI_BOX_WIDTH \
GUI_INFO_WIDTH \
I18N_DIR \
IGNORE_FIND_PATH \
PKG_MANAGER_PRIORITY \
PREFIX_ERROR_LOG_FILE \
PREFIX_OUTPUT_DIR \
TEMP_CONTROL_DISPLAY_LOCKED \
TEMP_CONTROL_WAIT_BOX_DELAY \
TEMP_CONTROL_WAIT_BOX_FIFO \
TEMP_DATA_TEXT_BOX \
TEMP_DIR \
TEMP_DIR_FILENAME_LOCKS \
TEMP_DIR_ITEMS_TO_REMOVE \
TEMP_DIR_LOGS \
TEMP_DIR_STORAGE_TEXT \
TEMP_DIR_TASK
# -----------------------------------------------------------------------------
# SECTION: Global variables ----
# -----------------------------------------------------------------------------
# Internal Field Separator used for splitting fields based on the
# value defined in $FIELD_SEPARATOR.
IFS=$FIELD_SEPARATOR
# List of all input files passed as positional parameters.
INPUT_FILES=$*
# Variable used to share data between specific parallel task functions
# (e.g., passwords, configuration values).
TEMP_DATA_TASK=""
# Associative array that stores translation key-value pairs loaded
# from PO files during i18n initialization by '_i18n_initialize'.
declare -A I18N_DATA=()
# -----------------------------------------------------------------------------
# SECTION: Build the structure of the '$TEMP_DIR' ----
# -----------------------------------------------------------------------------
# DESCRIPTION:
#
# '$TEMP_DIR_FILENAME_LOCKS':
# This directory is used to store temporary lock directories created by
# the '_get_filename_next_suffix' function during concurrent executions.
# Each process creates a uniquely named subdirectory here (using
# 'mkdir'), which acts as a lightweight synchronization mechanism. The
# idea to prevent name conflicts by race conditions when multiple
# processes attempt to generate filenames simultaneously.
#
# '$TEMP_DIR_ITEMS_TO_REMOVE':
# This directory is used for temporary items scheduled for removal after
# the scripts' tasks finish executing.
#
# '$TEMP_DIR_LOGS'
# This directory stores temporary error logs generated during
# the execution of the scripts.
#
# '$TEMP_DIR_STORAGE_TEXT':
# This directory stores text files from output data produced by parallel
# tasks during the execution of the scripts.
#
# '$TEMP_DIR_TASK':
# This directory is used by the '_make_temp_dir' and '_make_temp_file'
# functions to store temporary files created during the scripts' tasks.
mkdir -p "$TEMP_DIR_FILENAME_LOCKS"
mkdir -p "$TEMP_DIR_ITEMS_TO_REMOVE"
mkdir -p "$TEMP_DIR_LOGS"
mkdir -p "$TEMP_DIR_STORAGE_TEXT"
mkdir -p "$TEMP_DIR_TASK"
# -----------------------------------------------------------------------------
# SECTION: Core utilities ----
# -----------------------------------------------------------------------------
# FUNCTION: _cleanup_on_exit
#
# DESCRIPTION:
# This function performs cleanup tasks when the script exits. It is
# designed to safely and efficiently remove temporary directories or files
# that were created during the script's execution.
_cleanup_on_exit() {
# Remove local temporary dirs or files.
local items_to_remove=""
items_to_remove=$(cat -- "$TEMP_DIR_ITEMS_TO_REMOVE/"* 2>/dev/null)
# Escape single quotes in filenames to handle them correctly in 'xargs'
# with 'bash -c'.
items_to_remove=$(sed -z "s|'|'\\\''|g" <<<"$items_to_remove")
printf "%s" "$items_to_remove" | xargs \
--no-run-if-empty \
--delimiter="$FIELD_SEPARATOR" \
--max-procs="$(_get_max_procs)" \
--replace="{}" \
bash -c "{ chmod -R u+rw -- '{}' && rm -rf -- '{}'; } 2>/dev/null"
# Remove the main temporary dir.
{ chmod -R u+w -- "$TEMP_DIR" && rm -rf -- "$TEMP_DIR"; } 2>/dev/null
if ! _is_gui_session; then
echo -e "$MSG_INFO $(_i18n 'Done!')" >&2
fi
}
trap _cleanup_on_exit EXIT
# FUNCTION: _exit_script
#
# DESCRIPTION:
# This function is responsible for safely exiting the script by terminating all
# child processes associated with the current script and printing an exit
# message to the terminal.
_exit_script() {
_close_wait_box
# Lock the main temporary directory to prevent
# any active process from writing to it.
chmod -R u-w -- "$TEMP_DIR" 2>/dev/null
local child_pids=""
local script_pid=$$
# Get the process ID (PID) of all child processes.
child_pids=$(pstree -p "$script_pid" |
grep --only-matching --perl-regexp "\(+\K[^)]+")
# NOTE: Use 'xargs' and kill to send the SIGTERM signal to all child
# processes, including the current script.
# See: https://www.baeldung.com/linux/safely-exit-scripts
xargs kill <<<"$child_pids" 2>/dev/null
}
# FUNCTION: _check_output
#
# DESCRIPTION:
# This function validates the success of a command or process based on its
# exit code and output. It logs errors if the command fails or if an
# expected output file is missing.
#
# PARAMETERS:
# $1 (exit_code): The exit code returned by the command or process.
# $2 (std_output): The standard output or error from the command.
# $3 (input_file): The input file associated (if applicable).
# $4 (output_file): The expected output file to verify its existence.
#
# RETURNS:
# "0" (true): If the command was successful and the output file exists.
# "1" (false): If the command failed or the output file does not exist.
_check_output() {
local exit_code=$1
local std_output=$2
local input_file=$3
local output_file=$4
local msg=""
# Check the '$exit_code' and log the error.
if ((exit_code != 0)); then
msg="$(_i18n 'The command failed.')"
_log_error "$msg" "$input_file" "$std_output" "$output_file"
return 1
fi
# Check if the output file exists.
if [[ -n "$output_file" ]] && [[ ! -e "$output_file" ]]; then
msg="$(_i18n 'The output file does not exist.')"
_log_error "$msg" "$input_file" "$std_output" "$output_file"
return 1
fi
return 0
}
# FUNCTION: _log_error
#
# DESCRIPTION:
# This function writes an error log entry with a specified message,
# including details such as the input file, output file, and terminal
# output. The entry is saved to a temporary log file.
#
# PARAMETERS:
# $1 (message): The error message to be logged.
# $2 (input_file): The path of the input file associated with the
# operation.
# $3 (std_output): The standard output or result from the operation
# that will be logged.
# $4 (output_file): The path of the output file associated with the
# operation.
_log_error() {
local message=$1
local input_file=$2
local std_output=$3
local output_file=$4
local log_temp_file=""
log_temp_file=$(mktemp --tmpdir="$TEMP_DIR_LOGS" 2>/dev/null) || return 1
{
printf "[%s]\n" "$(date "+%Y-%m-%d %H:%M:%S")"
if [[ -n "$input_file" ]]; then
printf " > Input file: %s\n" "$input_file"
fi
if [[ -n "$output_file" ]]; then
printf " > Output file: %s\n" "$output_file"
fi
printf " > %s\n" "Error: $message"
if [[ -n "$std_output" ]]; then
printf " > Standard output:\n"
printf "%s\n" "$std_output"
fi
printf "\n"
} >"$log_temp_file"
}
# FUNCTION: _logs_consolidate
#
# DESCRIPTION:
# This function gathers all error logs from a temporary directory and
# compiles them into a single consolidated log file. If any error logs are
# found, it displays an error message indicating the location of the
# consolidated log file and terminates the script.
#
# PARAMETERS:
# $1 (output_dir): Optional. The directory where the consolidated log
# file will be saved. If not specified, a default directory is used.
_logs_consolidate() {
local output_dir=$1
local log_file_output="$output_dir/$PREFIX_ERROR_LOG_FILE.log"
local log_files_count=""
# Do nothing if there are no error log files.
log_files_count="$(find "$TEMP_DIR_LOGS" -type f 2>/dev/null | wc -l)"
if ((log_files_count == 0)); then
return 0
fi
if [[ -z "$output_dir" ]]; then
output_dir=$(_get_output_dir "par_use_same_dir=true")
fi
log_file_output="$output_dir/$PREFIX_ERROR_LOG_FILE.log"
# If the file already exists, add a suffix.
log_file_output=$(_get_filename_next_suffix "$log_file_output")
# Compile log errors in a single file.
{
printf "Script: '%s'.\n" "$(_get_script_name)"
printf "Total errors: %s.\n\n" "$log_files_count"
cat -- "$TEMP_DIR_LOGS/"* 2>/dev/null
} >"$log_file_output"
local log_file=""
log_file=$(_str_human_readable_path "$log_file_output")
local msg=""
msg="$(_i18n 'Finished with errors! See the log:')"
_display_error_box "$msg $log_file"
_exit_script
}
# FUNCTION: _run_task_parallel
#
# DESCRIPTION:
# This function runs a task in parallel for a set of input files, using a
# specified output directory for results.
#
# PARAMETERS:
# $1 (input_files): A field-separated list of file paths to process.
# $2 (output_dir): The directory where the output files will be stored.
_run_task_parallel() {
local input_files=$1
local output_dir=$2
# Execute the function '_main_task' for each file in parallel.
export -f _main_task
_run_function_parallel \
"_main_task '{}' '$output_dir'" "$input_files" "$FIELD_SEPARATOR"
}
# FUNCTION: _run_function_parallel
#
# DESCRIPTION:
# This function executes a given Bash expression or command in parallel for
# a list of input items. It uses 'xargs' to distribute execution across
# multiple processes, allowing concurrent processing and improved performance
# on multi-core systems.
#
# PARAMETERS:
# $1 (expression): The Bash expression or command to execute for each item.
# The '{}' placeholder inside the expression will be replaced by the
# current item being processed.
# $2 (items): A list of items to process, separated by the char delimiter.
# $3 (delimiter): The character used to separate items in the input list.
_run_function_parallel() {
local expression=$1
local items=$2
local delimiter=$3
# Export necessary environment variables so they are available
# within each subshell created by 'xargs'.
export \
FIELD_SEPARATOR \
GUI_BOX_HEIGHT \
GUI_BOX_WIDTH \
GUI_INFO_WIDTH \
IGNORE_FIND_PATH \
INPUT_FILES \
TEMP_CONTROL_DISPLAY_LOCKED \
TEMP_DATA_TASK \
TEMP_DATA_TEXT_BOX \
TEMP_DIR_FILENAME_LOCKS \
TEMP_DIR_ITEMS_TO_REMOVE \
TEMP_DIR_LOGS \
TEMP_DIR_STORAGE_TEXT \
TEMP_DIR_TASK
# Export functions so they can be called inside
# the parallel subprocesses executed by 'bash -c'.
export -f \
_check_output \
_cmd_magick_convert \
_command_exists \
_convert_delimited_string_to_text \
_convert_text_to_delimited_string \
_directory_pop \
_directory_push \
_display_lock \
_display_unlock \
_display_password_box \
_exit_script \
_get_file_encoding \
_get_file_mime \
_get_filename_dir \
_get_filename_extension \
_get_filename_full_path \
_get_filename_next_suffix \
_get_max_procs \
_get_output_filename \
_make_temp_dir \
_make_temp_dir_local \
_make_temp_file \
_get_working_directory \
_i18n \
_is_directory_empty \
_is_gui_session \
_log_error \
_move_file \
_storage_text_write \
_storage_text_write_ln \
_str_collapse_char \
_strip_filename_extension \
_text_remove_empty_lines \
_text_remove_pwd \
_text_uri_decode \
_translate_to_gvfs_path
# Escape single quotes in items to handle them correctly in 'xargs'
# with 'bash -c'.
items=$(sed -z "s|'|'\\\''|g" <<<"$items")
# Execute the given expression in parallel for each item.
printf "%s" "$items" | xargs \
--no-run-if-empty \
--delimiter="$delimiter" \
--max-procs="$(_get_max_procs)" \
--replace="{}" \
bash -c "$expression"
}
# -----------------------------------------------------------------------------
# SECTION: Dependency management ----
# -----------------------------------------------------------------------------
# FUNCTION: _command_exists
#
# DESCRIPTION:
# This function checks whether a given command is available on the system.
#
# PARAMETERS:
# $1 (command_check): The name of the command to verify.
#
# RETURNS:
# "0" (true): If the command is available.
# "1" (false): If the command is not available.
_command_exists() {
local command_check=$1
command -v "$command_check" &>/dev/null || return 1
}
# FUNCTION: _check_dependencies_clipboard
#
# DESCRIPTION:
# This function ensures that clipboard-related dependencies are available
# according to the current display session type (Wayland or X11). Detects the
# session type and adds the proper clipboard tool ('wl-paste' for Wayland or
# 'xclip' for X11) to the dependency list.
#
# PARAMETERS:
# $1 (dep_keys): Base list of dependency keys to check before adding
# session-specific clipboard dependencies.
_check_dependencies_clipboard() {
local dep_keys=$1
local dep_keys_final="$dep_keys "
# Try to determine the session type.
local session_type="${XDG_SESSION_TYPE:-}"
# Fallback detection in case '$XDG_SESSION_TYPE' is empty.
if [[ -z "$session_type" ]]; then
if [[ -n "${WAYLAND_DISPLAY:-}" ]]; then
session_type="wayland"
elif [[ -n "${DISPLAY:-}" ]]; then
session_type="x11"
fi
fi
case "$session_type" in
"wayland") dep_keys_final+="wl-paste" ;;
"x11") dep_keys_final+="xclip" ;;
*)
local msg=""
msg="$(_i18n 'Your system does not support clipboard operations.')"
_display_error_box "$msg"
_exit_script
;;
esac
_check_dependencies "$dep_keys_final"
}
# FUNCTION: _check_dependencies
#
# DESCRIPTION:
# This function ensures that all required dependencies are available for the
# scripts. Checks each dependency key, determines the correct package for the
# active package manager, and installs missing packages if necessary.
#
# PARAMETERS:
# $1 (dep_keys): A list of dependency keys. The list can be delimited either
# by a space ' ', a comma ',' or by a newline '\n'. These keys and its
# values are defined on file '.dependencies.sh'.
_check_dependencies() {
local dep_keys=$1
[[ -z "$dep_keys" ]] && return
# Step 1: Normalize and remove duplicates from the dependency list.
dep_keys=$(tr "\n" " " <<<"$dep_keys")
dep_keys=$(tr "," " " <<<"$dep_keys")
dep_keys=$(_str_sort "$dep_keys" " " "true")
# List of pairs in the format "<pkg_manager>:<package>".
local pairs=""
# Step 2: Resolve the package names for each dependency key.
#
# This creates a list of pairs in the format "<pkg_manager>:<package>".
# The first available package manager in '$PKG_MANAGER_PRIORITY'
# that provides the dependency definition will be used.
dep_keys=$(tr " " "$FIELD_SEPARATOR" <<<"$dep_keys")
local dep_key=""
for dep_key in $dep_keys; do
local package_names=""
_command_exists "$dep_key" && continue
# Try to find a defined package for an available package manager.
local definitions_found="false"
local pkg_manager=""
for pkg_manager in "${PKG_MANAGER_PRIORITY[@]}"; do
if ! _command_exists "$pkg_manager"; then
continue
fi
# Retrieve the package names from '.dependencies.sh'.
package_names=$(_deps_get_dependency_value \
"$dep_key" "$pkg_manager" "DEPENDENCIES_MAP")
if [[ -n "$package_names" ]]; then
definitions_found="true"
break
fi
done
# Abort if no package definition was found.
if [[ "$definitions_found" == "false" ]]; then
local msg=""
msg="$(_i18n 'Could not find a package for:')"
_display_error_box "$msg $dep_key"
_exit_script
fi
# Append resolved packages as "<pkg_manager>:<package>" pairs.
if [[ -n "$package_names" ]]; then
package_names=$(sed "s|^|$pkg_manager:|g" <<<"$package_names")
package_names=$(sed "s| | $pkg_manager:|g" <<<"$package_names")
pairs+=" $package_names"
fi
done
# Sort and prepare the list of package pairs.
pairs=$(_str_sort "$pairs" " " "true")
# Step 3: Verify which packages need installation.
local post_install_full=""
local packages_install=""
# Iterate over each "<pkg_manager>:<package>" pair.
pairs=$(tr " " "$FIELD_SEPARATOR" <<<"$pairs")
local pair=""
for pair in $pairs; do
local pkg_manager="${pair%%:*}"
local package="${pair#*:}"
local post_install=""
# Skip if the command or package is already available.
if _command_exists "$package" ||
_deps_is_package_installed "$pkg_manager" "$package"; then
continue
fi
# Retrieve optional post-install command.
post_install=$(_deps_get_dependency_value \
"$package" "$pkg_manager" "POST_INSTALL")
# Add package and post-install commands to the respective lists.
[[ -n "$package" ]] && packages_install+=" $pkg_manager:$package"
if [[ -n "$post_install" ]]; then
# Append post-install commands. Each entry must follow the format
# "<pkg_manager>:<commands>" and be separated by '\n'.
post_install_full+="$pkg_manager:$post_install;"$'\n'
fi
done
# Step 4: Install missing packages and execute post-install actions.
_deps_install_missing_packages "$packages_install" "$post_install_full"
}
# FUNCTION: _deps_get_dependency_value
#
# DESCRIPTION:
# Retrieves the value associated with a specific key-subkey pair from an
# associative array.
#
# PARAMETERS:
# $1 (key): The key whose value is being queried.
# $2 (pkg_manager): The package manager to match.
# $3 (_input_array): The name of the associative array that contains
# the mappings (<subkey>:<value> pairs).
#
# RETURNS:
# "0" (true): If a matching value is found and printed.
# "1" (false): If no matching value is found.
_deps_get_dependency_value() {
local key=$1
local pkg_manager=$2
local -n _input_array=$3
local pairs=""
# Source the configuration file that defines the mapping between commands,
# packages, and package managers. This file is used by the scripts to check
# and resolve their own dependencies.
if [[ ! -v "PACKAGE_NAME" ]]; then
source "$ROOT_DIR/.dependencies.sh"
fi
# Retrieve the raw value from the associative array.
pairs=${_input_array[$key]:-}
# Remove leading, trailing, and duplicate spaces.
pairs=$(_str_collapse_char "$pairs" " ")
# If the key does not exist or has no associated values, return failure.
if [[ -z "$pairs" ]]; then
return 0
fi
# Replace newlines with '$FIELD_SEPARATOR' for iteration.
pairs=$(tr "\n" "$FIELD_SEPARATOR" <<<"$pairs")
# Iterate over each <package_manager>:<key_value> pair.
local pair=""
for pair in $pairs; do
local subkey="${pair%%:*}"
local value="${pair#*:}"
# Remove leading, trailing, and duplicate spaces.
subkey=$(_str_collapse_char "$subkey" " ")
value=$(_str_collapse_char "$value" " ")
# Map equivalent package managers for compatibility.
case "$subkey:$pkg_manager" in
"apt:apt-get" | "dnf:rpm-ostree")
subkey=$pkg_manager
;;
esac
# Special handling for Termux (Android). Since Termux (on Android) uses
# its own package ecosystem and may share paths with 'proot-distro'
# containers, we ensure it's a real Termux session by checking that
# '$HOME' contains "com.termux", the package manager is "pkg", and the
# system reports "Android".
if [[ "$subkey" == "pkg" ]] && [[ "${HOME:-}" == *"com.termux"* ]] &&
[[ "$(uname -o)" == "Android" ]]; then
printf "%s" "$value"
return 0
fi
# If the package manager matches, print and exit successfully.
if [[ "$subkey" == "$pkg_manager" ]] || [[ "$subkey" == "*" ]]; then
printf "%s" "$value"
return 0
fi
done
# If no match was found, return failure.
return 1
}
# FUNCTION: _deps_install_missing_packages
_deps_install_missing_packages() {
local packages_install=$1
local post_install=$2
[[ -z "$packages_install" ]] && return
# Remove leading, trailing, and duplicate spaces.
packages_install=$(_str_collapse_char "$packages_install" " ")
# Format the package names for display.
local pkg_names=""
pkg_names=$(tr " " "\n" <<<"$packages_install")
pkg_names=$(sed "s|~[^\n]*||g" <<<"$pkg_names")
pkg_names=$(sed "s|^\([a-z-]*\):\(.*\)|- \2 (\1)|g" <<<"$pkg_names")
local msg=""
msg+="$(_i18n 'The following packages are missing:')"
msg+="\n"
msg+="$pkg_names"
msg+="\n\n"
msg+="$(_i18n 'Would you like to install them?')"
if ! _display_question_box "$msg"; then
_exit_script
fi
_deps_install_packages "$packages_install" "$post_install"
_deps_installation_check "$packages_install"
}
# FUNCTION: _deps_install_packages
#
# DESCRIPTION:
# This function installs specified packages using the corresponding
# package manager defined for each one. The input list must contain
# pairs in the format "<pkg_manager>:<package>" separated by spaces.
#
# Example:
# _deps_install_packages "apt-get:curl dnf:wget brew:git"
#
# Supported package managers:
# - "apt-get" : For Debian/Ubuntu systems.
# - "dnf" : For Fedora/RHEL systems.
# - "rpm-ostree" : For Fedora Atomic systems.
# - "pacman" : For Arch Linux systems.
# - "zypper" : For openSUSE systems.
# - "nix" : For Nix-based systems.
# - "brew" : For Homebrew package manager.
# - "guix" : For GNU Guix systems.
#
# PARAMETERS:
# $1 (pkg_list): A space-separated list of "<pkg_manager>:<package>" pairs.
# $2 (post_install): Optional command executed after all installations.
_deps_install_packages() {
local pairs=$1
local post_install=$2
local cmd_admin=""
local cmd_admin_available=""
local cmd_inst=""
local -A pkg_map=()
# Replace spaces with '$FIELD_SEPARATOR' for iteration.
pairs=$(tr " " "$FIELD_SEPARATOR" <<<"$pairs")
# Build a map of <pkg_manager> -> "pkg1 pkg2 ...".
local pair=""
for pair in $pairs; do
local pkg_manager="${pair%%:*}"
local package="${pair#*:}"
pkg_map["$pkg_manager"]+="$package "
done
# Determine admin command.
if ! _is_gui_session; then
_command_exists "sudo" && cmd_admin_available="sudo"
else
_command_exists "pkexec" && cmd_admin_available="pkexec"
fi
local msg=""
msg="$(_i18n 'Installing the packages. Please, wait...')"
_display_wait_box_message "$msg" "0"
# Iterate over each detected package manager.
for pkg_manager in "${!pkg_map[@]}"; do
local packages="${pkg_map[$pkg_manager]}"
packages=$(_str_collapse_char "$packages" " ")
[[ -z "$packages" ]] && continue
cmd_inst=""
cmd_admin="$cmd_admin_available"
# Define installation commands depending on the package manager.
case "$pkg_manager" in
"apt-get")
cmd_inst+="apt-get update &>/dev/null;"
cmd_inst+="apt-get -y install $packages &>/dev/null"
;;
"dnf")
cmd_inst+="dnf check-update &>/dev/null;"
cmd_inst+="dnf -y install $packages &>/dev/null"
;;
"rpm-ostree")
cmd_inst+="rpm-ostree install $packages &>/dev/null"
;;
"pacman")
cmd_inst+="pacman -Syy &>/dev/null;"
cmd_inst+="pacman --noconfirm -S $packages &>/dev/null"
;;
"zypper")
cmd_inst+="zypper refresh &>/dev/null;"
cmd_inst+="zypper --non-interactive install $packages &>/dev/null"
;;
"nix")
local nix_packages=""
local nix_channel="nixpkgs"
if grep --quiet "ID=nixos" /etc/os-release 2>/dev/null; then
nix_channel="nixos"
fi
packages=$(sed "s|~[^ ]*||g" <<<"$packages")
# Prefix packages with their channel namespace.
nix_packages="$nix_channel.$packages"
nix_packages=$(sed "s| $||g" <<<"$nix_packages")
nix_packages=$(sed "s| | $nix_channel.|g" <<<"$nix_packages")
cmd_inst+="nix-env -iA $nix_packages &>/dev/null"
# Nix does not require root for installing user packages.
cmd_admin=""
;;
"brew")
# Configure Homebrew for non-interactive and less verbose
# operation.
export HOMEBREW_VERBOSE=""
export HOMEBREW_NO_ANALYTICS=1
export HOMEBREW_NO_AUTO_UPDATE=1
export HOMEBREW_NO_COLOR=1
export HOMEBREW_NO_EMOJI=1
export HOMEBREW_NO_ENV_HINTS=1
export HOMEBREW_NO_GITHUB_API=1
# Replace spaces with '$FIELD_SEPARATOR' for iteration.
packages=$(tr " " "$FIELD_SEPARATOR" <<<"$packages")
# Homebrew: prioritize precompiled bottles instead of source
# builds. Dependencies are installed first, followed by the main
# packages.
# Each package is installed separately because installing multiple
# packages at once can break dependency resolution when using
# '--force-bottle'.
local pkg=""
for pkg in $packages; do
# Install all dependencies (recursively) using bottles.
cmd_inst+="brew deps --topological $pkg 2>/dev/null | "
cmd_inst+="xargs --no-run-if-empty -I{} "
cmd_inst+="brew install --force-bottle {} &>/dev/null;"
# Install the requested packages themselves.
cmd_inst+="brew install --force-bottle $pkg &>/dev/null;"
done
cmd_inst=$(_str_collapse_char "$cmd_inst" ";")
# Homebrew runs as a non-root user.
cmd_admin=""
;;
"guix")
cmd_inst="guix package -i $packages &>/dev/null"
;;
esac
# Execute installation.
if [[ -n "$cmd_inst" ]]; then
# Process optional post-install commands (if any). Each entry must
# follow the format "<pkg_manager>:<commands>" and be separated by
# newline characters '\n'.
if [[ -n "$post_install" ]]; then
local post_install_sel=""
post_install_sel=$(grep "^$pkg_manager:" <<<"$post_install")
post_install_sel=$(cut -d ":" -f 2- <<<"$post_install_sel")
post_install_sel=$(tr -d "\n" <<<"$post_install_sel")
if [[ -n "$post_install_sel" ]]; then
cmd_inst="$cmd_inst; $post_install_sel"
fi
fi
# If root privileges are required, prepend with 'sudo' or 'pkexec'.
$cmd_admin bash -c "$cmd_inst"
fi
done
# Close the installation progress dialog.
_close_wait_box
}
# FUNCTION: _deps_installation_check
#
# DESCRIPTION:
# This function verifies whether the specified packages were successfully
# installed using their respective package managers. It checks each pair in the
# format "<pkg_manager>:<package>" one by one, ensuring that all dependencies
# are properly installed before proceeding.
#
# PARAMETERS:
# $1 (pairs_check): A space-separated list of "<pkg_manager>:<package>".
_deps_installation_check() {
local pairs=$1
local msg=""
# Replace spaces with '$FIELD_SEPARATOR' for iteration.
pairs=$(tr " " "$FIELD_SEPARATOR" <<<"$pairs")
# Iterate over each "<pkg_manager>:<package>" pair.
local pair=""
for pair in $pairs; do
local pkg_manager="${pair%%:*}"
local package="${pair#*:}"
if _deps_is_package_installed "$pkg_manager" "$package"; then
continue
fi
# Special case for 'rpm-ostree'.
if [[ "$pkg_manager" == "rpm-ostree" ]]; then
_deps_check_rpm_ostree_requires_reboot "$package"
fi
# If the package could not be installed, show an error and exit.
msg="$(_i18n 'Could not install the package:')"
_display_error_box "$msg $package ($pkg_manager)!"
_exit_script
done
}
# FUNCTION: _deps_check_rpm_ostree_requires_reboot
#
# DESCRIPTION:
# This function checks if a package installed via 'rpm-ostree' requires
# a system reboot to take effect. If the package is found in the current
# deployment list, it indicates that a reboot is necessary.
#
# PARAMETERS:
# $1 (package): The name of the package to check.
_deps_check_rpm_ostree_requires_reboot() {
local package=$1
local msg=""
msg="$(_i18n 'The package was installed, but a system reboot is required.')"
# Check if the package appears in the 'rpm-ostree' deployment list.
if rpm-ostree status --json | jq -r ".deployments[0].packages[]" |
grep -qxF "$package"; then
_display_info_box "$msg ($package)"
_exit_script
fi
}
# FUNCTION: _deps_is_package_installed
#
# DESCRIPTION:
# This function checks if a specific package is installed using the given
# package manager.
#
# PARAMETERS:
# $1 (pkg_manager): The package manager to use for the check.
# Supported values:
# - "apt-get" : For Debian/Ubuntu systems.
# - "dnf" : For Fedora/RHEL systems.
# - "rpm-ostree" : For Fedora Atomic systems.
# - "pacman" : For Arch Linux systems.
# - "zypper" : For openSUSE systems.
# - "nix" : For Nix-based systems.
# - "brew" : For Homebrew package manager.
# - "guix" : For GNU Guix systems.
# $2 (package): The name of the package to check.
#
# RETURNS:
# "0" (true): If the package is installed.
# "1" (false): If the package is not installed or an error occurs.
_deps_is_package_installed() {
local pkg_manager=$1
local package=$2
# Keep only the package name after '~' for verification, used when install
# and check package names differ (e.g., on NixOS).
if [[ "$package" == *"~"* ]]; then
package=$(sed "s|[A-Za-z0-9.-]*~||g" <<<"$package")
fi
case "$pkg_manager" in
"apt-get")
if dpkg -s "$package" &>/dev/null; then
return 0
fi
;;
"dnf")
if dnf repoquery --installed --qf "%{name}\n" |
grep -qxF "$package"; then
return 0
fi
;;
"rpm-ostree")
_deps_check_rpm_ostree_requires_reboot "$package"
if rpm -qa --qf "%{name}\n" | grep -qxF "$package"; then
return 0
fi
;;
"pacman")
if pacman -Q "$package" &>/dev/null; then
return 0
fi
;;
"zypper")
if zypper search --installed-only "$package" | grep --quiet "^i"; then
return 0
fi
;;
"nix")
if nix-env -q | grep --quiet "^$package"; then