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

CyberShadow / aconfmgr / 373

02 Dec 2023 10:51AM UTC coverage: 84.045% (-9.6%) from 93.666%
373

push

github

CyberShadow-Renovate
Update dependency paru to v20231201221822

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

410 existing lines in 22 files now uncovered.

3777 of 4494 relevant lines covered (84.05%)

145.36 hits per line

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

69.17
/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,443✔
10

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

25
default_file_mode=644
1,443✔
26

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

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

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

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

46
# Defaults
47

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

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

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

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

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

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

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

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

133
        # Configuration
134

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

137
        typeset -ag ignore_packages=()
158✔
138
        typeset -ag ignore_foreign_packages=()
158✔
139
        typeset -Ag used_files
79✔
140

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

155
        if $lint_config
78✔
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 ]]
78✔
179
        then
180
                LogLeaveDirStats "$output_dir"
60✔
181
        else
182
                LogLeave 'Done (configuration not found).\n'
18✔
183
        fi
184
}
185

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

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

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

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

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

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

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

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

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

261
        ### Packages
262

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

268
        ### Files
269

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

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

277
        # Stray files
278

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

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

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

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

292
        AconfNeedProgram gawk gawk n
75✔
293

294
        # Progress display - only show file names once per second
295
        local progress_fd
75✔
296
        exec {progress_fd}> \
75✔
297
                 >( gawk '
75✔
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
        }
151✔
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
75✔
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 /                                                                        \
75✔
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                                \
75✔
338
                        | ( grep                                                                \
×
339
                                        --null --null-data                                \
150✔
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
437✔
350
                do
351
                        local file action
365✔
352
                        file=${line:1}
365✔
353
                        action=${line:0:1}
363✔
354

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

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

367
                                        if [[ $stray_file_count -eq $warn_file_count_threshold ]]
149✔
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"
213✔
400
                                        while [[ -n "$path" ]]
615✔
401
                                        do
402
                                                ignored_dirs[$path]=y
399✔
403
                                                path=${path%/*}
401✔
404
                                        done
405
                                        ;;
406
                        esac
407
                done
408

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

411
        exec {progress_fd}<&-
74✔
412

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

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

429
        LogLeave
74✔
430

431
        # Modified files
432

433
        LogEnter 'Searching for modified files...\n'
73✔
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" | \
146✔
453
                while read -r line
3,228✔
454
                do
455
                        if [[ $line =~ ^(.*):\ \'(.*)\'\ (type|size|modification\ time|md5sum|UID|GID|permission|symlink\ target)\ mismatch\ \(expected\ (.*)\)$ ]]
3,153✔
456
                        then
457
                                local package="${BASH_REMATCH[1]}"
195✔
458
                                local file="${BASH_REMATCH[2]}"
198✔
459
                                local kind="${BASH_REMATCH[3]}"
198✔
460
                                local value="${BASH_REMATCH[4]}"
199✔
461

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

474
                                if [[ $ignored == n ]]
181✔
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
181✔
515
                        elif [[ $line =~ ^(.*):\ \'(.*)\'\ missing\ file$ ]]
2,982✔
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\)$ ]]
2,971✔
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)$ ]]
2,767✔
546
                        then
547
                                local package="${BASH_REMATCH[1]}"
2,779✔
548
                                Log '%s...\r' "$(Color M "%q" "$package")"
5,589✔
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)"
150✔
555

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

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

570
        LogLeave # Reading file attributes
75✔
571

572
        LogEnter 'Checking disk space...\n'
75✔
573
        local -i i
75✔
574
        local -i total_blocks=0
75✔
575
        local -i tmp_block_size tmp_blocks_free
75✔
576
        tmp_block_size=$(stat -f -c %S "$system_dir")
150✔
577
        tmp_blocks_free=$(stat -f -c %f "$system_dir")
150✔
578
        for ((i=0; i<${#found_files[*]}; i++))
530✔
579
        do
580
                local -i size="${found_file_sizes[$i]}"
190✔
581
                local -i blocks=$(((size+tmp_block_size-1)/tmp_block_size)) # Count blocks
190✔
582
                total_blocks+=$blocks
190✔
583
                if (( total_blocks >= tmp_blocks_free ))
190✔
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
75✔
595

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

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

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

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

614
                if [[ -n "${found_file_edited[$file]+x}" ]]
148✔
615
                then
616
                        mkdir --parents "$(dirname "$system_dir"/files/"$file")"
294✔
617
                        if [[ "$type" == "symbolic link" ]]
147✔
618
                        then
619
                                ln -s "$(sudo readlink "$file")" "$system_dir"/files/"$file"
36✔
620
                        elif [[ "$type" == "regular file" || "$type" == "regular empty file" ]]
226✔
621
                        then
622
                                if [[ $size -gt $warn_size_threshold ]]
34✔
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
34✔
628
                                unset filter_func
34✔
629
                                for filter_pattern in "${!file_content_filters[@]}"
3✔
630
                                do
631
                                        # shellcheck disable=SC2053
632
                                        if [[ "$file" == $filter_pattern ]]
3✔
633
                                        then
634
                                                filter_func=${file_content_filters[$filter_pattern]}
3✔
635
                                        fi
636
                                done
637

638
                                if [[ -v filter_func ]]
34✔
639
                                then
640
                                        sudo cat "$file" | "$filter_func" "$file" > "$system_dir"/files/"$file"
6✔
641
                                else
642
                                        # shellcheck disable=SC2024
643
                                        sudo cat "$file" > "$system_dir"/files/"$file"
31✔
644
                                fi
645
                        elif [[ "$type" == "directory" ]]
95✔
646
                        then
647
                                mkdir --parents "$system_dir"/files/"$file"
95✔
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
148✔
656
                        for prop in mode owner group
444✔
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 ]]
498✔
662
                                then
663
                                        continue
18✔
664
                                fi
665

666
                                local value
426✔
667
                                eval "value=\$$prop"
852✔
668

669
                                local default_value
426✔
670

671
                                if [[ $i -lt $stray_file_count ]]
426✔
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=
336✔
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
90✔
684
                                fi
685

686
                                local orig_value
426✔
687
                                orig_value=$(AconfDefaultFileProp "$file" "$prop" "$type" "$default_value")
852✔
688

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

694
        LogLeave # Processing found files
75✔
695

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

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

701
typeset -A file_property_kind_exists
1,443✔
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
435✔
707
        local prop=$2 # Name of the property (owner, group, or mode)
435✔
708
        local type="${3:-}" # Type of the file, as identified by `stat --format=%F`
435✔
709
        local default="${4:-}" # Default value, returned if we don't know the original file property.
435✔
710

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

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

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

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

732
                        if [[ "$type" == "symbolic link" ]]
113✔
733
                        then
734
                                FatalError 'Symbolic links do not have a mode\n' # Bug
×
735
                        elif [[ "$type" == "directory" ]]
113✔
736
                        then
737
                                printf 755
85✔
738
                        else
739
                                printf '%s' "$default_file_mode"
28✔
740
                        fi
741
                        ;;
742
                owner|group)
743
                        printf 'root'
232✔
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
219✔
751
        local varname="$2"  # Name of global associative array variable to read into
219✔
752

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

763
                        if [[ -z "$value" ]]
460✔
764
                        then
765
                                unset "${varname}[\$file:\$kind]"
119✔
766
                        else
767
                                eval "${varname}[\$file:\$kind]=\"\$value\""
682✔
768
                        fi
769

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

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

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

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

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

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

808
        LogLeave
145✔
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'
73✔
819

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

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

828
        typeset -ag system_only_files=()
146✔
829
        local file
73✔
830

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

838
        typeset -ag changed_files=()
146✔
839

840
        AconfNeedProgram diff diffutils n
73✔
841

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

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

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

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

871
        typeset -ag config_only_files=()
146✔
872

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

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

885
        #
886
        # Modified file properties
887
        #
888

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

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

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

902
        AconfCompareFileProps
73✔
903

904
        LogLeave 'Done (%s only in system, %s changed, %s only in config).\n'        \
292✔
905
                         "$(Color G "${#system_only_file_props[@]}")"                                        \
292✔
906
                         "$(Color G "${#changed_file_props[@]}")"                                                \
292✔
907
                         "$(Color G "${#config_only_file_props[@]}")"
292✔
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'
72✔
917

918
        # Configuration
919

920
        AconfCompileOutput
72✔
921

922
        # System
923

924
        AconfCompileSystem
72✔
925

926
        # Vars
927

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

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

934
        AconfAnalyzeFiles
72✔
935

936
        LogLeave # Collecting data
72✔
937
}
938

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

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

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

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

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

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

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

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

983
base_devel_installed=n
1,443✔
984

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
1040
                LogEnter 'Assuming this package is part of a package base:\n'
×
1041

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

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

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

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

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

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

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

1084
                        if [[ ${#depends[@]} != 0 ]]
1✔
1085
                        then
UNCOV
1086
                                ( "$PACMAN" --deptest "${depends[@]}" || true ) | mapfile -t missing_depends
×
UNCOV
1087
                                if [[ ${#missing_depends[@]} != 0 ]]
×
1088
                                then
UNCOV
1089
                                        for dependency in "${missing_depends[@]}"
×
1090
                                        do
UNCOV
1091
                                                LogEnter '%s:\n' "$(Color M %q "$dependency")"
×
UNCOV
1092
                                                if "$PACMAN" --query --info "$dependency" > /dev/null 2>&1
×
1093
                                                then
1094
                                                        Log 'Already installed.\n' # Shouldn't happen, actually
×
UNCOV
1095
                                                elif "$PACMAN" --sync --info "$dependency" > /dev/null 2>&1
×
1096
                                                then
UNCOV
1097
                                                        Log 'Installing from repositories...\n'
×
UNCOV
1098
                                                        AconfInstallNative --asdeps "$dependency"
×
UNCOV
1099
                                                        Log 'Installed.\n'
×
1100
                                                else
UNCOV
1101
                                                        local installed=false
×
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.
UNCOV
1106
                                                        AconfNeedProgram pacsift pacutils n
×
UNCOV
1107
                                                        AconfNeedProgram unbuffer expect n
×
UNCOV
1108
                                                        local providers
×
1109
                                                        providers=$(unbuffer pacsift --sync --exact --satisfies="$dependency")
UNCOV
1110
                                                        if [[ -n "$providers" ]]
×
1111
                                                        then
UNCOV
1112
                                                                Log 'Installing provider package from repositories...\n'
×
UNCOV
1113
                                                                AconfInstallNative --asdeps "$dependency"
×
UNCOV
1114
                                                                Log 'Installed.\n'
×
UNCOV
1115
                                                                installed=true
×
1116
                                                        fi
1117

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

UNCOV
1126
                                                LogLeave ''
×
1127
                                        done
1128
                                fi
1129
                        fi
1130

1131
                        LogLeave
1✔
1132

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

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

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

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

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

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

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

UNCOV
1186
                                        LogLeave
×
1187
                                done
1188

UNCOV
1189
                                LogLeave
×
1190
                        fi
1191
                fi
1192
        done
1193

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

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

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

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

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

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

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

1239
        LogLeave
1✔
1240
}
1241

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

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

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

1270
        local target_packages=("$@")
2✔
1271

1272
        DetectAurHelper
1✔
1273

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

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

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

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

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

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

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

1371
                        local filemask
7✔
1372
                        if $precise
7✔
1373
                        then
1374
                                filemask=$filemask_precise
7✔
1375
                        else
UNCOV
1376
                                filemask=$filemask_any
×
1377
                        fi
1378

1379
                        local dirs=()
14✔
1380
                        if $foreign
7✔
1381
                        then
UNCOV
1382
                                DetectAurHelper
×
1383
                                local -A tried_helper=()
1384

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

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

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

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

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

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

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

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

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

1537
        local package_file
7✔
1538
        package_file="$(AconfNeedPackageFile "$package")"
14✔
1539

1540
        local args=(bsdtar -x --to-stdout --file "$package_file" "${file/\//}")
14✔
1541
        if [[ -r "$package_file" ]]
7✔
1542
        then
UNCOV
1543
                "${args[@]}"
×
1544
        else
1545
                sudo "${args[@]}"
7✔
1546
        fi
1547
}
1548

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

UNCOV
1553
        local package_file
×
UNCOV
1554
        package_file="$(AconfNeedPackageFile "$package")"
×
1555

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

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

UNCOV
1565
        AconfReplace "$tmp_file" "$file"
×
UNCOV
1566
        sudo rm -rf "$tmp_base"
×
1567
}
1568

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

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

1595
####################################################################################################
1596

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

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

UNCOV
1602
        if [[ $prompt_mode == never ]]
×
1603
        then
UNCOV
1604
                return
×
1605
        fi
1606

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

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

1643
####################################################################################################
1644

1645
log_indent=:
1,443✔
1646

1647
function Log() {
1648
        if [[ "$#" != 0 && -n "$1" ]]
18,367✔
1649
        then
1650
                local fmt="$1"
8,979✔
1651
                shift
8,980✔
1652

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

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

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

1668
function LogEnter() {
1669
        Log "$@"
2,588✔
1670
        log_indent=$log_indent:
2,569✔
1671
}
1672

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

1681
        log_indent=${log_indent::-1}
2,590✔
1682
}
1683

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

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

1697
function Color() {
1698
        local var="ANSI_color_$1"
5,422✔
1699
        printf -- "%s" "${!var}"
5,421✔
1700
        shift
5,424✔
1701
        # shellcheck disable=2059
1702
        printf -- "$@"
5,418✔
1703
        printf -- "%s" "${ANSI_color_W}"
5,418✔
1704
}
1705

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

1720
####################################################################################################
1721

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

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

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

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

1740
        LogLeave ''
7✔
1741

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

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

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

1770
####################################################################################################
1771

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

1777
        size="$(eval "echo \${#${name}""[*]}")"
2,565✔
1778
        if [[ $size != 0 ]]
855✔
1779
        then
1780
                eval "echo \"\${${name}[*]}\""
320✔
1781
        fi
1782
}
1783

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

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

629✔
1801
# Ditto, but shell-escape array elements.
2,033✔
1802
function PrintQArray() {
1803
        local name="$1" # Name of the global variable containing the array
2,777✔
1804
        local size
744✔
1805

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

1817
if [[ $EUID == 0 ]]
1,443✔
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() {
UNCOV
1827
        env -u SHELLOPTS -u PS4 -u SHLVL -u BASH_XTRACEFD "$@"
×
1828
}
1829

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

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

1842
if ! ( empty_array=() ; : "${empty_array[@]}" )
2,886✔
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,443✔
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