• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

CyberShadow / aconfmgr / 470

26 Mar 2024 06:13PM UTC coverage: 80.669% (-13.0%) from 93.672%
470

push

github

CyberShadow-Renovate
Update dependency paru to v20240326042315

0 of 1 new or added line in 1 file covered. (0.0%)

464 existing lines in 23 files now uncovered.

3209 of 3978 relevant lines covered (80.67%)

140.08 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

60.16
/src/common.bash
1
# common.bash
2

3
# This file contains aconfmgr's common code, used by all commands.
4

5
####################################################################################################
6

7
# Globals
8

9
PACMAN=${PACMAN:-pacman}
1,513✔
10

11
output_dir="$tmp_dir"/output
1,513✔
12
system_dir="$tmp_dir"/system # Current system configuration, to be compared against the output directory
1,513✔
13

14
# The directory used for building AUR packages.
15
# When running as root, our "$tmp_dir" will be inaccessible to
16
# the user under which the building is performed ("nobody"),
17
# so we need a separate directory under this circumstance.
18
if [[ $EUID == 0 ]]
1,513✔
19
then
20
        aur_dir="$tmp_dir"-aur
×
21
else
22
        aur_dir="$tmp_dir"/aur
1,513✔
23
fi
24

25
default_file_mode=644
1,513✔
26

27
ANSI_clear_line=" [0K"
1,513✔
28
ANSI_color_R=" [1;31m"
1,513✔
29
ANSI_color_G=" [1;32m"
1,513✔
30
ANSI_color_Y=" [1;33m"
1,513✔
31
ANSI_color_B=" [1;34m"
1,513✔
32
ANSI_color_M=" [1;35m"
1,513✔
33
ANSI_color_C=" [1;36m"
1,513✔
34
ANSI_color_W=" [1;39m"
1,513✔
35
ANSI_reset=" [0m"
1,513✔
36

37
verbose=0
1,513✔
38
lint_config=false
1,513✔
39
umask $((666 - default_file_mode))
1,513✔
40

41
aconfmgr_action=
1,513✔
42
aconfmgr_action_args=()
1,513✔
43

44
####################################################################################################
45

46
# Defaults
47

48
# Initial ignore path list.
49
# Can be appended to using the IgnorePath helper.
50
ignore_paths=(
1,513✔
51
    '/dev'
1,513✔
52
    '/home'
1,513✔
53
    '/media'
1,513✔
54
    '/mnt'
1,513✔
55
    '/proc'
1,513✔
56
    '/root'
1,513✔
57
    '/run'
1,513✔
58
    '/sys'
1,513✔
59
    '/tmp'
1,513✔
60
    # '/var/.updated'
1,513✔
61
    '/var/cache'
1,513✔
62
    # '/var/lib'
1,513✔
63
    # '/var/lock'
1,513✔
64
    # '/var/log'
1,513✔
65
    # '/var/spool'
1,513✔
66
)
1,513✔
67

68
# These files must be installed before anything else,
69
# because they affect or are required for what follows.
70
# shellcheck disable=SC2034
71
priority_files=(
1,513✔
72
        /etc/passwd
1,513✔
73
        /etc/group
1,513✔
74
        /etc/pacman.conf
1,513✔
75
        /etc/pacman.d/mirrorlist
1,513✔
76
        /etc/makepkg.conf
1,513✔
77
)
1,513✔
78

79
# File content filters
80
# These are useful for files which contain some unpredictable element,
81
# such as a timestamp, which can't be considered as part of the system
82
# configuration, and can be safely omitted from the file.
83
# This is an associative array of patterns mapping to function
84
# names. The function is called with the file name as the only
85
# parameter, the file contents on its stdin, and is expected to
86
# provide the filtered contents on its stdout.
87
declare -A file_content_filters
1,513✔
88

89
# Some limits for common-sense warnings.
90
# Feel free to override these in your configuration.
91
warn_size_threshold=$((10*1024*1024)) # Warn on copying files bigger than this
1,513✔
92
warn_file_count_threshold=1000        # Warn on finding this many stray files
1,513✔
93
warn_tmp_df_threshold=$((1024*1024))  # Warn on error if free space in $tmp_dir is below this
1,513✔
94

95
makepkg_user=nobody # when running as root
1,513✔
96

97
####################################################################################################
98

99
function LogLeaveDirStats() {
100
        local dir="$1"
130✔
101
        Log 'Finalizing...\r'
130✔
102
        LogLeave 'Done (%s native packages, %s foreign packages, %s files).\n'        \
1,040✔
103
                         "$(Color G "$(wc -l < "$dir"/packages.txt)")"                                        \
×
104
                         "$(Color G "$(wc -l < "$dir"/foreign-packages.txt)")"                        \
×
105
                         "$(Color G "$(find "$dir"/files -not -type d | wc -l)")"
×
106
}
107

108
skip_config=n
1,513✔
109

110
# Run user configuration scripts, to collect desired state into #output_dir
111
function AconfCompileOutput() {
112
        LogEnter 'Compiling user configuration...\n'
77✔
113

114
        if [[ $skip_config == y ]]
77✔
115
        then
116
                LogLeave 'Skipped.\n'
1✔
117
                return
1✔
118
        fi
119

120
        # shellcheck disable=SC2174
121
        mkdir --mode=700 --parents "$tmp_dir"
76✔
122

123
        rm -rf "$output_dir"
76✔
124
        mkdir --parents "$output_dir"
76✔
125
        mkdir "$output_dir"/files
76✔
126
        touch "$output_dir"/packages.txt
76✔
127
        touch "$output_dir"/foreign-packages.txt
76✔
128
        touch "$output_dir"/file-props.txt
76✔
129
        touch "$output_dir"/warnings
76✔
130
        # shellcheck disable=SC2174
131
        mkdir --mode=700 --parents "$config_dir"
76✔
132

133
        # Configuration
134

135
        Log 'Using configuration in %s\n' "$(Color C "%q" "$config_dir")"
152✔
136

137
        typeset -ag ignore_packages=()
152✔
138
        typeset -ag ignore_foreign_packages=()
152✔
139
        typeset -Ag used_files
76✔
140

141
        local found=n
76✔
142
        local file
76✔
143
        for file in "$config_dir"/*.sh
79✔
144
        do
145
                if [[ -e "$file" ]]
79✔
146
                then
147
                        LogEnter 'Sourcing %s...\n' "$(Color C "%q" "$file")"
122✔
148
                        # shellcheck source=/dev/null
149
                        source "$file"
61✔
150
                        found=y
61✔
151
                        LogLeave ''
61✔
152
                fi
153
        done
154

155
        if $lint_config
76✔
156
        then
157
                # Check for unused files (files not referenced by the CopyFile
158
                # helper).
159
                # Only do this in the "check" action, as unused files do not
160
                # necessarily indicate a bug in the configuration - they may
161
                # simply be used under certain conditions.
162
                if [[ -d "$config_dir"/files ]]
3✔
163
                then
164
                        local line
2✔
165
                        find "$config_dir"/files -type f -print0 | \
2✔
166
                                while read -r -d $'\0' line
4✔
167
                                do
168
                                        local key=${line#"$config_dir"/files}
2✔
169
                                        if [[ -z "${used_files[$key]+x}" ]]
2✔
170
                                        then
171
                                                ConfigWarning 'Unused file: %s\n' \
2✔
172
                                                                          "$(Color C "%q" "$line")"
2✔
173
                                        fi
174
                                done
175
                fi
176
        fi
177

178
        if [[ $found == y ]]
76✔
179
        then
180
                LogLeaveDirStats "$output_dir"
58✔
181
        else
182
                LogLeave 'Done (configuration not found).\n'
18✔
183
        fi
184
}
185

186
skip_inspection=n
1,513✔
187
skip_checksums=n
1,513✔
188

189
# Given a list of paths to ignore (which can contain shell patterns),
190
# creates the list of arguments to give to 'find' to ignore them.
191
# The result is stored in the variable given by name as the first argument.
192
function AconfCreateFindIgnoreArgs() {
193
        # A correct and simple implementation of this function would just give
194
        # each argument as a parameter to find's -wholename, e.g. result in
195
        # (-wholename path1 -o -wholename path2 -o ... -o -wholename pathn)
196
        # However, this is painfully slow if the number of ignore patterns is large
197
        # Instead, this function (ab)uses the fact that if the number of patterns
198
        # given to GNU find is big, then as an implementation detail, using regular
199
        # expressions (-regex option and similar) scales much better than using
200
        # shell patterns (-wholename option and similar)
201
        local ignore_args_varname=$1
72✔
202
        local -n ignore_args_var=$ignore_args_varname
72✔
203
        shift
72✔
204
        local ignore_paths=("$@")
144✔
205

206
        # Divide the ignore paths as simple (contain obviously literal ASCII
207
        # characters or an asterisk wildcard) or complex (such as those using
208
        # character ranges, question mark wildcards, international characters, etc.)
209
        # Simple ignore paths are later going to be converted to regex,
210
        # complex ignore paths are passed literally to find's -wholename
211
        local simple_ignore_paths=()
144✔
212

213
        local ignore_path
72✔
214
        for ignore_path in "${ignore_paths[@]}"
740✔
215
        do
216
                # In this regular expression, we don't use ranges like "a-z", since this
217
                # can match non-ASCII characters. Also, the hyphen is at the end of the
218
                # regular expression to avoid it being interpreted as a range
219
                if [[ "$ignore_path" =~ [^abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/\ .*-] ]]
740✔
220
                then
221
                        ignore_args_var+=(-wholename "$ignore_path" -o)
5✔
222
                else
223
                        simple_ignore_paths+=("${ignore_path}")
735✔
224
                fi
225
        done
226

227
        if [ ${#simple_ignore_paths[@]} -ne 0 ]
72✔
228
        then
229
                # Converting the simple ignore paths to regular expressions just needs to
230
                # handle the asterisk wildcard, and escape a few characters
231
                local ignore_regexps
72✔
232
                echo -n "${simple_ignore_paths[*]}" | \
72✔
233
                        sed 's|[^*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/ ]|[&]|g; s|\*|.*|g' | \
72✔
234
                        mapfile -t ignore_regexps
72✔
235

236
                ignore_args_var+=(-regex "$( IFS='|' ; echo "${ignore_regexps[*]}" )" -o)
216✔
237
        fi
238

239
        ignore_args_var+=(-false)
72✔
240
}
241

242
# Collect system state into $system_dir
243
function AconfCompileSystem() {
244
        LogEnter 'Inspecting system state...\n'
73✔
245

246
        if [[ $skip_inspection == y ]]
73✔
247
        then
248
                LogLeave 'Skipped.\n'
1✔
249
                return
1✔
250
        fi
251

252
        # shellcheck disable=SC2174
253
        mkdir --mode=700 --parents "$tmp_dir"
72✔
254

255
        rm -rf "$system_dir"
72✔
256
        mkdir --parents "$system_dir"
72✔
257
        mkdir "$system_dir"/files
72✔
258
        touch "$system_dir"/file-props.txt
72✔
259
        touch "$system_dir"/orig-file-props.txt
72✔
260

261
        ### Packages
262

263
        LogEnter 'Querying package list...\n'
72✔
264
        ( "$PACMAN" --query --quiet --explicit --native  || true ) | sort | ( grep -vFxf <(PrintArray ignore_packages        ) || true ) > "$system_dir"/packages.txt
382✔
265
        ( "$PACMAN" --query --quiet --explicit --foreign || true ) | sort | ( grep -vFxf <(PrintArray ignore_foreign_packages) || true ) > "$system_dir"/foreign-packages.txt
430✔
266
        LogLeave
72✔
267

268
        ### Files
269

270
        local -a found_files
72✔
271
        found_files=()
72✔
272

273
        # whether the contents is different from the original
274
        local -A found_file_edited
72✔
275
        found_file_edited=()
72✔
276

277
        # Stray files
278

279
        local -a ignore_args
72✔
280
        AconfCreateFindIgnoreArgs ignore_args "${ignore_paths[@]}"
72✔
281

282
        LogEnter 'Enumerating owned files...\n'
72✔
283
        mkdir --parents "$tmp_dir"
72✔
284
        ( "$PACMAN" --query --list --quiet || true ) | sed 's#\/$##' | sort --unique > "$tmp_dir"/owned-files
216✔
285
        LogLeave
72✔
286

287
        LogEnter 'Searching for stray files...\n'
72✔
288

289
        local line
72✔
290
        local -Ag ignored_dirs
72✔
291

292
        AconfNeedProgram gawk gawk n
72✔
293

294
        # Progress display - only show file names once per second
295
        local progress_fd
72✔
296
        exec {progress_fd}> \
72✔
297
                 >( gawk '
72✔
298
BEGIN {
×
299
    RS = "\0";
×
300
    t = systime();
×
301
};
×
302
{
303
    u = systime();
×
304
    if (t != u) {
×
305
        t = u;
×
306
        printf "%s\0", $0;
×
307
        system(""); # https://unix.stackexchange.com/a/83853/4830
×
308
        }
145✔
UNCOV
309
}' | \
×
310
                                while read -r -d $'\0' line
1✔
311
                                do
1✔
312
                                        local path=${line:1}
1✔
313
                                        path=${path%/*} # Never show files, only directories
×
UNCOV
314
                                        while [[ ${#path} -gt 40 ]]
×
315
                                        do
316
                                                path=${path%/*}
2✔
317
                                        done
318
                                        Log 'Scanning %s...\r' "$(Color M "%q" "$path")"
×
319
                                done
320
                  )
×
321

322
        local stray_file_count=0
72✔
323
        (
324
                # NB: Regular expressions can be generated by AconfCreateFindIgnoreArgs
325
                #     The posix-extended regex type is used since it's easier to work
326
                #     with (e.g. no need to escape '|' alternations, parenthesis, etc.)
327
                sudo find /                                                                        \
72✔
328
                         -regextype posix-extended                                \
×
329
                         -not                                                                        \
×
330
                         \(                                                                                \
×
331
                                 \(                                                                        \
×
332
                                        "${ignore_args[@]}"                                \
×
333
                                \)                                                                        \
×
334
                                -printf 'I' -print0 -prune                        \
×
335
                        \)                                                                                \
×
336
                        -printf 'O' -print0                                                \
×
337
                        | tee /dev/fd/$progress_fd                                \
72✔
338
                        | ( grep                                                                \
×
339
                                        --null --null-data                                \
144✔
340
                                        --invert-match                                        \
×
341
                                        --fixed-strings                                        \
×
342
                                        --line-regexp                                        \
×
343
                                        --file                                                        \
×
344
                                        <( < "$tmp_dir"/owned-files                \
×
345
                                                 sed -e 's#^#O#'                        \
×
346
                                         )                                                                \
×
347
                                        || true )                                                \
×
348
        ) |                                                                                                \
×
349
                while read -r -d $'\0' line
269✔
350
                do
351
                        local file action
197✔
352
                        file=${line:1}
197✔
353
                        action=${line:0:1}
197✔
354

355
                        case "$action" in
197✔
356
                                O) # Stray file
357
                                        #echo "ignore_paths+='$file' # "
358
                                        if ((verbose))
143✔
359
                                        then
360
                                                Log '%s\r' "$(Color C "%q" "$file")"
×
361
                                        fi
362

363
                                        found_files+=("$file")
143✔
364
                                        found_file_edited[$file]=y
143✔
365
                                        stray_file_count=$((stray_file_count+1))
143✔
366

367
                                        if [[ $stray_file_count -eq $warn_file_count_threshold ]]
143✔
368
                                        then
369
                                                LogEnter '%s: reached %s stray files while in directory %s.\n' \
×
370
                                                        "$(Color Y "Warning")" \
×
371
                                                        "$(Color G "$stray_file_count")" \
×
372
                                                        "$(Color C "%q" "$(dirname "$file")")"
×
373
                                                LogLeave 'Perhaps add %s (or a parent directory) to configuration to ignore it.\n' \
×
374
                                                                 "$(Color Y "IgnorePath %q" "$(dirname "$file")"/'*')"
×
375
                                                warn_file_count_threshold=$((warn_file_count_threshold * 10))
×
376
                                        fi
377
                                        ;;
378
                                I) # Ignored
379

380
                                        # For convenience, we want to also ignore
381
                                        # directories which contain only ignored files.
382
                                        #
383
                                        # This is so that a rule such as:
384
                                        #
385
                                        # IgnorePath '/foo/bar/baz/*.log'
386
                                        #
387
                                        # does not cause `aconfmgr save` to still emit lines like
388
                                        #
389
                                        # CreateDir /foo/bar
390
                                        # CreateDir /foo/bar/baz
391
                                        #
392
                                        # However, we can't simply exclude parent dirs of
393
                                        # excluded files from the file list, as then they
394
                                        # will show up as missing in the diff against the
395
                                        # compiled configuration. So, later we remove
396
                                        # parent directories of any found un-ignored
397
                                        # files.
398

399
                                        local path="$file"
54✔
400
                                        while [[ -n "$path" ]]
146✔
401
                                        do
402
                                                ignored_dirs[$path]=y
92✔
403
                                                path=${path%/*}
92✔
404
                                        done
405
                                        ;;
406
                        esac
407
                done
408

409
        LogLeave 'Done (%s stray files).\n' "$(Color G %s $stray_file_count)"
144✔
410

411
        exec {progress_fd}<&-
72✔
412

413
        LogEnter 'Cleaning up ignored files'\'' directories...\n'
72✔
414

415
        local file
72✔
416
        for file in "${found_files[@]}"
143✔
417
        do
418
                if [[ -z "${ignored_dirs[$file]+x}" ]]
143✔
419
                then
420
                        local path="$file"
109✔
421
                        while [[ -n "$path" ]]
233✔
422
                        do
423
                                unset "ignored_dirs[\$path]"
124✔
424
                                path=${path%/*}
124✔
425
                        done
426
                fi
427
        done
428

429
        LogLeave
72✔
430

431
        # Modified files
432

433
        LogEnter 'Searching for modified files...\n'
72✔
434

435
        AconfNeedProgram paccheck pacutils n
72✔
436
        AconfNeedProgram unbuffer expect n
72✔
437
        local modified_file_count=0
72✔
438
        local -A saw_file
72✔
439

440
        # Tentative tracking of original file properties.
441
        # The canonical version is read from orig-file-props.txt in AconfAnalyzeFiles
442
        unset orig_file_props ; typeset -Ag orig_file_props
144✔
443

444
        : > "$tmp_dir"/file-owners
72✔
445

446
        local paccheck_opts=(unbuffer paccheck --files --file-properties --backup --noupgrade)
144✔
447
        if [[ $skip_checksums == n ]]
72✔
448
        then
449
                paccheck_opts+=(--md5sum)
69✔
450
        fi
451

452
        sudo sh -c "LC_ALL=C stdbuf -o0 $(printf ' %q' "${paccheck_opts[@]}") 2>&1 || true" | \
144✔
453
                while read -r line
492✔
454
                do
455
                        if [[ $line =~ ^(.*):\ \'(.*)\'\ (type|size|modification\ time|md5sum|UID|GID|permission|symlink\ target)\ mismatch\ \(expected\ (.*)\)$ ]]
420✔
456
                        then
457
                                local package="${BASH_REMATCH[1]}"
113✔
458
                                local file="${BASH_REMATCH[2]}"
113✔
459
                                local kind="${BASH_REMATCH[3]}"
113✔
460
                                local value="${BASH_REMATCH[4]}"
113✔
461

462
                                local ignored=n
113✔
463
                                local ignore_path
113✔
464
                                for ignore_path in "${ignore_paths[@]}"
1,613✔
465
                                do
466
                                        # shellcheck disable=SC2053
467
                                        if [[ "$file" == $ignore_path ]]
1,613✔
468
                                        then
469
                                                ignored=y
15✔
470
                                                break
15✔
471
                                        fi
472
                                done
473

474
                                if [[ $ignored == n ]]
113✔
475
                                then
476
                                        if [[ -z "${saw_file[$file]+x}" ]]
98✔
477
                                        then
478
                                                saw_file[$file]=y
35✔
479
                                                Log '%s: %s\n' "$(Color M "%q" "$package")" "$(Color C "%q" "$file")"
105✔
480
                                                found_files+=("$file")
35✔
481
                                                modified_file_count=$((modified_file_count+1))
35✔
482
                                        fi
483

484
                                        local prop
98✔
485
                                        case "$kind" in
98✔
486
                                                UID)
487
                                                        prop=owner
15✔
488
                                                        value=${value#*/}
15✔
489
                                                        ;;
490
                                                GID)
491
                                                        prop=group
15✔
492
                                                        value=${value#*/}
15✔
493
                                                        ;;
494
                                                permission)
495
                                                        prop=mode
20✔
496
                                                        ;;
497
                                                type|size|modification\ time|md5sum|symlink\ target)
498
                                                        prop=
48✔
499
                                                        found_file_edited[$file]=y
48✔
500
                                                        ;;
501
                                                *)
502
                                                        prop=
×
503
                                                        ;;
504
                                        esac
505

506
                                        if [[ -n "$prop" ]]
98✔
507
                                        then
508
                                                local key="$file:$prop"
50✔
509
                                                orig_file_props[$key]=$value
50✔
510

511
                                                printf '%s\t%s\t%q\n' "$prop" "$value" "$file" >> "$system_dir"/orig-file-props.txt
50✔
512
                                        fi
513
                                fi
514
                                printf '%s\0%s\0' "$file" "$package" >> "$tmp_dir"/file-owners
113✔
515
                        elif [[ $line =~ ^(.*):\ \'(.*)\'\ missing\ file$ ]]
307✔
516
                        then
517
                                local package="${BASH_REMATCH[1]}"
9✔
518
                                local file="${BASH_REMATCH[2]}"
9✔
519

520
                                local ignored=n
9✔
521
                                local ignore_path
9✔
522
                                for ignore_path in "${ignore_paths[@]}"
150✔
523
                                do
524
                                        # shellcheck disable=SC2053
525
                                        if [[ "$file" == $ignore_path ]]
150✔
526
                                        then
527
                                                ignored=y
2✔
528
                                                break
2✔
529
                                        fi
530
                                done
531

532
                                if [[ $ignored == y ]]
9✔
533
                                then
534
                                        continue
2✔
535
                                fi
536

537
                                Log '%s (missing)...\r' "$(Color M "%q" "$package")"
14✔
538
                                printf '%s\t%s\t%q\n' "deleted" "y" "$file" >> "$system_dir"/file-props.txt
7✔
539
                                printf '%s\0%s\0' "$file" "$package" >> "$tmp_dir"/file-owners
7✔
540
                        elif [[ $line =~ ^warning:\ (.*):\ \'(.*)\'\ read\ error\ \(No\ such\ file\ or\ directory\)$ ]]
298✔
541
                        then
542
                                local package="${BASH_REMATCH[1]}"
206✔
543
                                local file="${BASH_REMATCH[2]}"
206✔
544
                                # Ignore
545
                        elif [[ $line =~ ^(.*):\ all\ files\ match\ (database|mtree|mtree\ md5sums)$ ]]
92✔
546
                        then
547
                                local package="${BASH_REMATCH[1]}"
92✔
548
                                Log '%s...\r' "$(Color M "%q" "$package")"
184✔
549
                                #echo "Now at ${BASH_REMATCH[1]}"
550
                        else
UNCOV
551
                                Log 'Unknown paccheck output line: %s\n' "$(Color Y "%q" "$line")"
×
552
                        fi
553
                done
554
        LogLeave 'Done (%s modified files).\n' "$(Color G %s $modified_file_count)"
144✔
555

556
        LogEnter 'Reading file attributes...\n'
72✔
557

558
        typeset -a found_file_types found_file_sizes found_file_modes found_file_owners found_file_groups
72✔
559
        if [[ ${#found_files[*]} == 0 ]]
72✔
560
        then
561
                Log 'No files found, skipping.\n'
×
562
        else
563
                Log 'Reading file types...\n'  ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%F | mapfile -t  found_file_types
288✔
564
                Log 'Reading file sizes...\n'  ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%s | mapfile -t  found_file_sizes
288✔
565
                Log 'Reading file modes...\n'  ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%a | mapfile -t  found_file_modes
288✔
566
                Log 'Reading file owners...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%U | mapfile -t found_file_owners
288✔
567
                Log 'Reading file groups...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%G | mapfile -t found_file_groups
288✔
568
        fi
569

570
        LogLeave # Reading file attributes
72✔
571

572
        LogEnter 'Checking disk space...\n'
72✔
573
        local -i i
72✔
574
        local -i total_blocks=0
72✔
575
        local -i tmp_block_size tmp_blocks_free
72✔
576
        tmp_block_size=$(stat -f -c %S "$system_dir")
144✔
577
        tmp_blocks_free=$(stat -f -c %f "$system_dir")
144✔
578
        local tmp_fs_type
72✔
579
        tmp_fs_type=$(stat -f -c %T "$system_dir")
144✔
580
        if [[ "$tmp_fs_type" != "ramfs" ]]
72✔
581
        then
582
                for ((i=0; i<${#found_files[*]}; i++))
500✔
583
                do
584
                        local -i size="${found_file_sizes[$i]}"
178✔
585
                        local -i blocks=$(((size+tmp_block_size-1)/tmp_block_size)) # Count blocks
178✔
586
                        total_blocks+=$blocks
178✔
587
                        if (( total_blocks >= tmp_blocks_free ))
178✔
588
                        then
589
                                local file="${found_files[$i]}"
×
590
                                Log 'Copying file %s (%s bytes / %s blocks) to temporary storage would exhaust free space on %s (%s bytes / %s blocks).\n' \
×
591
                                        "$(Color C "%q" "$file")" "$(Color G "$size")" "$(Color G "$blocks")" \
×
592
                                        "$(Color C "%q" "$system_dir")" "$(Color G "$((tmp_blocks_free * tmp_block_size))")" "$(Color G "$tmp_blocks_free")"
×
593
                                Log 'Perhaps add %s (or a parent directory) to configuration to ignore it, or run with %s pointing at another location.\n' \
×
594
                                        "$(Color Y "IgnorePath %q" "$(dirname "$file")"/'*')" "$(Color Y "TMPDIR")"
×
595
                                FatalError 'Refusing to proceed.\n'
×
596
                        fi
597
                done
598
        fi
599
        LogLeave
72✔
600

601
        LogEnter 'Processing found files...\n'
72✔
602

603
        for ((i=0; i<${#found_files[*]}; i++))
500✔
604
        do
605
                Log '%s/%s...\r' "$(Color G "$i")" "$(Color G "${#found_files[*]}")"
534✔
606

607
                local  file="${found_files[$i]}"
178✔
608
                local  type="${found_file_types[$i]}"
178✔
609
                local  size="${found_file_sizes[$i]}"
178✔
610
                local  mode="${found_file_modes[$i]}"
178✔
611
                local owner="${found_file_owners[$i]}"
178✔
612
                local group="${found_file_groups[$i]}"
178✔
613

614
                if [[ "${ignored_dirs[$file]-n}" == y ]]
178✔
615
                then
616
                        continue
33✔
617
                fi
618

619
                if [[ -n "${found_file_edited[$file]+x}" ]]
145✔
620
                then
621
                        mkdir --parents "$(dirname "$system_dir"/files/"$file")"
288✔
622
                        if [[ "$type" == "symbolic link" ]]
144✔
623
                        then
624
                                ln -s -- "$(sudo readlink "$file")" "$system_dir"/files/"$file"
36✔
625
                        elif [[ "$type" == "regular file" || "$type" == "regular empty file" ]]
220✔
626
                        then
627
                                if [[ $size -gt $warn_size_threshold ]]
34✔
628
                                then
629
                                        Log '%s: copying large file %s (%s bytes). Add %s to configuration to ignore.\n' "$(Color Y "Warning")" "$(Color C "%q" "$file")" "$(Color G "$size")" "$(Color Y "IgnorePath %q" "$file")"
×
630
                                fi
631

632
                                local filter_pattern filter_func
34✔
633
                                unset filter_func
34✔
634
                                for filter_pattern in "${!file_content_filters[@]}"
3✔
635
                                do
636
                                        # shellcheck disable=SC2053
637
                                        if [[ "$file" == $filter_pattern ]]
3✔
638
                                        then
639
                                                filter_func=${file_content_filters[$filter_pattern]}
3✔
640
                                        fi
641
                                done
642

643
                                if [[ -v filter_func ]]
34✔
644
                                then
645
                                        sudo cat "$file" | "$filter_func" "$file" > "$system_dir"/files/"$file"
6✔
646
                                else
647
                                        # shellcheck disable=SC2024
648
                                        sudo cat "$file" > "$system_dir"/files/"$file"
31✔
649
                                fi
650
                        elif [[ "$type" == "directory" ]]
92✔
651
                        then
652
                                mkdir --parents "$system_dir"/files/"$file"
92✔
653
                        else
654
                                Log '%s: Skipping file %s with unknown type %s. Add %s to configuration to ignore.\n' "$(Color Y "Warning")" "$(Color C "%q" "$file")" "$(Color G "$type")" "$(Color Y "IgnorePath %q" "$file")"
×
655
                                continue
×
656
                        fi
657
                fi
658

659
                {
660
                        local prop
145✔
661
                        for prop in mode owner group
435✔
662
                        do
663
                                # Ignore mode "changes" in symbolic links
664
                                # If a file's type changes, a change in mode can be reported too.
665
                                # But, symbolic links cannot have a mode, so ignore this change.
666
                                if [[ "$type" == "symbolic link" && "$prop" == mode ]]
489✔
667
                                then
668
                                        continue
18✔
669
                                fi
670

671
                                local value
417✔
672
                                eval "value=\$$prop"
834✔
673

674
                                local default_value
417✔
675

676
                                if [[ $i -lt $stray_file_count ]]
417✔
677
                                then
678
                                        # For stray files, the default owner/group is root/root,
679
                                        # and the default mode depends on the type.
680
                                        # Let AconfDefaultFileProp get the correct default value for us.
681

682
                                        default_value=
327✔
683
                                else
684
                                        # For owned files, we assume that the defaults are the
685
                                        # files' current properties, unless paccheck said
686
                                        # otherwise.
687

688
                                        default_value=$value
90✔
689
                                fi
690

691
                                local orig_value
417✔
692
                                orig_value=$(AconfDefaultFileProp "$file" "$prop" "$type" "$default_value")
834✔
693

694
                                [[ "$value" == "$orig_value" ]] || printf '%s\t%s\t%q\n' "$prop" "$value" "$file"
476✔
695
                        done
696
                } >> "$system_dir"/file-props.txt
×
697
        done
698

699
        LogLeave # Processing found files
72✔
700

701
        LogLeaveDirStats "$system_dir" # Inspecting system state
72✔
702
}
703

704
####################################################################################################
705

706
typeset -A file_property_kind_exists
1,513✔
707

708
# Print to stdout the original/default value of the given file property.
709
# Uses orig_file_props entry if present.
710
function AconfDefaultFileProp() {
711
        local file=$1 # Absolute path to the file
426✔
712
        local prop=$2 # Name of the property (owner, group, or mode)
426✔
713
        local type="${3:-}" # Type of the file, as identified by `stat --format=%F`
426✔
714
        local default="${4:-}" # Default value, returned if we don't know the original file property.
426✔
715

716
        local key="$file:$prop"
426✔
717

718
        if [[ -n "${orig_file_props[$key]+x}" ]]
426✔
719
        then
720
                printf '%s' "${orig_file_props[$key]}"
40✔
721
                return
40✔
722
        fi
723

724
        if [[ -n "$default" ]]
386✔
725
        then
726
                printf '%s' "$default"
50✔
727
                return
50✔
728
        fi
729

730
        case "$prop" in
336✔
731
                mode)
732
                        if [[ -z "$type" ]]
110✔
733
                        then
734
                                type=$(sudo env LC_ALL=C stat --format=%F "$file")
6✔
735
                        fi
736

737
                        if [[ "$type" == "symbolic link" ]]
110✔
738
                        then
739
                                FatalError 'Symbolic links do not have a mode\n' # Bug
×
740
                        elif [[ "$type" == "directory" ]]
110✔
741
                        then
742
                                printf 755
82✔
743
                        else
744
                                printf '%s' "$default_file_mode"
28✔
745
                        fi
746
                        ;;
747
                owner|group)
748
                        printf 'root'
226✔
749
                        ;;
750
        esac
751
}
752

753
# Read a file-props.txt file into an associative array.
754
function AconfReadFileProps() {
755
        local filename="$1" # Path to file-props.txt to be read
210✔
756
        local varname="$2"  # Name of global associative array variable to read into
210✔
757

758
        local line
210✔
759
        while read -r line
670✔
760
        do
761
                if [[ $line =~ ^(.*)\        (.*)\        (.*)$ ]]
460✔
762
                then
763
                        local kind="${BASH_REMATCH[1]}"
460✔
764
                        local value="${BASH_REMATCH[2]}"
460✔
765
                        local file="${BASH_REMATCH[3]}"
460✔
766
                        file="$(eval "printf %s $file")" # Unescape
1,380✔
767

768
                        if [[ -z "$value" ]]
460✔
769
                        then
770
                                unset "${varname}[\$file:\$kind]"
119✔
771
                        else
772
                                eval "${varname}[\$file:\$kind]=\"\$value\""
682✔
773
                        fi
774

775
                        file_property_kind_exists[$kind]=y
460✔
776
                fi
777
        done < "$filename"
×
778
}
779

780
# Compare file properties.
781
function AconfCompareFileProps() {
782
        LogEnter 'Comparing file properties...\n'
139✔
783

784
        typeset -ag system_only_file_props=()
278✔
785
        typeset -ag changed_file_props=()
278✔
786
        typeset -ag config_only_file_props=()
278✔
787

788
        local key
139✔
789
        for key in "${!system_file_props[@]}"
133✔
790
        do
791
                if [[ -z "${output_file_props[$key]+x}" ]]
133✔
792
                then
793
                        system_only_file_props+=("$key")
31✔
794
                fi
795
        done
796

797
        for key in "${!system_file_props[@]}"
133✔
798
        do
799
                if [[ -n "${output_file_props[$key]+x}" && "${system_file_props[$key]}" != "${output_file_props[$key]}" ]]
235✔
800
                then
801
                        changed_file_props+=("$key")
29✔
802
                fi
803
        done
804

805
        for key in "${!output_file_props[@]}"
181✔
806
        do
807
                if [[ -z "${system_file_props[$key]+x}" ]]
181✔
808
                then
809
                        config_only_file_props+=("$key")
79✔
810
                fi
811
        done
812

813
        LogLeave
139✔
814
}
815

816
# Compare file information in $output_dir and $system_dir.
817
function AconfAnalyzeFiles() {
818

819
        #
820
        # Stray/modified files - diff
821
        #
822

823
        LogEnter 'Examining files...\n'
70✔
824

825
        LogEnter 'Loading data...\n'
70✔
826
        mkdir --parents "$tmp_dir"
70✔
827
        ( cd "$output_dir"/files && find . -mindepth 1 -print0 ) | cut --zero-terminated -c 2- | sort --zero-terminated > "$tmp_dir"/output-files
280✔
828
        ( cd "$system_dir"/files && find . -mindepth 1 -print0 ) | cut --zero-terminated -c 2- | sort --zero-terminated > "$tmp_dir"/system-files
280✔
829
        LogLeave
70✔
830

831
        Log 'Comparing file data...\n'
70✔
832

833
        typeset -ag system_only_files=()
140✔
834
        local file
70✔
835

836
        ( comm -13 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
70✔
837
                while read -r -d $'\0' file
106✔
838
                do
839
                        Log 'Only in system: %s\n' "$(Color C "%q" "$file")"
72✔
840
                        system_only_files+=("$file")
36✔
841
                done
842

843
        typeset -ag changed_files=()
140✔
844

845
        AconfNeedProgram diff diffutils n
70✔
846

847
        ( comm -12 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
70✔
848
                while read -r -d $'\0' file
123✔
849
                do
850
                        local output_type system_type
53✔
851
                        output_type=$(LC_ALL=C stat --format=%F "$output_dir"/files/"$file")
159✔
852
                        system_type=$(LC_ALL=C stat --format=%F "$system_dir"/files/"$file")
159✔
853

854
                        if [[ "$output_type" != "$system_type" ]]
53✔
855
                        then
856
                                Log 'Changed type (%s / %s): %s\n' \
80✔
857
                                        "$(Color Y "%q" "$output_type")" \
80✔
858
                                        "$(Color Y "%q" "$system_type")" \
80✔
859
                                        "$(Color C "%q" "$file")"
80✔
860
                                changed_files+=("$file")
20✔
861
                                continue
20✔
862
                        fi
863

864
                        if [[ "$output_type" == "directory" || "$system_type" == "directory" ]]
57✔
865
                        then
866
                                continue
9✔
867
                        fi
868

869
                        if ! diff --no-dereference --brief "$output_dir"/files/"$file" "$system_dir"/files/"$file" > /dev/null
24✔
870
                        then
871
                                Log 'Changed: %s\n' "$(Color C "%q" "$file")"
18✔
872
                                changed_files+=("$file")
9✔
873
                        fi
874
                done
875

876
        typeset -ag config_only_files=()
140✔
877

878
        ( comm -23 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
70✔
879
                while read -r -d $'\0' file
100✔
880
                do
881
                        Log 'Only in config: %s\n' "$(Color C "%q" "$file")"
60✔
882
                        config_only_files+=("$file")
30✔
883
                done
884

885
        LogLeave 'Done (%s only in system, %s changed, %s only in config).\n'        \
280✔
886
                         "$(Color G "${#system_only_files[@]}")"                                                \
280✔
887
                         "$(Color G "${#changed_files[@]}")"                                                        \
280✔
888
                         "$(Color G "${#config_only_files[@]}")"
280✔
889

890
        #
891
        # Modified file properties
892
        #
893

894
        LogEnter 'Examining file properties...\n'
70✔
895

896
        LogEnter 'Loading data...\n'
70✔
897
        unset orig_file_props # Also populated by AconfCompileSystem, so that it can be used by AconfDefaultFileProp
70✔
898
        typeset -Ag output_file_props ; AconfReadFileProps "$output_dir"/file-props.txt output_file_props
140✔
899
        typeset -Ag system_file_props ; AconfReadFileProps "$system_dir"/file-props.txt system_file_props
140✔
900
        typeset -Ag   orig_file_props ; AconfReadFileProps "$system_dir"/orig-file-props.txt orig_file_props
140✔
901
        LogLeave
70✔
902

903
        typeset -ag all_file_property_kinds
70✔
904
        all_file_property_kinds=("${!file_property_kind_exists[@]}")
70✔
905
        Print0Array all_file_property_kinds | sort --zero-terminated | mapfile -t -d $'\0' all_file_property_kinds
210✔
906

907
        AconfCompareFileProps
70✔
908

909
        LogLeave 'Done (%s only in system, %s changed, %s only in config).\n'        \
280✔
910
                         "$(Color G "${#system_only_file_props[@]}")"                                        \
280✔
911
                         "$(Color G "${#changed_file_props[@]}")"                                                \
280✔
912
                         "$(Color G "${#config_only_file_props[@]}")"
280✔
913
}
914

915
# The *_packages arrays are passed by name,
916
# so ShellCheck thinks the variables are unused:
917
# shellcheck disable=2034
918

919
# Prepare configuration and system state
920
function AconfCompile() {
921
        LogEnter 'Collecting data...\n'
69✔
922

923
        # Configuration
924

925
        AconfCompileOutput
69✔
926

927
        # System
928

929
        AconfCompileSystem
69✔
930

931
        # Vars
932

933
        < "$output_dir"/packages.txt         sort --unique | mapfile -t                   packages
138✔
934
        < "$system_dir"/packages.txt         sort --unique | mapfile -t         installed_packages
138✔
935

936
        < "$output_dir"/foreign-packages.txt sort --unique | mapfile -t           foreign_packages
138✔
937
        < "$system_dir"/foreign-packages.txt sort --unique | mapfile -t installed_foreign_packages
138✔
938

939
        AconfAnalyzeFiles
69✔
940

941
        LogLeave # Collecting data
69✔
942
}
943

944
####################################################################################################
945

946
pacman_opts=("$PACMAN")
1,513✔
947
aurman_opts=(aurman)
1,513✔
948
pacaur_opts=(pacaur)
1,513✔
949
yaourt_opts=(yaourt)
1,513✔
950
yay_opts=(yay)
1,513✔
951
paru_opts=(paru)
1,513✔
952
makepkg_opts=(makepkg)
1,513✔
953
diff_opts=(diff '--color=auto')
1,513✔
954

955
aur_helper=
1,513✔
956
aur_helpers=(aurman pacaur yaourt yay paru makepkg)
1,513✔
957

958
# Only aconfmgr can use makepkg under root
959
if [[ $EUID == 0 ]]
1,513✔
960
then
961
        aur_helper=makepkg
×
962
fi
963

964
function DetectAurHelper() {
UNCOV
965
        if [[ -n "$aur_helper" ]]
×
966
        then
UNCOV
967
                return
×
968
        fi
969

UNCOV
970
        LogEnter 'Detecting AUR helper...\n'
×
971

UNCOV
972
        local helper
×
UNCOV
973
        for helper in "${aur_helpers[@]}"
×
974
        do
UNCOV
975
                if hash "$helper" 2> /dev/null
×
976
                then
UNCOV
977
                        aur_helper=$helper
×
UNCOV
978
                        LogLeave '%s... Yes\n' "$(Color C %s "$helper")"
×
UNCOV
979
                        return
×
980
                fi
UNCOV
981
                Log '%s... No\n' "$(Color C %s "$helper")"
×
982
        done
983

984
        Log 'Can'\''t find even makepkg!?\n'
×
985
        Exit 1
×
986
}
987

988
base_devel_installed=n
1,513✔
989

990
function AconfMakePkg() {
UNCOV
991
        local install=true
×
UNCOV
992
        if [[ "$1" == --noinstall ]]
×
993
        then
UNCOV
994
                install=false
×
UNCOV
995
                shift
×
996
        fi
997

UNCOV
998
        local package="$1"
×
UNCOV
999
        local asdeps="${2:-false}"
×
1000

UNCOV
1001
        LogEnter 'Building foreign package %s from source.\n' "$(Color M %q "$package")"
×
1002

1003
        # shellcheck disable=SC2174
UNCOV
1004
        mkdir --parents --mode=700 "$aur_dir"
×
UNCOV
1005
        if [[ $EUID == 0 ]]
×
1006
        then
1007
                chown -R "$makepkg_user": "$aur_dir"
×
1008
        fi
1009

UNCOV
1010
        local pkg_dir="$aur_dir"/"$package"
×
UNCOV
1011
        Log 'Using directory %s.\n' "$(Color C %q "$pkg_dir")"
×
1012

UNCOV
1013
        rm -rf "$pkg_dir"
×
UNCOV
1014
        mkdir --parents "$pkg_dir"
×
1015

1016
        # Needed to clone the AUR repo. Should be replaced with curl/tar.
UNCOV
1017
        AconfNeedProgram git git n
×
1018

UNCOV
1019
        if [[ $base_devel_installed == n ]]
×
1020
        then
UNCOV
1021
                LogEnter 'Making sure the %s package is installed...\n' "$(Color M base-devel)"
×
UNCOV
1022
                ParanoidConfirm ''
×
UNCOV
1023
                if ! "$PACMAN" --query --quiet base-devel > /dev/null 2>&1
×
1024
                then
UNCOV
1025
                        AconfInstallNative base-devel
×
1026
                fi
1027

UNCOV
1028
                LogLeave
×
UNCOV
1029
                base_devel_installed=y
×
1030
        fi
1031

UNCOV
1032
        LogEnter 'Cloning...\n'
×
UNCOV
1033
        git clone "https://aur.archlinux.org/$package.git" "$pkg_dir"
×
UNCOV
1034
        LogLeave
×
1035

UNCOV
1036
        if [[ ! -f "$pkg_dir"/PKGBUILD ]]
×
1037
        then
UNCOV
1038
                Log 'No package description file found!\n'
×
1039

UNCOV
1040
                if [[ "$package" == auracle-git ]]
×
1041
                then
1042
                        FatalError 'Failed to download aconfmgr dependency!\n'
×
1043
                fi
1044

UNCOV
1045
                LogEnter 'Assuming this package is part of a package base:\n'
×
1046

UNCOV
1047
                LogEnter 'Retrieving package info...\n'
×
UNCOV
1048
                AconfNeedProgram auracle auracle-git y
×
UNCOV
1049
                local pkg_base
×
1050
                pkg_base=$(auracle info --format '{pkgbase}' "$package")
UNCOV
1051
                LogLeave 'Done, package base is %s.\n' "$(Color M %q "$pkg_base")"
×
1052

UNCOV
1053
                AconfMakePkg "$pkg_base" "$asdeps" # recurse
×
UNCOV
1054
                LogLeave # Package base
×
UNCOV
1055
                LogLeave # Package
×
UNCOV
1056
                return
×
1057
        fi
1058

UNCOV
1059
        AconfMakePkgDir "$package" "$asdeps" "$install" "$pkg_dir"
×
1060
}
1061

1062
function AconfMakePkgDir() {
UNCOV
1063
        local package=$1
×
UNCOV
1064
        local asdeps=$2
×
UNCOV
1065
        local install=$3
×
UNCOV
1066
        local pkg_dir=$4
×
1067

UNCOV
1068
        local gnupg_home
×
UNCOV
1069
        gnupg_home="$(realpath -m "$tmp_dir/gnupg")"
×
1070

UNCOV
1071
        local infofile infofilename
×
UNCOV
1072
        for infofilename in .SRCINFO .AURINFO
×
1073
        do
UNCOV
1074
                infofile="$pkg_dir"/"$infofilename"
×
UNCOV
1075
                if test -f "$infofile"
×
1076
                then
UNCOV
1077
                        LogEnter 'Checking dependencies...\n'
×
1078

UNCOV
1079
                        local depends missing_depends dependency arch
×
UNCOV
1080
                        arch="$(uname -m)"
×
1081
                        # Filter out packages from the same base
UNCOV
1082
                        ( grep -E $'^\t(make|check)?depends(_'"$arch"')? = ' "$infofile" || true ) \
×
UNCOV
1083
                                | sed 's/^.* = \([^<>=]*\)\([<>=].*\)\?$/\1/g' \
×
UNCOV
1084
                                | ( grep -vFf <(( grep '^pkgname = ' "$infofile" || true) \
×
1085
                                                                        | sed 's/^.* = \(.*\)$/\1/g' ) \
×
UNCOV
1086
                                                || true ) \
×
UNCOV
1087
                                | mapfile -t depends
×
1088

UNCOV
1089
                        if [[ ${#depends[@]} != 0 ]]
×
1090
                        then
UNCOV
1091
                                ( "$PACMAN" --deptest "${depends[@]}" || true ) | mapfile -t missing_depends
×
UNCOV
1092
                                if [[ ${#missing_depends[@]} != 0 ]]
×
1093
                                then
UNCOV
1094
                                        for dependency in "${missing_depends[@]}"
×
1095
                                        do
UNCOV
1096
                                                LogEnter '%s:\n' "$(Color M %q "$dependency")"
×
UNCOV
1097
                                                if "$PACMAN" --query --info "$dependency" > /dev/null 2>&1
×
1098
                                                then
1099
                                                        Log 'Already installed.\n' # Shouldn't happen, actually
×
UNCOV
1100
                                                elif "$PACMAN" --sync --info "$dependency" > /dev/null 2>&1
×
1101
                                                then
UNCOV
1102
                                                        Log 'Installing from repositories...\n'
×
UNCOV
1103
                                                        AconfInstallNative --asdeps "$dependency"
×
UNCOV
1104
                                                        Log 'Installed.\n'
×
1105
                                                else
UNCOV
1106
                                                        local installed=false
×
1107

1108
                                                        # Check if this package is provided by something in pacman repos.
1109
                                                        # `pacman -Si` will not give us that information,
1110
                                                        # however, `pacman -S` still works.
UNCOV
1111
                                                        AconfNeedProgram pacsift pacutils n
×
UNCOV
1112
                                                        AconfNeedProgram unbuffer expect n
×
UNCOV
1113
                                                        local providers
×
1114
                                                        providers=$(unbuffer pacsift --sync --exact --satisfies="$dependency")
UNCOV
1115
                                                        if [[ -n "$providers" ]]
×
1116
                                                        then
UNCOV
1117
                                                                Log 'Installing provider package from repositories...\n'
×
UNCOV
1118
                                                                AconfInstallNative --asdeps "$dependency"
×
UNCOV
1119
                                                                Log 'Installed.\n'
×
UNCOV
1120
                                                                installed=true
×
1121
                                                        fi
1122

UNCOV
1123
                                                        if ! $installed
×
1124
                                                        then
UNCOV
1125
                                                                Log 'Installing from AUR...\n'
×
UNCOV
1126
                                                                AconfMakePkg "$dependency" true
×
UNCOV
1127
                                                                Log 'Installed.\n'
×
1128
                                                        fi
1129
                                                fi
1130

UNCOV
1131
                                                LogLeave ''
×
1132
                                        done
1133
                                fi
1134
                        fi
1135

UNCOV
1136
                        LogLeave
×
1137

UNCOV
1138
                        local keys
×
UNCOV
1139
                        ( grep -E $'^\tvalidpgpkeys = ' "$infofile" || true ) | sed 's/^.* = \(.*\)$/\1/' | mapfile -t keys
×
UNCOV
1140
                        if [[ ${#keys[@]} != 0 ]]
×
1141
                        then
UNCOV
1142
                                LogEnter 'Checking PGP keys...\n'
×
1143

UNCOV
1144
                                local key
×
UNCOV
1145
                                for key in "${keys[@]}"
×
1146
                                do
UNCOV
1147
                                        export GNUPGHOME="$gnupg_home"
×
1148

UNCOV
1149
                                        if [[ ! -d "$GNUPGHOME" ]]
×
1150
                                        then
UNCOV
1151
                                                LogEnter 'Creating %s...\n' "$(Color C %s "$GNUPGHOME")"
×
UNCOV
1152
                                                mkdir --parents "$GNUPGHOME"
×
UNCOV
1153
                                                gpg --gen-key --batch <<EOF
×
UNCOV
1154
Key-Type: DSA
×
UNCOV
1155
Key-Length: 1024
×
UNCOV
1156
Name-Real: aconfmgr
×
UNCOV
1157
%no-protection
×
UNCOV
1158
EOF
×
UNCOV
1159
                                                LogLeave
×
1160
                                        fi
1161

UNCOV
1162
                                        LogEnter 'Adding key %s...\n' "$(Color Y %q "$key")"
×
1163
                                        #ParanoidConfirm ''
1164

UNCOV
1165
                                        local ok=false
×
UNCOV
1166
                                        local keyserver
×
UNCOV
1167
                                        for keyserver in keys.gnupg.net pgp.mit.edu pool.sks-keyservers.net keyserver.ubuntu.com # subkeys.pgp.net
×
1168
                                        do
UNCOV
1169
                                                LogEnter 'Trying keyserver %s...\n' "$(Color C %s "$keyserver")"
×
UNCOV
1170
                                                if gpg --keyserver "$keyserver" --recv-key "$key"
×
1171
                                                then
UNCOV
1172
                                                        ok=true
×
UNCOV
1173
                                                        LogLeave 'OK!\n'
×
UNCOV
1174
                                                        break
×
1175
                                                else
UNCOV
1176
                                                        LogLeave 'Error...\n'
×
1177
                                                fi
1178
                                        done
1179

UNCOV
1180
                                        if ! $ok
×
1181
                                        then
UNCOV
1182
                                                FatalError 'No keyservers succeeded.\n'
×
1183
                                        fi
1184

UNCOV
1185
                                        if [[ $EUID == 0 ]]
×
1186
                                        then
UNCOV
1187
                                                chmod 700 "$gnupg_home"
×
UNCOV
1188
                                                chown -R "$makepkg_user": "$gnupg_home"
×
1189
                                        fi
1190

UNCOV
1191
                                        LogLeave
×
1192
                                done
1193

UNCOV
1194
                                LogLeave
×
1195
                        fi
1196
                fi
1197
        done
1198

UNCOV
1199
        LogEnter 'Evaluating environment...\n'
×
UNCOV
1200
        local path
×
1201
        # shellcheck disable=SC2016
1202
        path=$(env -i sh -c 'source /etc/profile 1>&2 ; printf -- %s "$PATH"')
UNCOV
1203
        LogLeave
×
1204

UNCOV
1205
        LogEnter 'Building...\n'
×
1206
        (
UNCOV
1207
                cd "$pkg_dir"
×
UNCOV
1208
                mkdir --parents home
×
1209
                local args=(env -i "PATH=$path" "HOME=$PWD/home" "GNUPGHOME=$gnupg_home" "${makepkg_opts[@]}")
1210

UNCOV
1211
                if [[ $EUID == 0 ]]
×
1212
                then
UNCOV
1213
                        chown -R "$makepkg_user": .
×
UNCOV
1214
                        su -s /bin/bash "$makepkg_user" -c "GNUPGHOME=$(realpath ../../gnupg) $(printf ' %q' "${args[@]}")" 1>&2
×
1215

UNCOV
1216
                        if $install
×
1217
                        then
UNCOV
1218
                                local pkglist
×
UNCOV
1219
                                su -s /bin/bash "$makepkg_user" -c "GNUPGHOME=$(realpath ../../gnupg) $(printf ' %q' "${args[@]}" --packagelist)" | mapfile -t pkglist
×
1220

UNCOV
1221
                                if $asdeps
×
1222
                                then
UNCOV
1223
                                        "${pacman_opts[@]}" --upgrade --asdeps "${pkglist[@]}"
×
1224
                                else
UNCOV
1225
                                        "${pacman_opts[@]}" --upgrade "${pkglist[@]}"
×
1226
                                fi
1227
                        fi
1228
                else
UNCOV
1229
                        if $asdeps
×
1230
                        then
1231
                                args+=(--asdeps)
1232
                        fi
1233

UNCOV
1234
                        if $install
×
1235
                        then
1236
                                args+=(--install)
1237
                        fi
1238

UNCOV
1239
                        "${args[@]}" 1>&2
×
1240
                fi
UNCOV
1241
        )
×
UNCOV
1242
        LogLeave
×
1243

UNCOV
1244
        LogLeave
×
1245
}
1246

1247
function AconfInstallNative() {
1248
        local asdeps=false asdeps_arr=()
6✔
1249
        if [[ "$1" == --asdeps ]]
3✔
1250
        then
UNCOV
1251
                asdeps=true
×
1252
                asdeps_arr=(--asdeps)
UNCOV
1253
                shift
×
1254
        fi
1255

1256
        local target_packages=("$@")
6✔
1257
        if [[ $prompt_mode == never ]]
3✔
1258
        then
1259
                # Some prompts default to 'no'
UNCOV
1260
                ( yes || true ) | sudo "${pacman_opts[@]}" --confirm --sync "${asdeps_arr[@]}" "${target_packages[@]}"
×
1261
        else
1262
                sudo "${pacman_opts[@]}" --sync "${asdeps_arr[@]}" "${target_packages[@]}"
3✔
1263
        fi
1264
}
1265

1266
function AconfInstallForeign() {
1267
        local asdeps=false asdeps_arr=()
UNCOV
1268
        if [[ "$1" == --asdeps ]]
×
1269
        then
UNCOV
1270
                asdeps=true
×
1271
                asdeps_arr=(--asdeps)
UNCOV
1272
                shift
×
1273
        fi
1274

1275
        local target_packages=("$@")
1276

UNCOV
1277
        DetectAurHelper
×
1278

UNCOV
1279
        case "$aur_helper" in
×
1280
                aurman)
UNCOV
1281
                        RunExternal "${aurman_opts[@]}" --sync --aur "${asdeps_arr[@]}" "${target_packages[@]}"
×
1282
                        ;;
1283
                pacaur)
UNCOV
1284
                        RunExternal "${pacaur_opts[@]}" --sync --aur "${asdeps_arr[@]}" "${target_packages[@]}"
×
1285
                        ;;
1286
                yaourt)
UNCOV
1287
                        RunExternal "${yaourt_opts[@]}" --sync --aur "${asdeps_arr[@]}" "${target_packages[@]}"
×
1288
                        ;;
1289
                yay)
UNCOV
1290
                        RunExternal "${yay_opts[@]}" --sync --aur "${asdeps_arr[@]}" "${target_packages[@]}"
×
1291
                        ;;
1292
                paru)
UNCOV
1293
                        RunExternal "${paru_opts[@]}" --sync --aur "${asdeps_arr[@]}" "${target_packages[@]}"
×
1294
                        ;;
1295
                makepkg)
UNCOV
1296
                        local package
×
UNCOV
1297
                        for package in "${target_packages[@]}"
×
1298
                        do
UNCOV
1299
                                AconfMakePkg "$package" "$asdeps"
×
1300
                        done
1301
                        ;;
1302
                *)
UNCOV
1303
                        Log 'Error: unknown AUR helper %q\n' "$aur_helper"
×
UNCOV
1304
                        false
×
1305
                        ;;
1306
        esac
1307
}
1308

1309
function AconfNeedProgram() {
UNCOV
1310
        local program="$1" # program that needs to be in PATH
×
UNCOV
1311
        local package="$2" # package the program is available in
×
UNCOV
1312
        local foreign="$3" # whether this is a foreign package
×
1313

UNCOV
1314
        if ! hash "$program" 2> /dev/null
×
1315
        then
UNCOV
1316
                if [[ $foreign == y ]]
×
1317
                then
UNCOV
1318
                        LogEnter 'Installing foreign dependency %s:\n' "$(Color M %q "$package")"
×
UNCOV
1319
                        ParanoidConfirm ''
×
UNCOV
1320
                        AconfInstallForeign --asdeps "$package"
×
1321
                else
UNCOV
1322
                        LogEnter 'Installing native dependency %s:\n' "$(Color M %q "$package")"
×
UNCOV
1323
                        ParanoidConfirm ''
×
UNCOV
1324
                        AconfInstallNative --asdeps "$package"
×
1325
                fi
UNCOV
1326
                LogLeave 'Installed.\n'
×
1327
        fi
1328
}
1329

1330
# Get the path to the package file (.pkg.tar.*) for the specified package.
1331
# Download or build the package if necessary.
1332
function AconfNeedPackageFile() {
1333
        set -e
7✔
1334
        local package="$1"
7✔
1335

1336
        local info foreign
7✔
1337
        if info="$(LC_ALL=C "$PACMAN" --query --info "$package")"
21✔
1338
        then
1339
                if "$PACMAN" --query --quiet --foreign "$package" > /dev/null
7✔
1340
                then
UNCOV
1341
                        foreign=true
×
1342
                else
1343
                        foreign=false
7✔
1344
                fi
1345
        else
UNCOV
1346
                if info="$(LC_ALL=C "$PACMAN" --sync --info "$package")"
×
1347
                then
UNCOV
1348
                        foreign=false
×
1349
                else
UNCOV
1350
                        foreign=true
×
1351
                fi
1352
        fi
1353

1354
        local version='' architecture='' filemask_precise filemask_any
7✔
1355
        if [[ -n "$info" ]]
7✔
1356
        then
1357
                version="$(grep '^Version' <<< "$info" | sed 's/^.* : //g')"
21✔
1358
                architecture="$(grep '^Architecture' <<< "$info" | sed 's/^.* : //g')"
21✔
1359
                filemask_precise=$(printf "%q-%q-%q.pkg.*" "$package" "$version" "$architecture")
14✔
1360
        fi
1361
        filemask_any=$(printf "%q-*-*.pkg.*" "$package")
14✔
1362

1363
        # try without downloading first
1364
        local downloaded
7✔
1365
        for downloaded in false true
7✔
1366
        do
1367
                local precise
7✔
1368
                for precise in true false
7✔
1369
                do
1370
                        # if we don't have the exact version, we can only do non-precise
1371
                        if $precise && [[ -z "$version" ]]
14✔
1372
                        then
UNCOV
1373
                                continue
×
1374
                        fi
1375

1376
                        local filemask
7✔
1377
                        if $precise
7✔
1378
                        then
1379
                                filemask=$filemask_precise
7✔
1380
                        else
UNCOV
1381
                                filemask=$filemask_any
×
1382
                        fi
1383

1384
                        local dirs=()
14✔
1385
                        if $foreign
7✔
1386
                        then
UNCOV
1387
                                DetectAurHelper
×
1388
                                local -A tried_helper=()
1389

UNCOV
1390
                                local helper
×
UNCOV
1391
                                for helper in "$aur_helper" "${aur_helpers[@]}"
×
1392
                                do
UNCOV
1393
                                        if [[ ${tried_helper[$helper]+x} ]]
×
1394
                                        then
UNCOV
1395
                                                continue
×
1396
                                        fi
UNCOV
1397
                                        tried_helper[$helper]=y
×
1398

UNCOV
1399
                                        case "$helper" in
×
1400
                                                aurman)
1401
                                                        dirs+=("${XDG_CACHE_HOME:-$HOME/.cache}/aurman/$package")
1402
                                                        ;;
1403
                                                pacaur)
1404
                                                        dirs+=("${XDG_CACHE_HOME:-$HOME/.cache}/pacaur/$package")
1405
                                                        ;;
1406
                                                yaourt)
1407
                                                        # yaourt does not save .pkg.xz files
1408
                                                        ;;
1409
                                                yay)
1410
                                                        dirs+=("${XDG_CACHE_HOME:-$HOME/.cache}/yay/$package")
1411
                                                        ;;
1412
                                                paru)
1413
                                                        dirs+=("${XDG_CACHE_HOME:-$HOME/.cache}/paru/clone/$package")
1414
                                                        ;;
1415
                                                makepkg)
1416
                                                        dirs+=("$aur_dir"/"$package")
1417
                                                        ;;
1418
                                                *)
UNCOV
1419
                                                        Log 'Error: unknown AUR helper %q\n' "$aur_helper"
×
UNCOV
1420
                                                        false
×
1421
                                                        ;;
1422
                                        esac
1423
                                done
1424
                        else
1425
                                local dir
7✔
1426
                                ( LC_ALL=C pacman --verbose 2>/dev/null || true ) \
21✔
1427
                                        | sed -n 's/^Cache Dirs: \(.*\)$/\1/p' \
7✔
1428
                                        | sed 's/  /\n/g' \
7✔
1429
                                        | while read -r dir
21✔
1430
                                do
1431
                                        if [[ -n "$dir" ]]
14✔
1432
                                        then
1433
                                                dirs+=("$dir")
7✔
1434
                                        fi
1435
                                done
1436
                        fi
1437

1438
                        local files=()
14✔
1439
                        local dir
7✔
1440
                        for dir in "${dirs[@]}"
7✔
1441
                        do
1442
                                if sudo test -d "$dir"
7✔
1443
                                then
1444
                                        sudo find "$dir" -type f -name "$filemask" -not -name '*.sig' -print0 | \
7✔
1445
                                                while read -r -d $'\0' file
14✔
1446
                                                do
1447
                                                        files+=("$file")
7✔
1448
                                                done
1449
                                fi
1450
                        done
1451

1452
                        local file
7✔
1453
                        for file in "${files[@]}"
7✔
1454
                        do
1455
                                local correct
7✔
1456
                                if $precise
7✔
1457
                                then
1458
                                        correct=true
7✔
1459
                                else
UNCOV
1460
                                        local pkgname
×
UNCOV
1461
                                        pkgname=$(bsdtar -x --to-stdout --file "$file" .PKGINFO | \
×
UNCOV
1462
                                                                  sed -n 's/^pkgname = \(.*\)$/\1/p')
×
UNCOV
1463
                                        if [[ "$pkgname" == "$package" ]]
×
1464
                                        then
UNCOV
1465
                                                correct=true
×
1466
                                        else
UNCOV
1467
                                                correct=false
×
1468
                                        fi
1469
                                fi
1470

1471
                                if $correct
7✔
1472
                                then
1473
                                        printf '%s' "$file"
7✔
1474
                                        return
7✔
1475
                                fi
1476
                        done
1477
                done
1478

UNCOV
1479
                if $downloaded
×
1480
                then
UNCOV
1481
                        Log 'Unable to find package file for package %s!\n' "$(Color M %q "$package")"
×
UNCOV
1482
                        Exit 1
×
1483
                else
UNCOV
1484
                        if $foreign
×
1485
                        then
UNCOV
1486
                                LogEnter 'Building foreign package %s\n' "$(Color M %q "$package")"
×
UNCOV
1487
                                ParanoidConfirm ''
×
1488

UNCOV
1489
                                local helper
×
UNCOV
1490
                                for helper in "$aur_helper" "${aur_helpers[@]}"
×
1491
                                do
UNCOV
1492
                                        case "$helper" in
×
1493
                                                aurman)
1494
                                                        # aurman does not have a --makepkg option
1495
                                                        ;;
1496
                                                pacaur)
UNCOV
1497
                                                        if command -v "${pacaur_opts[0]}" > /dev/null
×
1498
                                                        then
UNCOV
1499
                                                                RunExternal "${pacaur_opts[@]}" --makepkg --aur --makepkg "$package" 1>&2
×
UNCOV
1500
                                                                break
×
1501
                                                        fi
1502
                                                        ;;
1503
                                                yaourt)
1504
                                                        # yaourt does not save .pkg.xz files
UNCOV
1505
                                                        continue
×
1506
                                                        ;;
1507
                                                yay)
1508
                                                        # yay does not have a --makepkg option
UNCOV
1509
                                                        continue
×
1510
                                                        ;;
1511
                                                paru)
1512
                                                        # paru does not have a --makepkg option
UNCOV
1513
                                                        continue
×
1514
                                                        ;;
1515
                                                makepkg)
UNCOV
1516
                                                        AconfMakePkg --noinstall "$package"
×
UNCOV
1517
                                                        break
×
1518
                                                        ;;
1519
                                                *)
UNCOV
1520
                                                        Log 'Error: unknown AUR helper %q\n' "$aur_helper"
×
UNCOV
1521
                                                        false
×
1522
                                                        ;;
1523
                                        esac
1524
                                done
1525

UNCOV
1526
                                LogLeave
×
1527
                        else
UNCOV
1528
                                LogEnter "Downloading package %s (%s) to pacman's cache\\n" "$(Color M %q "$package")" "$(Color C %s "$filemask_precise")"
×
UNCOV
1529
                                ParanoidConfirm ''
×
UNCOV
1530
                                sudo "$PACMAN" --sync --download --nodeps --nodeps --noconfirm "$package" 1>&2
×
UNCOV
1531
                                LogLeave
×
1532
                        fi
1533
                fi
1534
        done
1535
}
1536

1537
# Extract the original file from a package to stdout
1538
function AconfGetPackageOriginalFile() {
1539
        local package="$1" # Package to extract the file from
7✔
1540
        local file="$2" # Absolute path to file in package
7✔
1541

1542
        local package_file
7✔
1543
        package_file="$(AconfNeedPackageFile "$package")"
14✔
1544

1545
        local args=(bsdtar -x --to-stdout --file "$package_file" "${file/\//}")
14✔
1546
        if [[ -r "$package_file" ]]
7✔
1547
        then
UNCOV
1548
                "${args[@]}"
×
1549
        else
1550
                sudo "${args[@]}"
7✔
1551
        fi
1552
}
1553

1554
function AconfRestoreFile() {
UNCOV
1555
        local package=$1
×
UNCOV
1556
        local file=$2
×
1557

UNCOV
1558
        local package_file
×
UNCOV
1559
        package_file="$(AconfNeedPackageFile "$package")"
×
1560

1561
        # If we are restoring a directory, it may be non-empty.
1562
        # Extract the object to a temporary location first.
UNCOV
1563
        local tmp_base=${tmp_dir:?}/dir-props
×
UNCOV
1564
        sudo rm -rf "$tmp_base"
×
1565

UNCOV
1566
        mkdir -p "$tmp_base"
×
UNCOV
1567
        local tmp_file="$tmp_base""$file"
×
UNCOV
1568
        sudo tar x --directory "$tmp_base" --file "$package_file" --no-recursion "${file/\//}"
×
1569

UNCOV
1570
        AconfReplace "$tmp_file" "$file"
×
UNCOV
1571
        sudo rm -rf "$tmp_base"
×
1572
}
1573

1574
# Move filesystem object at $1 to $2, replacing any existing one.
1575
# Attempt to do so atomically, when possible.
1576
# Do the right thing when filesystem objects differ, but never
1577
# recursively remove directories (copy their attributes instead).
1578
function AconfReplace() {
UNCOV
1579
        local src=$1
×
UNCOV
1580
        local dst=$2
×
1581

1582
        # Try direct mv first
UNCOV
1583
        if ! sudo mv --no-target-directory "$src" "$dst" 2>/dev/null
×
1584
        then
1585
                # Direct mv failed - directory or object type mismatch
UNCOV
1586
                if sudo rm --force --dir "$dst" 2>/dev/null
×
1587
                then
1588
                        # Deleted target successfully, now overwrite it
UNCOV
1589
                        sudo mv --no-target-directory "$src" "$dst"
×
1590
                else
1591
                        # rm failed - likely a non-empty directory; copy
1592
                        # attributes only
UNCOV
1593
                        sudo chmod --reference="$src" "$dst"
×
UNCOV
1594
                        sudo chown --reference="$src" "$dst"
×
UNCOV
1595
                        sudo touch --reference="$src" "$dst"
×
1596
                fi
1597
        fi
1598
}
1599

1600
####################################################################################################
1601

1602
prompt_mode=normal # never / normal / paranoid
1,513✔
1603

1604
function Confirm() {
UNCOV
1605
        local detail_func="$1"
×
1606

UNCOV
1607
        if [[ $prompt_mode == never ]]
×
1608
        then
UNCOV
1609
                return
×
1610
        fi
1611

UNCOV
1612
        while true
×
1613
        do
UNCOV
1614
                if [[ -n "$detail_func" ]]
×
1615
                then
UNCOV
1616
                        Log 'Proceed? [Y/n/d] '
×
1617
                else
UNCOV
1618
                        Log 'Proceed? [Y/n] '
×
1619
                fi
UNCOV
1620
                read -r -n 1 answer < /dev/tty
×
UNCOV
1621
                echo 1>&2
×
UNCOV
1622
                case "$answer" in
×
1623
                        Y|y|'')
UNCOV
1624
                                return
×
1625
                                ;;
1626
                        N|n)
UNCOV
1627
                                Log '%s\n' "$(Color R "User abort")"
×
UNCOV
1628
                                Exit 1
×
1629
                                ;;
1630
                        D|d)
UNCOV
1631
                                $detail_func
×
UNCOV
1632
                                continue
×
1633
                                ;;
1634
                        *)
UNCOV
1635
                                continue
×
1636
                                ;;
1637
                esac
1638
        done
1639
}
1640

1641
function ParanoidConfirm() {
1642
        if [[ $prompt_mode == paranoid ]]
60✔
1643
        then
1644
                Confirm "$@"
60✔
1645
        fi
1646
}
1647

1648
####################################################################################################
1649

1650
log_indent=:
1,513✔
1651

1652
function Log() {
1653
        if [[ "$#" != 0 && -n "$1" ]]
11,900✔
1654
        then
1655
                local fmt="$1"
5,766✔
1656
                shift
5,766✔
1657

1658
                if [[ -z $ANSI_clear_line ]]
5,766✔
1659
                then
1660
                        # Replace carriage returns in format string with newline
1661
                        # when colors are disabled. This avoids systemd's journal
1662
                        # from showing such lines as [# blob data].
1663

UNCOV
1664
                        fmt=${fmt//\\r/\\n} # Replace the '\r' sequence
×
1665
                                            # (backslash-r) , not actual carriage
1666
                                            # returns.
1667
                fi
1668

1669
                printf "${ANSI_clear_line}${ANSI_color_B}%s ${ANSI_color_W}${fmt}${ANSI_reset}" "$log_indent" "$@" 1>&2
5,766✔
1670
        fi
1671
}
1672

1673
function LogEnter() {
1674
        Log "$@"
2,376✔
1675
        log_indent=$log_indent:
2,376✔
1676
}
1677

1678
function LogLeave() {
1679
        if [[ $# == 0 ]]
2,376✔
1680
        then
1681
                Log 'Done.\n'
1,485✔
1682
        else
1683
                Log "$@"
891✔
1684
        fi
1685

1686
        log_indent=${log_indent::-1}
2,376✔
1687
}
1688

1689
function ConfigWarning() {
1690
        Log '%s: '"$1" "$(Color Y "Warning")" "${@:2}"
8✔
1691
        printf W >> "$output_dir"/warnings
4✔
1692
}
1693

1694
function FatalError() {
1695
        Log "$@"
7✔
1696
        false
14✔
1697
        # if we're here, errexit is not set
UNCOV
1698
        Log 'Continuing after error. This is a bug, please report it.\n'
×
UNCOV
1699
        Exit 1
×
1700
}
1701

1702
function Color() {
1703
        local var="ANSI_color_$1"
2,600✔
1704
        printf -- "%s" "${!var}"
2,600✔
1705
        shift
2,600✔
1706
        # shellcheck disable=2059
1707
        printf -- "$@"
2,600✔
1708
        printf -- "%s" "${ANSI_color_W}"
2,600✔
1709
}
1710

1711
# The ANSI_color_* variables are looked up by name:
1712
# shellcheck disable=2034
1713
function DisableColor() {
UNCOV
1714
        ANSI_color_R=
×
UNCOV
1715
        ANSI_color_G=
×
UNCOV
1716
        ANSI_color_Y=
×
UNCOV
1717
        ANSI_color_B=
×
UNCOV
1718
        ANSI_color_M=
×
UNCOV
1719
        ANSI_color_C=
×
UNCOV
1720
        ANSI_color_W=
×
UNCOV
1721
        ANSI_reset=
×
UNCOV
1722
        ANSI_clear_line=
×
1723
}
1724

1725
####################################################################################################
1726

1727
function OnError() {
1728
        trap '' EXIT ERR
7✔
1729

1730
        LogEnter '%s! Stack trace:\n' "$(Color R "Fatal error")"
14✔
1731

1732
        local frame=0 str
7✔
1733
        while str=$(caller $frame)
56✔
1734
        do
1735
                if [[ $str =~ ^([^\ ]*)\ ([^\ ]*)\ (.*)$ ]]
21✔
1736
                then
1737
                        Log '%s:%s [%s]\n' "$(Color C "%q" "${BASH_REMATCH[3]}")" "$(Color G "%q" "${BASH_REMATCH[1]}")" "$(Color Y "%q" "${BASH_REMATCH[2]}")"
84✔
1738
                else
UNCOV
1739
                        Log '%s\n' "$str"
×
1740
                fi
1741

1742
                frame=$((frame+1))
21✔
1743
        done
1744

1745
        LogLeave ''
7✔
1746

1747
        if [[ -d "$tmp_dir" ]]
7✔
1748
        then
1749
                local df dir
7✔
1750
                df=$(($(stat -f --format="%a*%S" "$tmp_dir")))
14✔
1751
                if ! dir="$(realpath "$(dirname "$tmp_dir")" 2> /dev/null)"
21✔
1752
                then
UNCOV
1753
                        dir="$(dirname "$tmp_dir")"
×
1754
                fi
1755
                if [[ $df -lt $warn_tmp_df_threshold ]]
7✔
1756
                then
UNCOV
1757
                        LogEnter 'Probable cause: low disk space (%s bytes) in %s. Suggestions:\n' "$(Color G %s "$df")" "$(Color C %q "$dir")"
×
UNCOV
1758
                        Log '- Ignore more files and directories using %s directives;\n' "$(Color Y IgnorePath)"
×
UNCOV
1759
                        Log '- Free up more space in %s;\n' "$(Color C %q "$dir")"
×
UNCOV
1760
                        Log '- Set %s to another location before invoking %s.\n' "$(Color Y \$TMPDIR)" "$(Color Y aconfmgr)"
×
UNCOV
1761
                        LogLeave ''
×
1762
                fi
1763
        fi
1764

1765
        # Ensure complete abort when inside a string expansion
1766
        exit 1
7✔
1767
}
1768
trap OnError EXIT ERR
1,513✔
1769

1770
function Exit() {
1771
        trap '' EXIT ERR
1,506✔
1772
        exit "${1:-0}"
1,506✔
1773
}
1774

1775
####################################################################################################
1776

1777
# Print an array, one element per line (assuming IFS starts with \n).
1778
function PrintArray() {
1779
        local name="$1" # Name of the global variable containing the array
819✔
1780
        local size
819✔
1781

1782
        size="$(eval "echo \${#${name}""[*]}")"
2,457✔
1783
        if [[ $size != 0 ]]
819✔
1784
        then
1785
                eval "echo \"\${${name}[*]}\""
250✔
1786
        fi
1787
}
1788

1789
# Ditto, but terminate elements with a NUL.
1790
function Print0Array() {
1791
        local name="$1" # Name of the global variable containing the array
875✔
1792

UNCOV
1793
        eval "$(cat <<EOF
×
UNCOV
1794
        if [[ \${#${name}[*]} != 0 ]]
×
1795
        then
UNCOV
1796
                local item
×
UNCOV
1797
                for item in "\${${name}[@]}"
×
1798
                do
UNCOV
1799
                        printf '%s\\0' "\$item"
×
1800
                done
1801
        fi
UNCOV
1802
EOF
×
1803
)"
2,625✔
1804
}
1805

604✔
1806
# Ditto, but shell-escape array elements.
1,855✔
1807
function PrintQArray() {
1808
        local name="$1" # Name of the global variable containing the array
1,855✔
UNCOV
1809
        local size
×
1810

UNCOV
1811
        size="$(eval "echo \${#${name}""[*]}")"
×
UNCOV
1812
        if [[ $size != 0 ]]
×
1813
        then
UNCOV
1814
                eval "printf -- %q \"\${${name}[0]}\""
×
UNCOV
1815
                if [[ $size -gt 1 ]]
×
1816
                then
UNCOV
1817
                        eval "printf -- ' %q' \"\${${name}[@]:1}\""
×
1818
                fi
1819
        fi
1820
}
1821

1822
if [[ $EUID == 0 ]]
1,513✔
1823
then
1824
        function sudo() { "$@" ; }
1825
fi
1826

1827
# Run external bash script.
1828
# No-op, except when running under the test suite with bashcov,
1829
# in which case it does not propagate bashcov to the invoked script.
1830
# Unlike `env -i`, does not nuke the environment.
1831
function RunExternal() {
UNCOV
1832
        env -u SHELLOPTS -u PS4 -u SHLVL -u BASH_XTRACEFD "$@"
×
1833
}
1834

1835
# cat a file; if it's not readable, cat via sudo.
1836
function SuperCat() {
1837
        local file="$1"
1✔
1838

1839
        if [[ -r "$1" ]]
1✔
1840
        then
UNCOV
1841
                cat "$1"
×
1842
        else
1843
                sudo cat "$1"
1✔
1844
        fi
1845
}
1846

1847
if ! ( empty_array=() ; : "${empty_array[@]}" )
3,026✔
1848
then
1849
        # Old bash versions treat substitution of an empty array
1850
        # synonymous with substituting an unset variable, signaling an
1851
        # error in -u mode and stopping the script in -e mode. We
1852
        # generally want both of these enabled to catch bugs early and
1853
        # fail fast, but making every array substitution conditional on
1854
        # whether it is empty or not is unreasonably onerous, so just
1855
        # disable those checks in old bash versions - it is then up to the
1856
        # test suite ran against newer bash versions to ensure code
1857
        # correctness.
1858

1859
        Log '%s: Old bash detected, disabling unset variable checking.\n' "$(Color Y "Warning")"
×
1860
        set +u
×
1861
fi
1862

1863
: # include in coverage
1,513✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc