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

CyberShadow / aconfmgr / 370

30 Nov 2023 09:52AM UTC coverage: 93.666%. Remained the same
370

push

github

CyberShadow-Renovate
Update dependency yay to v20231130094145

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

2 existing lines in 1 file now uncovered.

4555 of 4863 relevant lines covered (93.67%)

459.3 hits per line

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

94.55
/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,529✔
10

11
output_dir="$tmp_dir"/output
1,529✔
12
system_dir="$tmp_dir"/system # Current system configuration, to be compared against the output directory
1,529✔
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,529✔
19
then
20
        aur_dir="$tmp_dir"-aur
×
21
else
22
        aur_dir="$tmp_dir"/aur
1,529✔
23
fi
24

25
default_file_mode=644
1,529✔
26

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

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

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

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

46
# Defaults
47

48
# Initial ignore path list.
49
# Can be appended to using the IgnorePath helper.
50
ignore_paths=(
1,529✔
51
    '/dev'
1,529✔
52
    '/home'
1,529✔
53
    '/media'
1,529✔
54
    '/mnt'
1,529✔
55
    '/proc'
1,529✔
56
    '/root'
1,529✔
57
    '/run'
1,529✔
58
    '/sys'
1,529✔
59
    '/tmp'
1,529✔
60
    # '/var/.updated'
1,529✔
61
    '/var/cache'
1,529✔
62
    # '/var/lib'
1,529✔
63
    # '/var/lock'
1,529✔
64
    # '/var/log'
1,529✔
65
    # '/var/spool'
1,529✔
66
)
1,529✔
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,529✔
72
        /etc/passwd
1,529✔
73
        /etc/group
1,529✔
74
        /etc/pacman.conf
1,529✔
75
        /etc/pacman.d/mirrorlist
1,529✔
76
        /etc/makepkg.conf
1,529✔
77
)
1,529✔
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,529✔
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,529✔
92
warn_file_count_threshold=1000        # Warn on finding this many stray files
1,529✔
93
warn_tmp_df_threshold=$((1024*1024))  # Warn on error if free space in $tmp_dir is below this
1,529✔
94

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

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

99
function LogLeaveDirStats() {
100
        local dir="$1"
304✔
101
        Log 'Finalizing...\r'
304✔
102
        LogLeave 'Done (%s native packages, %s foreign packages, %s files).\n'        \
2,431✔
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,529✔
109

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

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

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

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

133
        # Configuration
134

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

137
        typeset -ag ignore_packages=()
330✔
138
        typeset -ag ignore_foreign_packages=()
330✔
139
        typeset -Ag used_files
165✔
140

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

155
        if $lint_config
165✔
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 ]]
6✔
163
                then
164
                        local line
4✔
165
                        find "$config_dir"/files -type f -print0 | \
4✔
166
                                while read -r -d $'\0' line
8✔
167
                                do
168
                                        local key=${line#"$config_dir"/files}
4✔
169
                                        if [[ -z "${used_files[$key]+x}" ]]
4✔
170
                                        then
171
                                                ConfigWarning 'Unused file: %s\n' \
4✔
172
                                                                          "$(Color C "%q" "$line")"
4✔
173
                                        fi
174
                                done
175
                fi
176
        fi
177

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

186
skip_inspection=n
1,529✔
187
skip_checksums=n
1,529✔
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
157✔
202
        local -n ignore_args_var=$ignore_args_varname
157✔
203
        shift
157✔
204
        local ignore_paths=("$@")
314✔
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=()
314✔
212

213
        local ignore_path
157✔
214
        for ignore_path in "${ignore_paths[@]}"
2,666✔
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_/\ .*-] ]]
2,666✔
220
                then
221
                        ignore_args_var+=(-wholename "$ignore_path" -o)
10✔
222
                else
223
                        simple_ignore_paths+=("${ignore_path}")
2,656✔
224
                fi
225
        done
226

227
        if [ ${#simple_ignore_paths[@]} -ne 0 ]
157✔
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
157✔
232
                echo -n "${simple_ignore_paths[*]}" | \
157✔
233
                        sed 's|[^*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_/ ]|[&]|g; s|\*|.*|g' | \
157✔
234
                        mapfile -t ignore_regexps
157✔
235

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

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

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

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

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

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

261
        ### Packages
262

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

268
        ### Files
269

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

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

277
        # Stray files
278

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

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

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

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

292
        AconfNeedProgram gawk gawk n
157✔
293

294
        # Progress display - only show file names once per second
295
        local progress_fd
157✔
296
        exec {progress_fd}> \
157✔
297
                 >( gawk '
157✔
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
        }
315✔
309
}' | \
1✔
310
                                while read -r -d $'\0' line
1✔
311
                                do
1✔
UNCOV
312
                                        local path=${line:1}
×
313
                                        path=${path%/*} # Never show files, only directories
×
314
                                        while [[ ${#path} -gt 40 ]]
2✔
315
                                        do
UNCOV
316
                                                path=${path%/*}
×
317
                                        done
318
                                        Log 'Scanning %s...\r' "$(Color M "%q" "$path")"
×
319
                                done
320
                  )
×
321

322
        local stray_file_count=0
157✔
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 /                                                                        \
157✔
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                                \
157✔
338
                        | ( grep                                                                \
×
339
                                        --null --null-data                                \
314✔
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
4,496✔
350
                do
351
                        local file action
4,472✔
352
                        file=${line:1}
4,465✔
353
                        action=${line:0:1}
4,459✔
354

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

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

367
                                        if [[ $stray_file_count -eq $warn_file_count_threshold ]]
278✔
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"
4,100✔
400
                                        while [[ -n "$path" ]]
11,784✔
401
                                        do
402
                                                ignored_dirs[$path]=y
7,657✔
403
                                                path=${path%/*}
7,632✔
404
                                        done
405
                                        ;;
406
                        esac
407
                done
408

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

411
        exec {progress_fd}<&-
141✔
412

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

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

429
        LogLeave
88✔
430

431
        # Modified files
432

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

435
        AconfNeedProgram paccheck pacutils n
93✔
436
        AconfNeedProgram unbuffer expect n
98✔
437
        local modified_file_count=0
104✔
438
        local -A saw_file
103✔
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
214✔
443

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

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

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

462
                                local ignored=n
2,517✔
463
                                local ignore_path
2,526✔
464
                                for ignore_path in "${ignore_paths[@]}"
45,713✔
465
                                do
466
                                        # shellcheck disable=SC2053
467
                                        if [[ "$file" == $ignore_path ]]
45,615✔
468
                                        then
469
                                                ignored=y
1,946✔
470
                                                break
1,942✔
471
                                        fi
472
                                done
473

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

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

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

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

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

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

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

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

558
        typeset -a found_file_types found_file_sizes found_file_modes found_file_owners found_file_groups
157✔
559
        if [[ ${#found_files[*]} == 0 ]]
157✔
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
628✔
564
                Log 'Reading file sizes...\n'  ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%s | mapfile -t  found_file_sizes
628✔
565
                Log 'Reading file modes...\n'  ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%a | mapfile -t  found_file_modes
628✔
566
                Log 'Reading file owners...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%U | mapfile -t found_file_owners
628✔
567
                Log 'Reading file groups...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%G | mapfile -t found_file_groups
628✔
568
        fi
569

570
        LogLeave # Reading file attributes
157✔
571

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

596
        LogEnter 'Processing found files...\n'
157✔
597

598
        for ((i=0; i<${#found_files[*]}; i++))
1,492✔
599
        do
600
                Log '%s/%s...\r' "$(Color G "$i")" "$(Color G "${#found_files[*]}")"
1,767✔
601

602
                local  file="${found_files[$i]}"
589✔
603
                local  type="${found_file_types[$i]}"
589✔
604
                local  size="${found_file_sizes[$i]}"
589✔
605
                local  mode="${found_file_modes[$i]}"
589✔
606
                local owner="${found_file_owners[$i]}"
589✔
607
                local group="${found_file_groups[$i]}"
589✔
608

609
                if [[ "${ignored_dirs[$file]-n}" == y ]]
589✔
610
                then
611
                        continue
288✔
612
                fi
613

614
                if [[ -n "${found_file_edited[$file]+x}" ]]
301✔
615
                then
616
                        mkdir --parents "$(dirname "$system_dir"/files/"$file")"
590✔
617
                        if [[ "$type" == "symbolic link" ]]
295✔
618
                        then
619
                                ln -s "$(sudo readlink "$file")" "$system_dir"/files/"$file"
72✔
620
                        elif [[ "$type" == "regular file" || "$type" == "regular empty file" ]]
454✔
621
                        then
622
                                if [[ $size -gt $warn_size_threshold ]]
68✔
623
                                then
624
                                        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")"
×
625
                                fi
626

627
                                local filter_pattern filter_func
68✔
628
                                unset filter_func
68✔
629
                                for filter_pattern in "${!file_content_filters[@]}"
6✔
630
                                do
631
                                        # shellcheck disable=SC2053
632
                                        if [[ "$file" == $filter_pattern ]]
6✔
633
                                        then
634
                                                filter_func=${file_content_filters[$filter_pattern]}
6✔
635
                                        fi
636
                                done
637

638
                                if [[ -v filter_func ]]
68✔
639
                                then
640
                                        sudo cat "$file" | "$filter_func" "$file" > "$system_dir"/files/"$file"
12✔
641
                                else
642
                                        # shellcheck disable=SC2024
643
                                        sudo cat "$file" > "$system_dir"/files/"$file"
62✔
644
                                fi
645
                        elif [[ "$type" == "directory" ]]
191✔
646
                        then
647
                                mkdir --parents "$system_dir"/files/"$file"
191✔
648
                        else
649
                                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")"
×
650
                                continue
×
651
                        fi
652
                fi
653

654
                {
655
                        local prop
301✔
656
                        for prop in mode owner group
903✔
657
                        do
658
                                # Ignore mode "changes" in symbolic links
659
                                # If a file's type changes, a change in mode can be reported too.
660
                                # But, symbolic links cannot have a mode, so ignore this change.
661
                                if [[ "$type" == "symbolic link" && "$prop" == mode ]]
1,011✔
662
                                then
663
                                        continue
36✔
664
                                fi
665

666
                                local value
867✔
667
                                eval "value=\$$prop"
1,734✔
668

669
                                local default_value
867✔
670

671
                                if [[ $i -lt $stray_file_count ]]
867✔
672
                                then
673
                                        # For stray files, the default owner/group is root/root,
674
                                        # and the default mode depends on the type.
675
                                        # Let AconfDefaultFileProp get the correct default value for us.
676

677
                                        default_value=
693✔
678
                                else
679
                                        # For owned files, we assume that the defaults are the
680
                                        # files' current properties, unless paccheck said
681
                                        # otherwise.
682

683
                                        default_value=$value
174✔
684
                                fi
685

686
                                local orig_value
867✔
687
                                orig_value=$(AconfDefaultFileProp "$file" "$prop" "$type" "$default_value")
1,734✔
688

689
                                [[ "$value" == "$orig_value" ]] || printf '%s\t%s\t%q\n' "$prop" "$value" "$file"
989✔
690
                        done
691
                } >> "$system_dir"/file-props.txt
×
692
        done
693

694
        LogLeave # Processing found files
157✔
695

696
        LogLeaveDirStats "$system_dir" # Inspecting system state
157✔
697
}
698

699
####################################################################################################
700

701
typeset -A file_property_kind_exists
1,529✔
702

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

711
        local key="$file:$prop"
891✔
712

713
        if [[ -n "${orig_file_props[$key]+x}" ]]
891✔
714
        then
715
                printf '%s' "${orig_file_props[$key]}"
90✔
716
                return
90✔
717
        fi
718

719
        if [[ -n "$default" ]]
801✔
720
        then
721
                printf '%s' "$default"
90✔
722
                return
90✔
723
        fi
724

725
        case "$prop" in
711✔
726
                mode)
727
                        if [[ -z "$type" ]]
233✔
728
                        then
729
                                type=$(sudo env LC_ALL=C stat --format=%F "$file")
12✔
730
                        fi
731

732
                        if [[ "$type" == "symbolic link" ]]
233✔
733
                        then
734
                                FatalError 'Symbolic links do not have a mode\n' # Bug
×
735
                        elif [[ "$type" == "directory" ]]
233✔
736
                        then
737
                                printf 755
177✔
738
                        else
739
                                printf '%s' "$default_file_mode"
56✔
740
                        fi
741
                        ;;
742
                owner|group)
743
                        printf 'root'
478✔
744
                        ;;
745
        esac
746
}
747

748
# Read a file-props.txt file into an associative array.
749
function AconfReadFileProps() {
750
        local filename="$1" # Path to file-props.txt to be read
459✔
751
        local varname="$2"  # Name of global associative array variable to read into
459✔
752

753
        local line
459✔
754
        while read -r line
1,405✔
755
        do
756
                if [[ $line =~ ^(.*)\        (.*)\        (.*)$ ]]
946✔
757
                then
758
                        local kind="${BASH_REMATCH[1]}"
946✔
759
                        local value="${BASH_REMATCH[2]}"
946✔
760
                        local file="${BASH_REMATCH[3]}"
946✔
761
                        file="$(eval "printf %s $file")" # Unescape
2,838✔
762

763
                        if [[ -z "$value" ]]
946✔
764
                        then
765
                                unset "${varname}[\$file:\$kind]"
238✔
766
                        else
767
                                eval "${varname}[\$file:\$kind]=\"\$value\""
1,416✔
768
                        fi
769

770
                        file_property_kind_exists[$kind]=y
946✔
771
                fi
772
        done < "$filename"
×
773
}
774

775
# Compare file properties.
776
function AconfCompareFileProps() {
777
        LogEnter 'Comparing file properties...\n'
302✔
778

779
        typeset -ag system_only_file_props=()
602✔
780
        typeset -ag changed_file_props=()
602✔
781
        typeset -ag config_only_file_props=()
602✔
782

783
        local key
301✔
784
        for key in "${!system_file_props[@]}"
276✔
785
        do
786
                if [[ -z "${output_file_props[$key]+x}" ]]
276✔
787
                then
788
                        system_only_file_props+=("$key")
70✔
789
                fi
790
        done
791

792
        for key in "${!system_file_props[@]}"
272✔
793
        do
794
                if [[ -n "${output_file_props[$key]+x}" && "${system_file_props[$key]}" != "${output_file_props[$key]}" ]]
475✔
795
                then
796
                        changed_file_props+=("$key")
58✔
797
                fi
798
        done
799

800
        for key in "${!output_file_props[@]}"
322✔
801
        do
802
                if [[ -z "${system_file_props[$key]+x}" ]]
322✔
803
                then
804
                        config_only_file_props+=("$key")
141✔
805
                fi
806
        done
807

808
        LogLeave
298✔
809
}
810

811
# Compare file information in $output_dir and $system_dir.
812
function AconfAnalyzeFiles() {
813

814
        #
815
        # Stray/modified files - diff
816
        #
817

818
        LogEnter 'Examining files...\n'
153✔
819

820
        LogEnter 'Loading data...\n'
153✔
821
        mkdir --parents "$tmp_dir"
153✔
822
        ( cd "$output_dir"/files && find . -mindepth 1 -print0 ) | cut --zero-terminated -c 2- | sort --zero-terminated > "$tmp_dir"/output-files
612✔
823
        ( cd "$system_dir"/files && find . -mindepth 1 -print0 ) | cut --zero-terminated -c 2- | sort --zero-terminated > "$tmp_dir"/system-files
612✔
824
        LogLeave
153✔
825

826
        Log 'Comparing file data...\n'
153✔
827

828
        typeset -ag system_only_files=()
306✔
829
        local file
153✔
830

831
        ( comm -13 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
153✔
832
                while read -r -d $'\0' file
223✔
833
                do
834
                        Log 'Only in system: %s\n' "$(Color C "%q" "$file")"
140✔
835
                        system_only_files+=("$file")
70✔
836
                done
837

838
        typeset -ag changed_files=()
306✔
839

840
        AconfNeedProgram diff diffutils n
153✔
841

842
        ( comm -12 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
153✔
843
                while read -r -d $'\0' file
257✔
844
                do
845
                        local output_type system_type
104✔
846
                        output_type=$(LC_ALL=C stat --format=%F "$output_dir"/files/"$file")
312✔
847
                        system_type=$(LC_ALL=C stat --format=%F "$system_dir"/files/"$file")
312✔
848

849
                        if [[ "$output_type" != "$system_type" ]]
104✔
850
                        then
851
                                Log 'Changed type (%s / %s): %s\n' \
160✔
852
                                        "$(Color Y "%q" "$output_type")" \
160✔
853
                                        "$(Color Y "%q" "$system_type")" \
160✔
854
                                        "$(Color C "%q" "$file")"
160✔
855
                                changed_files+=("$file")
40✔
856
                                continue
40✔
857
                        fi
858

859
                        if [[ "$output_type" == "directory" || "$system_type" == "directory" ]]
112✔
860
                        then
861
                                continue
16✔
862
                        fi
863

864
                        if ! diff --no-dereference --brief "$output_dir"/files/"$file" "$system_dir"/files/"$file" > /dev/null
48✔
865
                        then
866
                                Log 'Changed: %s\n' "$(Color C "%q" "$file")"
36✔
867
                                changed_files+=("$file")
18✔
868
                        fi
869
                done
870

871
        typeset -ag config_only_files=()
306✔
872

873
        ( comm -23 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
153✔
874
                while read -r -d $'\0' file
216✔
875
                do
876
                        Log 'Only in config: %s\n' "$(Color C "%q" "$file")"
126✔
877
                        config_only_files+=("$file")
63✔
878
                done
879

880
        LogLeave 'Done (%s only in system, %s changed, %s only in config).\n'        \
612✔
881
                         "$(Color G "${#system_only_files[@]}")"                                                \
612✔
882
                         "$(Color G "${#changed_files[@]}")"                                                        \
612✔
883
                         "$(Color G "${#config_only_files[@]}")"
612✔
884

885
        #
886
        # Modified file properties
887
        #
888

889
        LogEnter 'Examining file properties...\n'
153✔
890

891
        LogEnter 'Loading data...\n'
153✔
892
        unset orig_file_props # Also populated by AconfCompileSystem, so that it can be used by AconfDefaultFileProp
153✔
893
        typeset -Ag output_file_props ; AconfReadFileProps "$output_dir"/file-props.txt output_file_props
306✔
894
        typeset -Ag system_file_props ; AconfReadFileProps "$system_dir"/file-props.txt system_file_props
306✔
895
        typeset -Ag   orig_file_props ; AconfReadFileProps "$system_dir"/orig-file-props.txt orig_file_props
306✔
896
        LogLeave
153✔
897

898
        typeset -ag all_file_property_kinds
153✔
899
        all_file_property_kinds=("${!file_property_kind_exists[@]}")
153✔
900
        Print0Array all_file_property_kinds | sort --zero-terminated | mapfile -t -d $'\0' all_file_property_kinds
459✔
901

902
        AconfCompareFileProps
153✔
903

904
        LogLeave 'Done (%s only in system, %s changed, %s only in config).\n'        \
610✔
905
                         "$(Color G "${#system_only_file_props[@]}")"                                        \
610✔
906
                         "$(Color G "${#changed_file_props[@]}")"                                                \
610✔
907
                         "$(Color G "${#config_only_file_props[@]}")"
610✔
908
}
909

910
# The *_packages arrays are passed by name,
911
# so ShellCheck thinks the variables are unused:
912
# shellcheck disable=2034
913

914
# Prepare configuration and system state
915
function AconfCompile() {
916
        LogEnter 'Collecting data...\n'
151✔
917

918
        # Configuration
919

920
        AconfCompileOutput
151✔
921

922
        # System
923

924
        AconfCompileSystem
151✔
925

926
        # Vars
927

928
        < "$output_dir"/packages.txt         sort --unique | mapfile -t                   packages
302✔
929
        < "$system_dir"/packages.txt         sort --unique | mapfile -t         installed_packages
302✔
930

931
        < "$output_dir"/foreign-packages.txt sort --unique | mapfile -t           foreign_packages
302✔
932
        < "$system_dir"/foreign-packages.txt sort --unique | mapfile -t installed_foreign_packages
302✔
933

934
        AconfAnalyzeFiles
151✔
935

936
        LogLeave # Collecting data
151✔
937
}
938

939
####################################################################################################
940

941
pacman_opts=("$PACMAN")
1,529✔
942
aurman_opts=(aurman)
1,529✔
943
pacaur_opts=(pacaur)
1,529✔
944
yaourt_opts=(yaourt)
1,529✔
945
yay_opts=(yay)
1,529✔
946
paru_opts=(paru)
1,529✔
947
makepkg_opts=(makepkg)
1,529✔
948
diff_opts=(diff '--color=auto')
1,529✔
949

950
aur_helper=
1,529✔
951
aur_helpers=(aurman pacaur yaourt yay paru makepkg)
1,529✔
952

953
# Only aconfmgr can use makepkg under root
954
if [[ $EUID == 0 ]]
1,529✔
955
then
956
        aur_helper=makepkg
×
957
fi
958

959
function DetectAurHelper() {
960
        if [[ -n "$aur_helper" ]]
38✔
961
        then
962
                return
30✔
963
        fi
964

965
        LogEnter 'Detecting AUR helper...\n'
8✔
966

967
        local helper
8✔
968
        for helper in "${aur_helpers[@]}"
48✔
969
        do
970
                if hash "$helper" 2> /dev/null
48✔
971
                then
972
                        aur_helper=$helper
8✔
973
                        LogLeave '%s... Yes\n' "$(Color C %s "$helper")"
16✔
974
                        return
8✔
975
                fi
976
                Log '%s... No\n' "$(Color C %s "$helper")"
80✔
977
        done
978

979
        Log 'Can'\''t find even makepkg!?\n'
×
980
        Exit 1
×
981
}
982

983
base_devel_installed=n
1,529✔
984

985
function AconfMakePkg() {
986
        local install=true
23✔
987
        if [[ "$1" == --noinstall ]]
23✔
988
        then
989
                install=false
3✔
990
                shift
3✔
991
        fi
992

993
        local package="$1"
23✔
994
        local asdeps="${2:-false}"
23✔
995

996
        LogEnter 'Building foreign package %s from source.\n' "$(Color M %q "$package")"
46✔
997

998
        # shellcheck disable=SC2174
999
        mkdir --parents --mode=700 "$aur_dir"
23✔
1000
        if [[ $EUID == 0 ]]
23✔
1001
        then
1002
                chown -R "$makepkg_user": "$aur_dir"
×
1003
        fi
1004

1005
        local pkg_dir="$aur_dir"/"$package"
23✔
1006
        Log 'Using directory %s.\n' "$(Color C %q "$pkg_dir")"
46✔
1007

1008
        rm -rf "$pkg_dir"
23✔
1009
        mkdir --parents "$pkg_dir"
23✔
1010

1011
        # Needed to clone the AUR repo. Should be replaced with curl/tar.
1012
        AconfNeedProgram git git n
23✔
1013

1014
        if [[ $base_devel_installed == n ]]
23✔
1015
        then
1016
                LogEnter 'Making sure the %s package is installed...\n' "$(Color M base-devel)"
28✔
1017
                ParanoidConfirm ''
14✔
1018
                if ! "$PACMAN" --query --quiet base-devel > /dev/null 2>&1
14✔
1019
                then
1020
                        AconfInstallNative base-devel
1✔
1021
                fi
1022

1023
                LogLeave
14✔
1024
                base_devel_installed=y
14✔
1025
        fi
1026

1027
        LogEnter 'Cloning...\n'
23✔
1028
        git clone "https://aur.archlinux.org/$package.git" "$pkg_dir"
23✔
1029
        LogLeave
23✔
1030

1031
        if [[ ! -f "$pkg_dir"/PKGBUILD ]]
23✔
1032
        then
1033
                Log 'No package description file found!\n'
1✔
1034

1035
                if [[ "$package" == auracle-git ]]
1✔
1036
                then
1037
                        FatalError 'Failed to download aconfmgr dependency!\n'
×
1038
                fi
1039

1040
                LogEnter 'Assuming this package is part of a package base:\n'
1✔
1041

1042
                LogEnter 'Retrieving package info...\n'
1✔
1043
                AconfNeedProgram auracle auracle-git y
1✔
1044
                local pkg_base
1✔
1045
                pkg_base=$(auracle info --format '{pkgbase}' "$package")
2✔
1046
                LogLeave 'Done, package base is %s.\n' "$(Color M %q "$pkg_base")"
2✔
1047

1048
                AconfMakePkg "$pkg_base" "$asdeps" # recurse
1✔
1049
                LogLeave # Package base
1✔
1050
                LogLeave # Package
1✔
1051
                return
1✔
1052
        fi
1053

1054
        AconfMakePkgDir "$package" "$asdeps" "$install" "$pkg_dir"
22✔
1055
}
1056

1057
function AconfMakePkgDir() {
1058
        local package=$1
22✔
1059
        local asdeps=$2
22✔
1060
        local install=$3
22✔
1061
        local pkg_dir=$4
22✔
1062

1063
        local gnupg_home
22✔
1064
        gnupg_home="$(realpath -m "$tmp_dir/gnupg")"
44✔
1065

1066
        local infofile infofilename
22✔
1067
        for infofilename in .SRCINFO .AURINFO
44✔
1068
        do
1069
                infofile="$pkg_dir"/"$infofilename"
44✔
1070
                if test -f "$infofile"
44✔
1071
                then
1072
                        LogEnter 'Checking dependencies...\n'
22✔
1073

1074
                        local depends missing_depends dependency arch
22✔
1075
                        arch="$(uname -m)"
44✔
1076
                        # Filter out packages from the same base
1077
                        ( grep -E $'^\t(make|check)?depends(_'"$arch"')? = ' "$infofile" || true ) \
32✔
1078
                                | sed 's/^.* = \([^<>=]*\)\([<>=].*\)\?$/\1/g' \
22✔
1079
                                | ( grep -vFf <(( grep '^pkgname = ' "$infofile" || true) \
66✔
1080
                                                                        | sed 's/^.* = \(.*\)$/\1/g' ) \
×
1081
                                                || true ) \
10✔
1082
                                | mapfile -t depends
22✔
1083

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

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

1118
                                                        if ! $installed
6✔
1119
                                                        then
1120
                                                                Log 'Installing from AUR...\n'
4✔
1121
                                                                AconfMakePkg "$dependency" true
4✔
1122
                                                                Log 'Installed.\n'
4✔
1123
                                                        fi
1124
                                                fi
1125

1126
                                                LogLeave ''
28✔
1127
                                        done
1128
                                fi
1129
                        fi
1130

1131
                        LogLeave
22✔
1132

1133
                        local keys
22✔
1134
                        ( grep -E $'^\tvalidpgpkeys = ' "$infofile" || true ) | sed 's/^.* = \(.*\)$/\1/' | mapfile -t keys
87✔
1135
                        if [[ ${#keys[@]} != 0 ]]
22✔
1136
                        then
1137
                                LogEnter 'Checking PGP keys...\n'
1✔
1138

1139
                                local key
1✔
1140
                                for key in "${keys[@]}"
1✔
1141
                                do
1142
                                        export GNUPGHOME="$gnupg_home"
2✔
1143

1144
                                        if [[ ! -d "$GNUPGHOME" ]]
1✔
1145
                                        then
1146
                                                LogEnter 'Creating %s...\n' "$(Color C %s "$GNUPGHOME")"
2✔
1147
                                                mkdir --parents "$GNUPGHOME"
1✔
1148
                                                gpg --gen-key --batch <<EOF
1✔
1149
Key-Type: DSA
1✔
1150
Key-Length: 1024
1✔
1151
Name-Real: aconfmgr
1✔
1152
%no-protection
1✔
1153
EOF
1✔
1154
                                                LogLeave
1✔
1155
                                        fi
1✔
1156

1✔
1157
                                        LogEnter 'Adding key %s...\n' "$(Color Y %q "$key")"
2✔
1158
                                        #ParanoidConfirm ''
1✔
1159

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

1✔
1175
                                        if ! $ok
1✔
1176
                                        then
1✔
1177
                                                FatalError 'No keyservers succeeded.\n'
1✔
1178
                                        fi
1✔
1179

1✔
1180
                                        if [[ $EUID == 0 ]]
1✔
1181
                                        then
1✔
1182
                                                chmod 700 "$gnupg_home"
1✔
1183
                                                chown -R "$makepkg_user": "$gnupg_home"
1✔
1184
                                        fi
1✔
1185

1✔
1186
                                        LogLeave
1✔
1187
                                done
1✔
1188

1✔
1189
                                LogLeave
1✔
1190
                        fi
1✔
1191
                fi
1✔
1192
        done
1✔
1193

1✔
1194
        LogEnter 'Evaluating environment...\n'
22✔
1195
        local path
22✔
1196
        # shellcheck disable=SC2016
1✔
1197
        path=$(env -i sh -c 'source /etc/profile 1>&2 ; printf -- %s "$PATH"')
44✔
1198
        LogLeave
22✔
1199

1✔
1200
        LogEnter 'Building...\n'
22✔
1201
        (
1✔
1202
                cd "$pkg_dir"
22✔
1203
                mkdir --parents home
22✔
1204
                local args=(env -i "PATH=$path" "HOME=$PWD/home" "GNUPGHOME=$gnupg_home" "${makepkg_opts[@]}")
44✔
1205

1✔
1206
                if [[ $EUID == 0 ]]
22✔
1207
                then
1✔
1208
                        chown -R "$makepkg_user": .
1✔
1209
                        su -s /bin/bash "$makepkg_user" -c "GNUPGHOME=$(realpath ../../gnupg) $(printf ' %q' "${args[@]}")" 1>&2
1✔
1210

1✔
1211
                        if $install
1✔
1212
                        then
1✔
1213
                                local pkglist
1✔
1214
                                su -s /bin/bash "$makepkg_user" -c "GNUPGHOME=$(realpath ../../gnupg) $(printf ' %q' "${args[@]}" --packagelist)" | mapfile -t pkglist
1✔
1215

1✔
1216
                                if $asdeps
1✔
1217
                                then
1✔
1218
                                        "${pacman_opts[@]}" --upgrade --asdeps "${pkglist[@]}"
1✔
1219
                                else
1✔
1220
                                        "${pacman_opts[@]}" --upgrade "${pkglist[@]}"
1✔
1221
                                fi
1✔
1222
                        fi
1✔
1223
                else
1✔
1224
                        if $asdeps
22✔
1225
                        then
1✔
1226
                                args+=(--asdeps)
7✔
1227
                        fi
1✔
1228

1✔
1229
                        if $install
22✔
1230
                        then
1✔
1231
                                args+=(--install)
19✔
1232
                        fi
22✔
1233

22✔
1234
                        "${args[@]}" 1>&2
22✔
1235
                fi
1✔
1236
        )
1✔
1237
        LogLeave
22✔
1238

1✔
1239
        LogLeave
22✔
1240
}
1✔
1241

1✔
1242
function AconfInstallNative() {
1✔
1243
        local asdeps=false asdeps_arr=()
64✔
1244
        if [[ "$1" == --asdeps ]]
32✔
1245
        then
1✔
1246
                asdeps=true
25✔
1247
                asdeps_arr=(--asdeps)
25✔
1248
                shift
25✔
1249
        fi
1✔
1250

1✔
1251
        local target_packages=("$@")
64✔
1252
        if [[ $prompt_mode == never ]]
32✔
1253
        then
1✔
1254
                # Some prompts default to 'no'
1✔
1255
                ( yes || true ) | sudo "${pacman_opts[@]}" --confirm --sync "${asdeps_arr[@]}" "${target_packages[@]}"
1✔
1256
        else
1✔
1257
                sudo "${pacman_opts[@]}" --sync "${asdeps_arr[@]}" "${target_packages[@]}"
32✔
1258
        fi
1✔
1259
}
1✔
1260

1✔
1261
function AconfInstallForeign() {
1✔
1262
        local asdeps=false asdeps_arr=()
32✔
1263
        if [[ "$1" == --asdeps ]]
16✔
1264
        then
1✔
1265
                asdeps=true
3✔
1266
                asdeps_arr=(--asdeps)
3✔
1267
                shift
3✔
1268
        fi
1✔
1269

1✔
1270
        local target_packages=("$@")
32✔
1271

1✔
1272
        DetectAurHelper
16✔
1273

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

1✔
1304
function AconfNeedProgram() {
1✔
1305
        local program="$1" # program that needs to be in PATH
262✔
1306
        local package="$2" # package the program is available in
262✔
1307
        local foreign="$3" # whether this is a foreign package
262✔
1308

1✔
1309
        if ! hash "$program" 2> /dev/null
262✔
1310
        then
1✔
1311
                if [[ $foreign == y ]]
4✔
1312
                then
1✔
1313
                        LogEnter 'Installing foreign dependency %s:\n' "$(Color M %q "$package")"
5✔
1314
                        ParanoidConfirm ''
3✔
1315
                        AconfInstallForeign --asdeps "$package"
3✔
1316
                else
1✔
1317
                        LogEnter 'Installing native dependency %s:\n' "$(Color M %q "$package")"
3✔
1318
                        ParanoidConfirm ''
2✔
1319
                        AconfInstallNative --asdeps "$package"
2✔
1320
                fi
1✔
1321
                LogLeave 'Installed.\n'
4✔
1322
        fi
1✔
1323
}
1✔
1324

1✔
1325
# Get the path to the package file (.pkg.tar.*) for the specified package.
1✔
1326
# Download or build the package if necessary.
1✔
1327
function AconfNeedPackageFile() {
1✔
1328
        set -e
36✔
1329
        local package="$1"
36✔
1330

1✔
1331
        local info foreign
36✔
1332
        if info="$(LC_ALL=C "$PACMAN" --query --info "$package")"
108✔
1333
        then
1✔
1334
                if "$PACMAN" --query --quiet --foreign "$package" > /dev/null
21✔
1335
                then
1✔
1336
                        foreign=true
6✔
1337
                else
1✔
1338
                        foreign=false
16✔
1339
                fi
1✔
1340
        else
1✔
1341
                if info="$(LC_ALL=C "$PACMAN" --sync --info "$package")"
45✔
1342
                then
1✔
1343
                        foreign=false
6✔
1344
                else
1✔
1345
                        foreign=true
10✔
1346
                fi
1✔
1347
        fi
1✔
1348

1✔
1349
        local version='' architecture='' filemask_precise filemask_any
36✔
1350
        if [[ -n "$info" ]]
36✔
1351
        then
1✔
1352
                version="$(grep '^Version' <<< "$info" | sed 's/^.* : //g')"
78✔
1353
                architecture="$(grep '^Architecture' <<< "$info" | sed 's/^.* : //g')"
78✔
1354
                filemask_precise=$(printf "%q-%q-%q.pkg.*" "$package" "$version" "$architecture")
52✔
1355
        fi
1✔
1356
        filemask_any=$(printf "%q-*-*.pkg.*" "$package")
72✔
1357

1✔
1358
        # try without downloading first
1✔
1359
        local downloaded
36✔
1360
        for downloaded in false true
45✔
1361
        do
1✔
1362
                local precise
45✔
1363
                for precise in true false
64✔
1364
                do
1✔
1365
                        # if we don't have the exact version, we can only do non-precise
1✔
1366
                        if $precise && [[ -z "$version" ]]
109✔
1367
                        then
1✔
1368
                                continue
14✔
1369
                        fi
1✔
1370

1✔
1371
                        local filemask
50✔
1372
                        if $precise
50✔
1373
                        then
1✔
1374
                                filemask=$filemask_precise
31✔
1375
                        else
1✔
1376
                                filemask=$filemask_any
19✔
1377
                        fi
1✔
1378

1✔
1379
                        local dirs=()
100✔
1380
                        if $foreign
50✔
1381
                        then
1✔
1382
                                DetectAurHelper
22✔
1383
                                local -A tried_helper=()
44✔
1384

1✔
1385
                                local helper
22✔
1386
                                for helper in "$aur_helper" "${aur_helpers[@]}"
154✔
1387
                                do
1✔
1388
                                        if [[ ${tried_helper[$helper]+x} ]]
154✔
1389
                                        then
1✔
1390
                                                continue
22✔
1391
                                        fi
1✔
1392
                                        tried_helper[$helper]=y
132✔
1393

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

1✔
1433
                        local files=()
100✔
1434
                        local dir
50✔
1435
                        for dir in "${dirs[@]}"
138✔
1436
                        do
1✔
1437
                                if sudo test -d "$dir"
138✔
1438
                                then
1✔
1439
                                        sudo find "$dir" -type f -name "$filemask" -not -name '*.sig' -print0 | \
44✔
1440
                                                while read -r -d $'\0' file
80✔
1441
                                                do
1✔
1442
                                                        files+=("$file")
36✔
1443
                                                done
1✔
1444
                                fi
1✔
1445
                        done
1✔
1446

1✔
1447
                        local file
50✔
1448
                        for file in "${files[@]}"
36✔
1449
                        do
1✔
1450
                                local correct
36✔
1451
                                if $precise
36✔
1452
                                then
1✔
1453
                                        correct=true
26✔
1454
                                else
1✔
1455
                                        local pkgname
10✔
1456
                                        pkgname=$(bsdtar -x --to-stdout --file "$file" .PKGINFO | \
1✔
1457
                                                                  sed -n 's/^pkgname = \(.*\)$/\1/p')
30✔
1458
                                        if [[ "$pkgname" == "$package" ]]
10✔
1459
                                        then
1✔
1460
                                                correct=true
10✔
1461
                                        else
1✔
1462
                                                correct=false
1✔
1463
                                        fi
1✔
1464
                                fi
1✔
1465

1✔
1466
                                if $correct
36✔
1467
                                then
1✔
1468
                                        printf '%s' "$file"
36✔
1469
                                        return
36✔
1470
                                fi
1✔
1471
                        done
1✔
1472
                done
1✔
1473

1✔
1474
                if $downloaded
10✔
1475
                then
1✔
1476
                        Log 'Unable to find package file for package %s!\n' "$(Color M %q "$package")"
1✔
1477
                        Exit 1
1✔
1478
                else
1✔
1479
                        if $foreign
10✔
1480
                        then
1✔
1481
                                LogEnter 'Building foreign package %s\n' "$(Color M %q "$package")"
11✔
1482
                                ParanoidConfirm ''
6✔
1483

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

1✔
1521
                                LogLeave
6✔
1522
                        else
1✔
1523
                                LogEnter "Downloading package %s (%s) to pacman's cache\\n" "$(Color M %q "$package")" "$(Color C %s "$filemask_precise")"
13✔
1524
                                ParanoidConfirm ''
5✔
1525
                                sudo "$PACMAN" --sync --download --nodeps --nodeps --noconfirm "$package" 1>&2
5✔
1526
                                LogLeave
5✔
1527
                        fi
1✔
1528
                fi
1✔
1529
        done
1✔
1530
}
1✔
1531

1✔
1532
# Extract the original file from a package to stdout
1✔
1533
function AconfGetPackageOriginalFile() {
1✔
1534
        local package="$1" # Package to extract the file from
31✔
1535
        local file="$2" # Absolute path to file in package
31✔
1536

1✔
1537
        local package_file
31✔
1538
        package_file="$(AconfNeedPackageFile "$package")"
62✔
1539

1✔
1540
        local args=(bsdtar -x --to-stdout --file "$package_file" "${file/\//}")
62✔
1541
        if [[ -r "$package_file" ]]
31✔
1542
        then
22✔
1543
                "${args[@]}"
23✔
1544
        else
1✔
1545
                sudo "${args[@]}"
9✔
1546
        fi
1✔
1547
}
1✔
1548

1✔
1549
function AconfRestoreFile() {
1✔
1550
        local package=$1
6✔
1551
        local file=$2
6✔
1552

1✔
1553
        local package_file
6✔
1554
        package_file="$(AconfNeedPackageFile "$package")"
11✔
1555

1✔
1556
        # If we are restoring a directory, it may be non-empty.
1✔
1557
        # Extract the object to a temporary location first.
1✔
1558
        local tmp_base=${tmp_dir:?}/dir-props
6✔
1559
        sudo rm -rf "$tmp_base"
6✔
1560

1✔
1561
        mkdir -p "$tmp_base"
6✔
1562
        local tmp_file="$tmp_base""$file"
6✔
1563
        sudo tar x --directory "$tmp_base" --file "$package_file" --no-recursion "${file/\//}"
6✔
1564

1✔
1565
        AconfReplace "$tmp_file" "$file"
6✔
1566
        sudo rm -rf "$tmp_base"
6✔
1567
}
1✔
1568

1✔
1569
# Move filesystem object at $1 to $2, replacing any existing one.
1✔
1570
# Attempt to do so atomically, when possible.
1✔
1571
# Do the right thing when filesystem objects differ, but never
1✔
1572
# recursively remove directories (copy their attributes instead).
1✔
1573
function AconfReplace() {
1✔
1574
        local src=$1
6✔
1575
        local dst=$2
6✔
1576

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

1✔
1595
####################################################################################################
1✔
1596

1✔
1597
prompt_mode=normal # never / normal / paranoid
1,529✔
1598

1✔
1599
function Confirm() {
1✔
1600
        local detail_func="$1"
1✔
1601

1✔
1602
        if [[ $prompt_mode == never ]]
1✔
1603
        then
1✔
1604
                return
1✔
1605
        fi
1✔
1606

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

1✔
1636
function ParanoidConfirm() {
1✔
1637
        if [[ $prompt_mode == paranoid ]]
155✔
1638
        then
1✔
1639
                Confirm "$@"
155✔
1640
        fi
1✔
1641
}
1✔
1642

1✔
1643
####################################################################################################
1✔
1644

1✔
1645
log_indent=:
1,529✔
1646

1✔
1647
function Log() {
1✔
1648
        if [[ "$#" != 0 && -n "$1" ]]
155,862✔
1649
        then
1✔
1650
                local fmt="$1"
77,365✔
1651
                shift
77,358✔
1652

1✔
1653
                if [[ -z $ANSI_clear_line ]]
77,298✔
1654
                then
1✔
1655
                        # Replace carriage returns in format string with newline
1✔
1656
                        # when colors are disabled. This avoids systemd's journal
1✔
1657
                        # from showing such lines as [# blob data].
1✔
1658

1✔
1659
                        fmt=${fmt//\\r/\\n} # Replace the '\r' sequence
1✔
1660
                                            # (backslash-r) , not actual carriage
1✔
1661
                                            # returns.
1✔
1662
                fi
1✔
1663

1✔
1664
                printf "${ANSI_clear_line}${ANSI_color_B}%s ${ANSI_color_W}${fmt}${ANSI_reset}" "$log_indent" "$@" 1>&2
77,285✔
1665
        fi
1✔
1666
}
1✔
1667

1✔
1668
function LogEnter() {
1✔
1669
        Log "$@"
5,521✔
1670
        log_indent=$log_indent:
5,514✔
1671
}
1✔
1672

1✔
1673
function LogLeave() {
1✔
1674
        if [[ $# == 0 ]]
5,513✔
1675
        then
1✔
1676
                Log 'Done.\n'
3,466✔
1677
        else
1✔
1678
                Log "$@"
2,046✔
1679
        fi
1✔
1680

1✔
1681
        log_indent=${log_indent::-1}
5,522✔
1682
}
1✔
1683

1✔
1684
function ConfigWarning() {
1✔
1685
        Log '%s: '"$1" "$(Color Y "Warning")" "${@:2}"
17✔
1686
        printf W >> "$output_dir"/warnings
9✔
1687
}
1✔
1688

1✔
1689
function FatalError() {
1✔
1690
        Log "$@"
8✔
1691
        false
15✔
1692
        # if we're here, errexit is not set
1✔
1693
        Log 'Continuing after error. This is a bug, please report it.\n'
1✔
1694
        Exit 1
1✔
1695
}
1✔
1696

1✔
1697
function Color() {
1✔
1698
        local var="ANSI_color_$1"
70,144✔
1699
        printf -- "%s" "${!var}"
70,132✔
1700
        shift
70,162✔
1701
        # shellcheck disable=2059
1✔
1702
        printf -- "$@"
70,107✔
1703
        printf -- "%s" "${ANSI_color_W}"
70,103✔
1704
}
1✔
1705

1✔
1706
# The ANSI_color_* variables are looked up by name:
1✔
1707
# shellcheck disable=2034
1✔
1708
function DisableColor() {
1✔
1709
        ANSI_color_R=
1✔
1710
        ANSI_color_G=
1✔
1711
        ANSI_color_Y=
1✔
1712
        ANSI_color_B=
1✔
1713
        ANSI_color_M=
1✔
1714
        ANSI_color_C=
1✔
1715
        ANSI_color_W=
1✔
1716
        ANSI_reset=
1✔
1717
        ANSI_clear_line=
1✔
1718
}
1✔
1719

1✔
1720
####################################################################################################
1✔
1721

1✔
1722
function OnError() {
1✔
1723
        trap '' EXIT ERR
8✔
1724

1✔
1725
        LogEnter '%s! Stack trace:\n' "$(Color R "Fatal error")"
15✔
1726

1✔
1727
        local frame=0 str
8✔
1728
        while str=$(caller $frame)
57✔
1729
        do
1✔
1730
                if [[ $str =~ ^([^\ ]*)\ ([^\ ]*)\ (.*)$ ]]
22✔
1731
                then
1✔
1732
                        Log '%s:%s [%s]\n' "$(Color C "%q" "${BASH_REMATCH[3]}")" "$(Color G "%q" "${BASH_REMATCH[1]}")" "$(Color Y "%q" "${BASH_REMATCH[2]}")"
85✔
1733
                else
1✔
1734
                        Log '%s\n' "$str"
1✔
1735
                fi
1✔
1736

1✔
1737
                frame=$((frame+1))
22✔
1738
        done
1✔
1739

1✔
1740
        LogLeave ''
8✔
1741

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

1✔
1760
        # Ensure complete abort when inside a string expansion
1✔
1761
        exit 1
8✔
1762
}
1✔
1763
trap OnError EXIT ERR
1,529✔
1764

1✔
1765
function Exit() {
1✔
1766
        trap '' EXIT ERR
1,521✔
1767
        exit "${1:-0}"
1,521✔
1768
}
1✔
1769

1✔
1770
####################################################################################################
1✔
1771

1✔
1772
# Print an array, one element per line (assuming IFS starts with \n).
1✔
1773
function PrintArray() {
1✔
1774
        local name="$1" # Name of the global variable containing the array
1,807✔
1775
        local size
1,807✔
1776

1✔
1777
        size="$(eval "echo \${#${name}""[*]}")"
5,421✔
1778
        if [[ $size != 0 ]]
1,807✔
1779
        then
1✔
1780
                eval "echo \"\${${name}[*]}\""
1,356✔
1781
        fi
1✔
1782
}
1✔
1783

1✔
1784
# Ditto, but terminate elements with a NUL.
1✔
1785
function Print0Array() {
1✔
1786
        local name="$1" # Name of the global variable containing the array
1,933✔
1787

1✔
1788
        eval "$(cat <<EOF
1✔
1789
        if [[ \${#${name}[*]} != 0 ]]
1✔
1790
        then
1✔
1791
                local item
1✔
1792
                for item in "\${${name}[@]}"
1✔
1793
                do
1✔
1794
                        printf '%s\\0' "\$item"
1✔
1795
                done
1✔
1796
        fi
1✔
1797
EOF
1✔
1798
)"
5,799✔
1799
}
1800

1,320✔
1801
# Ditto, but shell-escape array elements.
9,062✔
1802
function PrintQArray() {
1803
        local name="$1" # Name of the global variable containing the array
9,927✔
1804
        local size
903✔
1805

1806
        size="$(eval "echo \${#${name}""[*]}")"
2,709✔
1807
        if [[ $size != 0 ]]
903✔
1808
        then
1809
                eval "printf -- %q \"\${${name}[0]}\""
8✔
1810
                if [[ $size -gt 1 ]]
4✔
1811
                then
1812
                        eval "printf -- ' %q' \"\${${name}[@]:1}\""
2✔
1813
                fi
1814
        fi
1815
}
1816

1817
if [[ $EUID == 0 ]]
1,529✔
1818
then
1819
        function sudo() { "$@" ; }
1820
fi
1821

1822
# Run external bash script.
1823
# No-op, except when running under the test suite with bashcov,
1824
# in which case it does not propagate bashcov to the invoked script.
1825
# Unlike `env -i`, does not nuke the environment.
1826
function RunExternal() {
1827
        env -u SHELLOPTS -u PS4 -u SHLVL -u BASH_XTRACEFD "$@"
8✔
1828
}
1829

1830
# cat a file; if it's not readable, cat via sudo.
1831
function SuperCat() {
1832
        local file="$1"
2✔
1833

1834
        if [[ -r "$1" ]]
2✔
1835
        then
1836
                cat "$1"
1✔
1837
        else
1838
                sudo cat "$1"
1✔
1839
        fi
1840
}
1841

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

1854
        Log '%s: Old bash detected, disabling unset variable checking.\n' "$(Color Y "Warning")"
×
1855
        set +u
×
1856
fi
1857

1858
: # include in coverage
1,529✔
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

© 2026 Coveralls, Inc