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

CyberShadow / aconfmgr / 663

22 Dec 2025 03:28PM UTC coverage: 91.226% (-2.5%) from 93.708%
663

push

github

web-flow
Merge 1fb44f3fa into 8755dc2ab

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

123 existing lines in 16 files now uncovered.

4575 of 5015 relevant lines covered (91.23%)

407.0 hits per line

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

94.37
/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}
6,600✔
10

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

25
default_file_mode=644
6,600✔
26

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

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

41
aconfmgr_action=
6,600✔
42
aconfmgr_action_args=()
6,600✔
43

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

46
# Defaults
47

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

95
makepkg_user=nobody # when running as root
6,597✔
96

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

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

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

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

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

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

133
        # Configuration
134

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

137
        typeset -ag ignore_packages=()
244✔
138
        typeset -ag ignore_foreign_packages=()
244✔
139
        typeset -Ag used_files
122✔
140

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

155
        if $lint_config
120✔
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 ]]
4✔
163
                then
164
                        local line
3✔
165
                        find "$config_dir"/files -type f -print0 | \
3✔
166
                                while read -r -d $'\0' line
6✔
167
                                do
168
                                        local key=${line#"$config_dir"/files}
3✔
169
                                        if [[ -z "${used_files[$key]+x}" ]]
3✔
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 ]]
120✔
179
        then
180
                LogLeaveDirStats "$output_dir"
102✔
181
        else
182
                LogLeave 'Done (configuration not found).\n'
18✔
183
        fi
184
}
185

186
skip_inspection=n
6,598✔
187
skip_checksums=n
6,598✔
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
117✔
202
        local -n ignore_args_var=$ignore_args_varname
117✔
203
        shift
117✔
204
        local ignore_paths=("$@")
234✔
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=()
234✔
212

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

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

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

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

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

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

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

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

261
        ### Packages
262

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

268
        ### Files
269

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

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

277
        # Stray files
278

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

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

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

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

292
        AconfNeedProgram gawk gawk n
117✔
293

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

322
        local stray_file_count=0
117✔
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 /                                                                        \
117✔
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                                \
117✔
338
                        | ( grep                                                                \
90✔
339
                                        --null --null-data                                \
144✔
340
                                        --invert-match                                        \
×
341
                                        --fixed-strings                                        \
×
342
                                        --line-regexp                                        \
×
343
                                        --file                                                        \
×
344
                                        <( < "$tmp_dir"/owned-files                \
×
345
                                                 sed -e 's#^#O#'                        \
×
346
                                         )                                                                \
×
347
                                        || true )                                                \
×
348
        ) |                                                                                                \
×
349
                while read -r -d $'\0' line
2,241✔
350
                do
351
                        local file action
2,200✔
352
                        file=${line:1}
2,186✔
353
                        action=${line:0:1}
2,183✔
354

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

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

367
                                        if [[ $stray_file_count -eq $warn_file_count_threshold ]]
198✔
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"
1,920✔
400
                                        while [[ -n "$path" ]]
5,472✔
401
                                        do
402
                                                ignored_dirs[$path]=y
3,483✔
403
                                                path=${path%/*}
3,467✔
404
                                        done
405
                                        ;;
406
                        esac
407
                done
408

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

411
        exec {progress_fd}<&-
102✔
412

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

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

429
        LogLeave
74✔
430

431
        # Modified files
432

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

435
        AconfNeedProgram paccheck pacutils n
73✔
436
        AconfNeedProgram unbuffer expect n
77✔
437
        local modified_file_count=0
81✔
438
        local -A saw_file
82✔
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
163✔
443

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

446
        local paccheck_opts=(unbuffer paccheck --files --file-properties --backup --noupgrade)
178✔
447
        if [[ $skip_checksums == n ]]
89✔
448
        then
449
                # Use SHA256 for pacman 7.0+ (libalpm v15+) which uses SHA256 in mtree
450
                # Fall back to MD5 for older versions
451
                if paccheck --help 2>&1 | grep -q -- '--sha256sum'
185✔
452
                then
453
                        paccheck_opts+=(--sha256sum)
44✔
454
                else
455
                        paccheck_opts+=(--md5sum)
69✔
456
                fi
457
        fi
458

459
        sudo sh -c "LC_ALL=C stdbuf -o0 $(printf ' %q' "${paccheck_opts[@]}") 2>&1 || true" | \
234✔
460
                while read -r line
33,074✔
461
                do
462
                        if [[ $line =~ ^(.*):\ \'(.*)\'\ (type|size|modification\ time|md5sum|sha256sum|UID|GID|permission|symlink\ target)\ mismatch\ \(expected\ (.*)\)$ ]]
32,752✔
463
                        then
464
                                local package="${BASH_REMATCH[1]}"
1,099✔
465
                                local file="${BASH_REMATCH[2]}"
1,101✔
466
                                local kind="${BASH_REMATCH[3]}"
1,100✔
467
                                local value="${BASH_REMATCH[4]}"
1,102✔
468

469
                                local ignored=n
1,106✔
470
                                local ignore_path
1,110✔
471
                                for ignore_path in "${ignore_paths[@]}"
19,112✔
472
                                do
473
                                        # shellcheck disable=SC2053
474
                                        if [[ "$file" == $ignore_path ]]
19,046✔
475
                                        then
476
                                                ignored=y
805✔
477
                                                break
806✔
478
                                        fi
479
                                done
480

481
                                if [[ $ignored == n ]]
901✔
482
                                then
483
                                        if [[ -z "${saw_file[$file]+x}" ]]
97✔
484
                                        then
485
                                                saw_file[$file]=y
36✔
486
                                                Log '%s: %s\n' "$(Color M "%q" "$package")" "$(Color C "%q" "$file")"
108✔
487
                                                found_files+=("$file")
36✔
488
                                                modified_file_count=$((modified_file_count+1))
36✔
489
                                        fi
490

491
                                        local prop
98✔
492
                                        case "$kind" in
98✔
493
                                                UID)
494
                                                        prop=owner
15✔
495
                                                        value=${value#*/}
15✔
496
                                                        ;;
497
                                                GID)
498
                                                        prop=group
15✔
499
                                                        value=${value#*/}
15✔
500
                                                        ;;
501
                                                permission)
502
                                                        prop=mode
19✔
503
                                                        ;;
504
                                                type|size|modification\ time|md5sum|sha256sum|symlink\ target)
505
                                                        prop=
49✔
506
                                                        found_file_edited[$file]=y
49✔
507
                                                        ;;
508
                                                *)
509
                                                        prop=
×
510
                                                        ;;
511
                                        esac
512

513
                                        if [[ -n "$prop" ]]
98✔
514
                                        then
515
                                                local key="$file:$prop"
49✔
516
                                                orig_file_props[$key]=$value
49✔
517

518
                                                printf '%s\t%s\t%q\n' "$prop" "$value" "$file" >> "$system_dir"/orig-file-props.txt
48✔
519
                                        fi
520
                                fi
521
                                printf '%s\0%s\0' "$file" "$package" >> "$tmp_dir"/file-owners
904✔
522
                        elif [[ $line =~ ^(.*):\ \'(.*)\'\ missing\ file$ ]]
31,959✔
523
                        then
524
                                local package="${BASH_REMATCH[1]}"
9✔
525
                                local file="${BASH_REMATCH[2]}"
9✔
526

527
                                local ignored=n
8✔
528
                                local ignore_path
8✔
529
                                for ignore_path in "${ignore_paths[@]}"
103✔
530
                                do
531
                                        # shellcheck disable=SC2053
532
                                        if [[ "$file" == $ignore_path ]]
102✔
533
                                        then
534
                                                ignored=y
1✔
535
                                                break
1✔
536
                                        fi
537
                                done
538

539
                                if [[ $ignored == y ]]
5✔
540
                                then
541
                                        continue
1✔
542
                                fi
543

544
                                Log '%s (missing)...\r' "$(Color M "%q" "$package")"
8✔
545
                                printf '%s\t%s\t%q\n' "deleted" "y" "$file" >> "$system_dir"/file-props.txt
6✔
546
                                printf '%s\0%s\0' "$file" "$package" >> "$tmp_dir"/file-owners
6✔
547
                        elif [[ $line =~ ^warning:\ (.*):\ \'(.*)\'\ read\ error\ \(No\ such\ file\ or\ directory\)$ ]]
31,785✔
548
                        then
549
                                local package="${BASH_REMATCH[1]}"
205✔
550
                                local file="${BASH_REMATCH[2]}"
205✔
551
                                # Ignore
552
                        elif [[ $line =~ ^(.*):\ all\ files\ match\ (database|mtree|mtree\ md5sums|mtree\ sha256sums)$ ]]
31,582✔
553
                        then
554
                                local package="${BASH_REMATCH[1]}"
31,858✔
555
                                Log '%s...\r' "$(Color M "%q" "$package")"
64,383✔
556
                                #echo "Now at ${BASH_REMATCH[1]}"
557
                        else
UNCOV
558
                                Log 'Unknown paccheck output line: %s\n' "$(Color Y "%q" "$line")"
×
559
                        fi
560
                done
561
        LogLeave 'Done (%s modified files).\n' "$(Color G %s $modified_file_count)"
234✔
562

563
        LogEnter 'Reading file attributes...\n'
117✔
564

565
        typeset -a found_file_types found_file_sizes found_file_modes found_file_owners found_file_groups
116✔
566
        if [[ ${#found_files[*]} == 0 ]]
116✔
567
        then
568
                Log 'No files found, skipping.\n'
×
569
        else
570
                Log 'Reading file types...\n'  ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%F | mapfile -t  found_file_types
464✔
571
                Log 'Reading file sizes...\n'  ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%s | mapfile -t  found_file_sizes
468✔
572
                Log 'Reading file modes...\n'  ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%a | mapfile -t  found_file_modes
468✔
573
                Log 'Reading file owners...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%U | mapfile -t found_file_owners
468✔
574
                Log 'Reading file groups...\n' ; Print0Array found_files | sudo env LC_ALL=C xargs -0 stat --format=%G | mapfile -t found_file_groups
468✔
575
        fi
576

577
        LogLeave # Reading file attributes
117✔
578

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

608
        LogEnter 'Processing found files...\n'
117✔
609

610
        for ((i=0; i<${#found_files[*]}; i++))
988✔
611
        do
612
                Log '%s/%s...\r' "$(Color G "$i")" "$(Color G "${#found_files[*]}")"
1,131✔
613

614
                local  file="${found_files[$i]}"
377✔
615
                local  type="${found_file_types[$i]}"
377✔
616
                local  size="${found_file_sizes[$i]}"
377✔
617
                local  mode="${found_file_modes[$i]}"
377✔
618
                local owner="${found_file_owners[$i]}"
377✔
619
                local group="${found_file_groups[$i]}"
377✔
620

621
                if [[ "${ignored_dirs[$file]-n}" == y ]]
377✔
622
                then
623
                        continue
168✔
624
                fi
625

626
                if [[ -n "${found_file_edited[$file]+x}" ]]
209✔
627
                then
628
                        mkdir --parents "$(dirname "$system_dir"/files/"$file")"
416✔
629
                        if [[ "$type" == "symbolic link" ]]
208✔
630
                        then
631
                                ln -s -- "$(sudo readlink "$file")" "$system_dir"/files/"$file"
38✔
632
                        elif [[ "$type" == "regular file" || "$type" == "regular empty file" ]]
333✔
633
                        then
634
                                if [[ $size -gt $warn_size_threshold ]]
47✔
635
                                then
636
                                        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")"
×
637
                                fi
638

639
                                local filter_pattern filter_func
47✔
640
                                unset filter_func
47✔
641
                                for filter_pattern in "${!file_content_filters[@]}"
6✔
642
                                do
643
                                        # shellcheck disable=SC2053
644
                                        if [[ "$file" == $filter_pattern ]]
6✔
645
                                        then
646
                                                filter_func=${file_content_filters[$filter_pattern]}
6✔
647
                                        fi
648
                                done
649

650
                                if [[ -v filter_func ]]
47✔
651
                                then
652
                                        sudo cat "$file" | "$filter_func" "$file" > "$system_dir"/files/"$file"
12✔
653
                                else
654
                                        # shellcheck disable=SC2024
655
                                        sudo cat "$file" > "$system_dir"/files/"$file"
41✔
656
                                fi
657
                        elif [[ "$type" == "directory" ]]
142✔
658
                        then
659
                                mkdir --parents "$system_dir"/files/"$file"
142✔
660
                        else
661
                                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")"
×
662
                                continue
×
663
                        fi
664
                fi
665

666
                {
667
                        local prop
209✔
668
                        for prop in mode owner group
627✔
669
                        do
670
                                # Ignore mode "changes" in symbolic links
671
                                # If a file's type changes, a change in mode can be reported too.
672
                                # But, symbolic links cannot have a mode, so ignore this change.
673
                                if [[ "$type" == "symbolic link" && "$prop" == mode ]]
684✔
674
                                then
675
                                        continue
19✔
676
                                fi
677

678
                                local value
608✔
679
                                eval "value=\$$prop"
1,216✔
680

681
                                local default_value
608✔
682

683
                                if [[ $i -lt $stray_file_count ]]
608✔
684
                                then
685
                                        # For stray files, the default owner/group is root/root,
686
                                        # and the default mode depends on the type.
687
                                        # Let AconfDefaultFileProp get the correct default value for us.
688

689
                                        default_value=
515✔
690
                                else
691
                                        # For owned files, we assume that the defaults are the
692
                                        # files' current properties, unless paccheck said
693
                                        # otherwise.
694

695
                                        default_value=$value
93✔
696
                                fi
697

698
                                local orig_value
608✔
699
                                orig_value=$(AconfDefaultFileProp "$file" "$prop" "$type" "$default_value")
1,216✔
700

701
                                [[ "$value" == "$orig_value" ]] || printf '%s\t%s\t%q\n' "$prop" "$value" "$file"
670✔
702
                        done
703
                } >> "$system_dir"/file-props.txt
×
704
        done
705

706
        LogLeave # Processing found files
117✔
707

708
        LogLeaveDirStats "$system_dir" # Inspecting system state
117✔
709
}
710

711
####################################################################################################
712

713
typeset -A file_property_kind_exists
6,601✔
714

715
# Print to stdout the original/default value of the given file property.
716
# Uses orig_file_props entry if present.
717
function AconfDefaultFileProp() {
718
        local file=$1 # Absolute path to the file
626✔
719
        local prop=$2 # Name of the property (owner, group, or mode)
626✔
720
        local type="${3:-}" # Type of the file, as identified by `stat --format=%F`
626✔
721
        local default="${4:-}" # Default value, returned if we don't know the original file property.
626✔
722

723
        local key="$file:$prop"
626✔
724

725
        if [[ -n "${orig_file_props[$key]+x}" ]]
626✔
726
        then
727
                printf '%s' "${orig_file_props[$key]}"
40✔
728
                return
40✔
729
        fi
730

731
        if [[ -n "$default" ]]
586✔
732
        then
733
                printf '%s' "$default"
53✔
734
                return
53✔
735
        fi
736

737
        case "$prop" in
533✔
738
                mode)
739
                        if [[ -z "$type" ]]
175✔
740
                        then
741
                                type=$(sudo env LC_ALL=C stat --format=%F "$file")
12✔
742
                        fi
743

744
                        if [[ "$type" == "symbolic link" ]]
175✔
745
                        then
746
                                FatalError 'Symbolic links do not have a mode\n' # Bug
×
747
                        elif [[ "$type" == "directory" ]]
175✔
748
                        then
749
                                printf 755
132✔
750
                        else
751
                                printf '%s' "$default_file_mode"
43✔
752
                        fi
753
                        ;;
754
                owner|group)
755
                        printf 'root'
358✔
756
                        ;;
757
        esac
758
}
759

760
# Read a file-props.txt file into an associative array.
761
function AconfReadFileProps() {
762
        local filename="$1" # Path to file-props.txt to be read
339✔
763
        local varname="$2"  # Name of global associative array variable to read into
339✔
764

765
        local line
339✔
766
        while read -r line
848✔
767
        do
768
                if [[ $line =~ ^(.*)\        (.*)\        (.*)$ ]]
509✔
769
                then
770
                        local kind="${BASH_REMATCH[1]}"
509✔
771
                        local value="${BASH_REMATCH[2]}"
509✔
772
                        local file="${BASH_REMATCH[3]}"
509✔
773
                        file="$(eval "printf %s $file")" # Unescape
1,527✔
774

775
                        if [[ -z "$value" ]]
509✔
776
                        then
777
                                unset "${varname}[\$file:\$kind]"
154✔
778
                        else
779
                                eval "${varname}[\$file:\$kind]=\"\$value\""
710✔
780
                        fi
781

782
                        file_property_kind_exists[$kind]=y
509✔
783
                fi
784
        done < "$filename"
×
785
}
786

787
# Compare file properties.
788
function AconfCompareFileProps() {
789
        LogEnter 'Comparing file properties...\n'
224✔
790

791
        typeset -ag system_only_file_props=()
444✔
792
        typeset -ag changed_file_props=()
446✔
793
        typeset -ag config_only_file_props=()
446✔
794

795
        local key
223✔
796
        for key in "${!system_file_props[@]}"
139✔
797
        do
798
                if [[ -z "${output_file_props[$key]+x}" ]]
139✔
799
                then
800
                        system_only_file_props+=("$key")
37✔
801
                fi
802
        done
803

804
        for key in "${!system_file_props[@]}"
128✔
805
        do
806
                if [[ -n "${output_file_props[$key]+x}" && "${system_file_props[$key]}" != "${output_file_props[$key]}" ]]
219✔
807
                then
808
                        changed_file_props+=("$key")
29✔
809
                fi
810
        done
811

812
        for key in "${!output_file_props[@]}"
131✔
813
        do
814
                if [[ -z "${system_file_props[$key]+x}" ]]
131✔
815
                then
816
                        config_only_file_props+=("$key")
67✔
817
                fi
818
        done
819

820
        LogLeave
220✔
821
}
822

823
# Compare file information in $output_dir and $system_dir.
824
function AconfAnalyzeFiles() {
825

826
        #
827
        # Stray/modified files - diff
828
        #
829

830
        LogEnter 'Examining files...\n'
113✔
831

832
        LogEnter 'Loading data...\n'
113✔
833
        mkdir --parents "$tmp_dir"
113✔
834
        ( cd "$output_dir"/files && find . -mindepth 1 -print0 ) | cut --zero-terminated -c 2- | sort --zero-terminated > "$tmp_dir"/output-files
452✔
835
        ( cd "$system_dir"/files && find . -mindepth 1 -print0 ) | cut --zero-terminated -c 2- | sort --zero-terminated > "$tmp_dir"/system-files
452✔
836
        LogLeave
113✔
837

838
        Log 'Comparing file data...\n'
113✔
839

840
        typeset -ag system_only_files=()
226✔
841
        local file
113✔
842

843
        ( comm -13 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
113✔
844
                while read -r -d $'\0' file
161✔
845
                do
846
                        Log 'Only in system: %s\n' "$(Color C "%q" "$file")"
96✔
847
                        system_only_files+=("$file")
48✔
848
                done
849

850
        typeset -ag changed_files=()
226✔
851

852
        AconfNeedProgram diff diffutils n
113✔
853

854
        ( comm -12 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
113✔
855
                while read -r -d $'\0' file
171✔
856
                do
857
                        local output_type system_type
58✔
858
                        output_type=$(LC_ALL=C stat --format=%F "$output_dir"/files/"$file")
174✔
859
                        system_type=$(LC_ALL=C stat --format=%F "$system_dir"/files/"$file")
174✔
860

861
                        if [[ "$output_type" != "$system_type" ]]
58✔
862
                        then
863
                                Log 'Changed type (%s / %s): %s\n' \
80✔
864
                                        "$(Color Y "%q" "$output_type")" \
80✔
865
                                        "$(Color Y "%q" "$system_type")" \
80✔
866
                                        "$(Color C "%q" "$file")"
80✔
867
                                changed_files+=("$file")
20✔
868
                                continue
20✔
869
                        fi
870

871
                        if [[ "$output_type" == "directory" || "$system_type" == "directory" ]]
67✔
872
                        then
873
                                continue
9✔
874
                        fi
875

876
                        if ! diff --no-dereference --brief "$output_dir"/files/"$file" "$system_dir"/files/"$file" > /dev/null
29✔
877
                        then
878
                                Log 'Changed: %s\n' "$(Color C "%q" "$file")"
20✔
879
                                changed_files+=("$file")
10✔
880
                        fi
881
                done
882

883
        typeset -ag config_only_files=()
226✔
884

885
        ( comm -23 --zero-terminated "$tmp_dir"/output-files "$tmp_dir"/system-files ) | \
113✔
886
                while read -r -d $'\0' file
153✔
887
                do
888
                        Log 'Only in config: %s\n' "$(Color C "%q" "$file")"
80✔
889
                        config_only_files+=("$file")
40✔
890
                done
891

892
        LogLeave 'Done (%s only in system, %s changed, %s only in config).\n'        \
452✔
893
                         "$(Color G "${#system_only_files[@]}")"                                                \
452✔
894
                         "$(Color G "${#changed_files[@]}")"                                                        \
452✔
895
                         "$(Color G "${#config_only_files[@]}")"
452✔
896

897
        #
898
        # Modified file properties
899
        #
900

901
        LogEnter 'Examining file properties...\n'
113✔
902

903
        LogEnter 'Loading data...\n'
113✔
904
        unset orig_file_props # Also populated by AconfCompileSystem, so that it can be used by AconfDefaultFileProp
113✔
905
        typeset -Ag output_file_props ; AconfReadFileProps "$output_dir"/file-props.txt output_file_props
226✔
906
        typeset -Ag system_file_props ; AconfReadFileProps "$system_dir"/file-props.txt system_file_props
226✔
907
        typeset -Ag   orig_file_props ; AconfReadFileProps "$system_dir"/orig-file-props.txt orig_file_props
226✔
908
        LogLeave
113✔
909

910
        typeset -ag all_file_property_kinds
113✔
911
        all_file_property_kinds=("${!file_property_kind_exists[@]}")
113✔
912
        Print0Array all_file_property_kinds | sort --zero-terminated | mapfile -t -d $'\0' all_file_property_kinds
339✔
913

914
        AconfCompareFileProps
113✔
915

916
        LogLeave 'Done (%s only in system, %s changed, %s only in config).\n'        \
449✔
917
                         "$(Color G "${#system_only_file_props[@]}")"                                        \
449✔
918
                         "$(Color G "${#changed_file_props[@]}")"                                                \
449✔
919
                         "$(Color G "${#config_only_file_props[@]}")"
449✔
920
}
921

922
# The *_packages arrays are passed by name,
923
# so ShellCheck thinks the variables are unused:
924
# shellcheck disable=2034
925

926
# Prepare configuration and system state
927
function AconfCompile() {
928
        LogEnter 'Collecting data...\n'
112✔
929

930
        # Configuration
931

932
        AconfCompileOutput
112✔
933

934
        # System
935

936
        AconfCompileSystem
112✔
937

938
        # Vars
939

940
        < "$output_dir"/packages.txt         sort --unique | mapfile -t                   packages
224✔
941
        < "$system_dir"/packages.txt         sort --unique | mapfile -t         installed_packages
224✔
942

943
        < "$output_dir"/foreign-packages.txt sort --unique | mapfile -t           foreign_packages
224✔
944
        < "$system_dir"/foreign-packages.txt sort --unique | mapfile -t installed_foreign_packages
224✔
945

946
        AconfAnalyzeFiles
112✔
947

948
        LogLeave # Collecting data
112✔
949
}
950

951
####################################################################################################
952

953
pacman_opts=("$PACMAN")
6,601✔
954
aurman_opts=(aurman)
6,601✔
955
pacaur_opts=(pacaur)
6,601✔
956
yaourt_opts=(yaourt)
6,601✔
957
yay_opts=(yay)
6,601✔
958
paru_opts=(paru)
6,601✔
959
aura_opts=(aura)
6,601✔
960
makepkg_opts=(makepkg)
6,601✔
961
diff_opts=(diff '--color=auto')
6,601✔
962

963
aur_helper=
6,601✔
964
aur_helpers=(aurman pacaur yaourt yay paru aura makepkg)
6,601✔
965

966
# Only aconfmgr can use makepkg under root
967
if [[ $EUID == 0 ]]
6,601✔
968
then
969
        aur_helper=makepkg
×
970
fi
971

972
function DetectAurHelper() {
973
        if [[ -n "$aur_helper" ]]
16✔
974
        then
975
                return
10✔
976
        fi
977

978
        LogEnter 'Detecting AUR helper...\n'
6✔
979

980
        local helper
6✔
981
        for helper in "${aur_helpers[@]}"
42✔
982
        do
983
                if hash "$helper" 2> /dev/null
42✔
984
                then
985
                        aur_helper=$helper
6✔
986
                        LogLeave '%s... Yes\n' "$(Color C %s "$helper")"
12✔
987
                        return
6✔
988
                fi
989
                Log '%s... No\n' "$(Color C %s "$helper")"
72✔
990
        done
991

992
        Log 'Can'\''t find even makepkg!?\n'
×
993
        Exit 1
×
994
}
995

996
base_devel_installed=n
6,601✔
997

998
# Query AUR RPC API to find the package base for a given package name.
999
# This is used to resolve virtual provides and split packages without
1000
# requiring auracle-git to be installed (which would create circular dependencies).
1001
function AconfQueryAURPackageBase() {
1002
        local package=$1
1✔
1003
        local aur_rpc_url="https://aur.archlinux.org/rpc/?v=5"
1✔
1004
        local pkg_base=""
1✔
1005

1006
        # Try exact package name match first
1007
        local response resultcount
1✔
1008
        response=$(curl -fsSL "${aur_rpc_url}&type=info&arg=${package}" 2>/dev/null || true)
2✔
1009

1010
        if [[ -n "$response" ]]
1✔
1011
        then
1012
                resultcount=$(printf '%s' "$response" | sed -n 's/.*"resultcount":\([0-9]*\).*/\1/p')
3✔
1013
                if [[ "$resultcount" -gt 0 ]]
1✔
1014
                then
UNCOV
1015
                        pkg_base=$(printf '%s' "$response" | grep -o '"PackageBase":"[^"]*"' | head -1 | sed 's/"PackageBase":"\([^"]*\)"/\1/')
×
1016
                fi
1017
        fi
1018

1019
        # If not found, search by provides (for virtual packages like 'glaze' provided by 'glaze-git')
1020
        if [[ -z "$pkg_base" ]]
1✔
1021
        then
1022
                response=$(curl -fsSL "${aur_rpc_url}&type=search&by=provides&arg=${package}" 2>/dev/null || true)
2✔
1023

1024
                if [[ -n "$response" ]]
1✔
1025
                then
1026
                        resultcount=$(printf '%s' "$response" | sed -n 's/.*"resultcount":\([0-9]*\).*/\1/p')
3✔
1027
                        if [[ "$resultcount" -gt 0 ]]
1✔
1028
                        then
1029
                                pkg_base=$(printf '%s' "$response" | grep -o '"PackageBase":"[^"]*"' | head -1 | sed 's/"PackageBase":"\([^"]*\)"/\1/')
5✔
1030
                        fi
1031
                fi
1032
        fi
1033

1034
        printf '%s' "$pkg_base"
1✔
1035
}
1036

1037
function AconfMakePkg() {
1038
        local install=true
12✔
1039
        if [[ "$1" == --noinstall ]]
12✔
1040
        then
UNCOV
1041
                install=false
×
UNCOV
1042
                shift
×
1043
        fi
1044

1045
        local package="$1"
12✔
1046
        local asdeps="${2:-false}"
12✔
1047

1048
        LogEnter 'Building foreign package %s from source.\n' "$(Color M %q "$package")"
24✔
1049

1050
        # shellcheck disable=SC2174
1051
        mkdir --parents --mode=700 "$aur_dir"
12✔
1052
        if [[ $EUID == 0 ]]
12✔
1053
        then
1054
                chown -R "$makepkg_user": "$aur_dir"
×
1055
        fi
1056

1057
        local pkg_dir="$aur_dir"/"$package"
12✔
1058
        Log 'Using directory %s.\n' "$(Color C %q "$pkg_dir")"
24✔
1059

1060
        rm -rf "$pkg_dir"
12✔
1061
        mkdir --parents "$pkg_dir"
12✔
1062

1063
        # Needed to clone the AUR repo. Should be replaced with curl/tar.
1064
        AconfNeedProgram git git n
12✔
1065

1066
        if [[ $base_devel_installed == n ]]
12✔
1067
        then
1068
                LogEnter 'Making sure the %s package is installed...\n' "$(Color M base-devel)"
18✔
1069
                ParanoidConfirm ''
9✔
1070
                if ! "$PACMAN" --query --quiet base-devel > /dev/null 2>&1
9✔
1071
                then
1072
                        AconfInstallNative base-devel
1✔
1073
                fi
1074

1075
                LogLeave
9✔
1076
                base_devel_installed=y
9✔
1077
        fi
1078

1079
        LogEnter 'Cloning...\n'
12✔
1080
        git clone "https://aur.archlinux.org/$package.git" "$pkg_dir"
12✔
1081
        LogLeave
12✔
1082

1083
        if [[ ! -f "$pkg_dir"/PKGBUILD ]]
12✔
1084
        then
1085
                Log 'No package description file found!\n'
1✔
1086

1087
                if [[ "$package" == auracle-git ]]
1✔
1088
                then
1089
                        FatalError 'Failed to download aconfmgr dependency!\n'
×
1090
                fi
1091

1092
                LogEnter 'Assuming this package is part of a package base:\n'
1✔
1093

1094
                LogEnter 'Retrieving package info from AUR...\n'
1✔
1095
                local pkg_base
1✔
1096
                pkg_base=$(AconfQueryAURPackageBase "$package")
2✔
1097

1098
                if [[ -z "$pkg_base" ]]
1✔
1099
                then
1100
                        # Fallback to auracle if AUR RPC fails
1101
                        Log 'AUR RPC query failed, falling back to auracle...\n'
×
1102
                        AconfNeedProgram auracle auracle-git y
×
1103
                        pkg_base=$(auracle info --format '{pkgbase}' "$package")
1104
                fi
1105
                LogLeave 'Done, package base is %s.\n' "$(Color M %q "$pkg_base")"
2✔
1106

1107
                AconfMakePkg "$pkg_base" "$asdeps" # recurse
1✔
1108
                LogLeave # Package base
1✔
1109
                LogLeave # Package
1✔
1110
                return
1✔
1111
        fi
1112

1113
        AconfMakePkgDir "$package" "$asdeps" "$install" "$pkg_dir"
11✔
1114
}
1115

1116
function AconfMakePkgDir() {
1117
        local package=$1
11✔
1118
        local asdeps=$2
11✔
1119
        local install=$3
11✔
1120
        local pkg_dir=$4
11✔
1121

1122
        local gnupg_home
11✔
1123
        gnupg_home="$(realpath -m "$tmp_dir/gnupg")"
22✔
1124

1125
        local infofile infofilename
11✔
1126
        for infofilename in .SRCINFO .AURINFO
22✔
1127
        do
1128
                infofile="$pkg_dir"/"$infofilename"
22✔
1129
                if test -f "$infofile"
22✔
1130
                then
1131
                        LogEnter 'Checking dependencies...\n'
11✔
1132

1133
                        local depends missing_depends dependency arch
11✔
1134
                        arch="$(uname -m)"
22✔
1135
                        # Filter out packages from the same base
1136
                        ( grep -E $'^\t(make|check)?depends(_'"$arch"')? = ' "$infofile" || true ) \
15✔
1137
                                | sed 's/^.* = \([^<>=]*\)\([<>=].*\)\?$/\1/g' \
11✔
1138
                                | ( grep -vFf <(( grep '^pkgname = ' "$infofile" || true) \
33✔
1139
                                                                        | sed 's/^.* = \(.*\)$/\1/g' ) \
×
1140
                                                || true ) \
4✔
1141
                                | mapfile -t depends
11✔
1142

1143
                        if [[ ${#depends[@]} != 0 ]]
11✔
1144
                        then
1145
                                ( "$PACMAN" --deptest "${depends[@]}" || true ) | mapfile -t missing_depends
21✔
1146
                                if [[ ${#missing_depends[@]} != 0 ]]
7✔
1147
                                then
1148
                                        for dependency in "${missing_depends[@]}"
19✔
1149
                                        do
1150
                                                LogEnter '%s:\n' "$(Color M %q "$dependency")"
38✔
1151
                                                if "$PACMAN" --query --info "$dependency" > /dev/null 2>&1
19✔
1152
                                                then
1153
                                                        Log 'Already installed.\n' # Shouldn't happen, actually
×
1154
                                                elif "$PACMAN" --sync --info "$dependency" > /dev/null 2>&1
19✔
1155
                                                then
1156
                                                        Log 'Installing from repositories...\n'
15✔
1157
                                                        AconfInstallNative --asdeps "$dependency"
15✔
1158
                                                        Log 'Installed.\n'
15✔
1159
                                                else
1160
                                                        local installed=false
4✔
1161

1162
                                                        # Check if this package is provided by something in pacman repos.
1163
                                                        # `pacman -Si` will not give us that information,
1164
                                                        # however, `pacman -S` still works.
1165
                                                        AconfNeedProgram pacsift pacutils n
4✔
1166
                                                        AconfNeedProgram unbuffer expect n
4✔
1167
                                                        local providers
4✔
1168
                                                        providers=$(unbuffer pacsift --sync --exact --satisfies="$dependency")
8✔
1169
                                                        if [[ -n "$providers" ]]
4✔
1170
                                                        then
1171
                                                                Log 'Installing provider package from repositories...\n'
2✔
1172
                                                                AconfInstallNative --asdeps "$dependency"
2✔
1173
                                                                Log 'Installed.\n'
2✔
1174
                                                                installed=true
2✔
1175
                                                        fi
1176

1177
                                                        if ! $installed
4✔
1178
                                                        then
1179
                                                                Log 'Installing from AUR...\n'
2✔
1180
                                                                AconfMakePkg "$dependency" true
2✔
1181
                                                                Log 'Installed.\n'
2✔
1182
                                                        fi
1183
                                                fi
1184

1185
                                                LogLeave ''
19✔
1186
                                        done
1187
                                fi
1188
                        fi
1189

1190
                        LogLeave
11✔
1191

1192
                        local keys
11✔
1193
                        ( grep -E $'^\tvalidpgpkeys = ' "$infofile" || true ) | sed 's/^.* = \(.*\)$/\1/' | mapfile -t keys
43✔
1194
                        if [[ ${#keys[@]} != 0 ]]
11✔
1195
                        then
1196
                                LogEnter 'Checking PGP keys...\n'
1✔
1197

1198
                                local key
1✔
1199
                                for key in "${keys[@]}"
1✔
1200
                                do
1201
                                        export GNUPGHOME="$gnupg_home"
2✔
1202

1203
                                        if [[ ! -d "$GNUPGHOME" ]]
1✔
1204
                                        then
1205
                                                LogEnter 'Creating %s...\n' "$(Color C %s "$GNUPGHOME")"
2✔
1206
                                                mkdir --parents "$GNUPGHOME"
1✔
1207
                                                gpg --gen-key --batch <<EOF
1✔
1208
Key-Type: DSA
1✔
1209
Key-Length: 1024
1✔
1210
Name-Real: aconfmgr
1✔
1211
%no-protection
1✔
1212
EOF
1✔
1213
                                                LogLeave
1✔
1214
                                        fi
1✔
1215

1✔
1216
                                        LogEnter 'Adding key %s...\n' "$(Color Y %q "$key")"
2✔
1217
                                        #ParanoidConfirm ''
1✔
1218

1✔
1219
                                        local ok=false
1✔
1220
                                        local keyserver
1✔
1221
                                        for keyserver in keys.gnupg.net pgp.mit.edu pool.sks-keyservers.net keyserver.ubuntu.com # subkeys.pgp.net
1✔
1222
                                        do
1✔
1223
                                                LogEnter 'Trying keyserver %s...\n' "$(Color C %s "$keyserver")"
2✔
1224
                                                if gpg --keyserver "$keyserver" --recv-key "$key"
1✔
1225
                                                then
1✔
1226
                                                        ok=true
1✔
1227
                                                        LogLeave 'OK!\n'
1✔
1228
                                                        break
1✔
1229
                                                else
1✔
1230
                                                        LogLeave 'Error...\n'
1✔
1231
                                                fi
1✔
1232
                                        done
1✔
1233

1✔
1234
                                        if ! $ok
1✔
1235
                                        then
1✔
1236
                                                FatalError 'No keyservers succeeded.\n'
1✔
1237
                                        fi
1✔
1238

1✔
1239
                                        if [[ $EUID == 0 ]]
1✔
1240
                                        then
1✔
1241
                                                chmod 700 "$gnupg_home"
1✔
1242
                                                chown -R "$makepkg_user": "$gnupg_home"
1✔
1243
                                        fi
1✔
1244

1✔
1245
                                        LogLeave
1✔
1246
                                done
1✔
1247

1✔
1248
                                LogLeave
1✔
1249
                        fi
1✔
1250
                fi
1✔
1251
        done
1✔
1252

1✔
1253
        LogEnter 'Evaluating environment...\n'
11✔
1254
        local path
11✔
1255
        # shellcheck disable=SC2016
1✔
1256
        path=$(env -i sh -c 'source /etc/profile 1>&2 ; printf -- %s "$PATH"')
22✔
1257
        LogLeave
11✔
1258

1✔
1259
        LogEnter 'Building...\n'
11✔
1260
        (
1✔
1261
                cd "$pkg_dir"
11✔
1262
                mkdir --parents home
11✔
1263
                # Set CARGO_TARGET_DIR to avoid issues with Rust builds on mounted volumes
1✔
1264
                # This prevents "could not write output" errors when building Rust packages
1✔
1265
                local cargo_target_dir="/tmp/cargo-target-$$"
11✔
1266
                local args=(env -i "PATH=$path" "HOME=$PWD/home" "GNUPGHOME=$gnupg_home" "CARGO_TARGET_DIR=$cargo_target_dir" "${makepkg_opts[@]}")
22✔
1267

1✔
1268
                if [[ $EUID == 0 ]]
11✔
1269
                then
1✔
1270
                        chown -R "$makepkg_user": .
1✔
1271
                        setpriv --reuid="$makepkg_user" --regid="$makepkg_user" --clear-groups bash -c "GNUPGHOME=$(realpath ../../gnupg) $(printf ' %q' "${args[@]}")" 1>&2
1✔
1272

1✔
1273
                        if $install
1✔
1274
                        then
1✔
1275
                                local pkglist
1✔
1276
                                setpriv --reuid="$makepkg_user" --regid="$makepkg_user" --clear-groups bash -c "GNUPGHOME=$(realpath ../../gnupg) $(printf ' %q' "${args[@]}" --packagelist)" | mapfile -t pkglist
1✔
1277

1✔
1278
                                # Filter out packages that don't exist (e.g., debug packages not built by default)
1✔
1279
                                local existing_pkgs=()
1✔
1280
                                local skipped_pkgs=()
1✔
1281
                                local pkg
1✔
1282
                                for pkg in "${pkglist[@]}"
1✔
1283
                                do
1✔
1284
                                        if [[ -f "$pkg" ]]
1✔
1285
                                        then
1✔
1286
                                                existing_pkgs+=("$pkg")
1✔
1287
                                        else
1✔
1288
                                                skipped_pkgs+=("$pkg")
1✔
1289
                                        fi
1✔
1290
                                done
1✔
1291

1✔
1292
                                if [[ ${#skipped_pkgs[@]} -gt 0 ]]
1✔
1293
                                then
1✔
1294
                                        Log 'Skipping %s non-existent package(s) from packagelist:\n' "$(Color G "${#skipped_pkgs[@]}")"
1✔
1295
                                        for pkg in "${skipped_pkgs[@]}"
1✔
1296
                                        do
1✔
1297
                                                Log '  %s\n' "$(Color M "%q" "$(basename "$pkg")")"
1✔
1298
                                        done
1✔
1299
                                fi
1✔
1300

1✔
1301
                                if [[ ${#existing_pkgs[@]} -eq 0 ]]
1✔
1302
                                then
1✔
1303
                                        Log 'Warning: No packages to install (all were filtered out)\n'
1✔
1304
                                elif $asdeps
1✔
1305
                                then
1✔
1306
                                        "${pacman_opts[@]}" --upgrade --asdeps "${existing_pkgs[@]}"
1✔
1307
                                else
1✔
1308
                                        "${pacman_opts[@]}" --upgrade "${existing_pkgs[@]}"
1✔
1309
                                fi
1✔
1310
                        fi
1✔
1311
                else
1✔
1312
                        if $asdeps
11✔
1313
                        then
1✔
1314
                                args+=(--asdeps)
4✔
1315
                        fi
1✔
1316

1✔
1317
                        if $install
11✔
1318
                        then
1✔
1319
                                args+=(--install)
11✔
1320
                        fi
11✔
1321

11✔
1322
                        "${args[@]}" 1>&2
11✔
1323
                fi
1✔
1324
        )
1✔
1325
        LogLeave
11✔
1326

1✔
1327
        LogLeave
11✔
1328
}
1✔
1329

1✔
1330
function AconfInstallNative() {
1✔
1331
        local asdeps=false asdeps_arr=()
48✔
1332
        if [[ "$1" == --asdeps ]]
24✔
1333
        then
1✔
1334
                asdeps=true
18✔
1335
                asdeps_arr=(--asdeps)
18✔
1336
                shift
18✔
1337
        fi
1✔
1338

1✔
1339
        local target_packages=("$@")
48✔
1340
        if [[ $prompt_mode == never ]]
24✔
1341
        then
1✔
1342
                # Some prompts default to 'no'
1✔
1343
                ( yes || true ) | sudo "${pacman_opts[@]}" --confirm --sync "${asdeps_arr[@]}" "${target_packages[@]}"
1✔
1344
        else
1✔
1345
                sudo "${pacman_opts[@]}" --sync "${asdeps_arr[@]}" "${target_packages[@]}"
24✔
1346
        fi
1✔
1347
}
1✔
1348

1✔
1349
function AconfInstallForeign() {
1✔
1350
        local asdeps=false asdeps_arr=()
20✔
1351
        if [[ "$1" == --asdeps ]]
10✔
1352
        then
1✔
1353
                asdeps=true
2✔
1354
                asdeps_arr=(--asdeps)
2✔
1355
                shift
2✔
1356
        fi
1✔
1357

1✔
1358
        local target_packages=("$@")
20✔
1359

1✔
1360
        DetectAurHelper
10✔
1361

1✔
1362
        case "$aur_helper" in
10✔
1363
                aurman)
1✔
1364
                        RunExternal "${aurman_opts[@]}" --sync --aur "${asdeps_arr[@]}" "${target_packages[@]}"
1✔
1365
                        ;;
1✔
1366
                pacaur)
1✔
1367
                        RunExternal "${pacaur_opts[@]}" --sync --aur "${asdeps_arr[@]}" "${target_packages[@]}"
2✔
1368
                        ;;
1✔
1369
                yaourt)
1✔
1370
                        RunExternal "${yaourt_opts[@]}" --sync --aur "${asdeps_arr[@]}" "${target_packages[@]}"
1✔
1371
                        ;;
1✔
1372
                yay)
1✔
1373
                        RunExternal "${yay_opts[@]}" --sync --aur "${asdeps_arr[@]}" "${target_packages[@]}"
2✔
1374
                        ;;
1✔
1375
                paru)
1✔
1376
                        RunExternal "${paru_opts[@]}" --sync --aur "${asdeps_arr[@]}" "${target_packages[@]}"
2✔
1377
                        ;;
1✔
1378
                aura)
1✔
1379
                        RunExternal "${aura_opts[@]}" -A "${asdeps_arr[@]}" "${target_packages[@]}"
1✔
1380
                        ;;
1✔
1381
                makepkg)
1✔
1382
                        local package
7✔
1383
                        for package in "${target_packages[@]}"
7✔
1384
                        do
1✔
1385
                                AconfMakePkg "$package" "$asdeps"
7✔
1386
                        done
1✔
1387
                        ;;
1✔
1388
                *)
1✔
1389
                        Log 'Error: unknown AUR helper %q\n' "$aur_helper"
1✔
1390
                        false
1✔
1391
                        ;;
1✔
1392
        esac
1✔
1393
}
1✔
1394

1✔
1395
function AconfNeedProgram() {
1✔
1396
        local program="$1" # program that needs to be in PATH
131✔
1397
        local package="$2" # package the program is available in
132✔
1398
        local foreign="$3" # whether this is a foreign package
133✔
1399

1✔
1400
        if ! hash "$program" 2> /dev/null
133✔
1401
        then
1✔
1402
                if [[ $foreign == y ]]
3✔
1403
                then
1✔
1404
                        LogEnter 'Installing foreign dependency %s:\n' "$(Color M %q "$package")"
3✔
1405
                        ParanoidConfirm ''
2✔
1406
                        AconfInstallForeign --asdeps "$package"
2✔
1407
                else
1✔
1408
                        LogEnter 'Installing native dependency %s:\n' "$(Color M %q "$package")"
3✔
1409
                        ParanoidConfirm ''
2✔
1410
                        AconfInstallNative --asdeps "$package"
2✔
1411
                fi
1✔
1412
                LogLeave 'Installed.\n'
3✔
1413
        fi
1✔
1414
}
1✔
1415

1✔
1416
# Get the path to the package file (.pkg.tar.*) for the specified package.
1✔
1417
# Download or build the package if necessary.
1✔
1418
function AconfNeedPackageFile() {
1✔
1419
        set -e
14✔
1420
        local package="$1"
14✔
1421

1✔
1422
        local info foreign
14✔
1423
        if info="$(LC_ALL=C "$PACMAN" --query --info "$package")"
42✔
1424
        then
1✔
1425
                if "$PACMAN" --query --quiet --foreign "$package" > /dev/null
11✔
1426
                then
1✔
1427
                        foreign=true
3✔
1428
                else
1✔
1429
                        foreign=false
9✔
1430
                fi
1✔
1431
        else
1✔
1432
                if info="$(LC_ALL=C "$PACMAN" --sync --info "$package")"
9✔
1433
                then
1✔
1434
                        foreign=false
1✔
1435
                else
1✔
1436
                        foreign=true
3✔
1437
                fi
1✔
1438
        fi
1✔
1439

1✔
1440
        local version='' architecture='' filemask_precise filemask_any
14✔
1441
        if [[ -n "$info" ]]
14✔
1442
        then
1✔
1443
                version="$(grep '^Version' <<< "$info" | sed 's/^.* : //g')"
33✔
1444
                architecture="$(grep '^Architecture' <<< "$info" | sed 's/^.* : //g')"
33✔
1445
                filemask_precise=$(printf "%q-%q-%q.pkg.*" "$package" "$version" "$architecture")
22✔
1446
        fi
1✔
1447
        filemask_any=$(printf "%q-*-*.pkg.*" "$package")
28✔
1448

1✔
1449
        # try without downloading first
1✔
1450
        local downloaded
14✔
1451
        for downloaded in false true
14✔
1452
        do
1✔
1453
                local precise
14✔
1454
                for precise in true false
17✔
1455
                do
1✔
1456
                        # if we don't have the exact version, we can only do non-precise
1✔
1457
                        if $precise && [[ -z "$version" ]]
31✔
1458
                        then
1✔
1459
                                continue
3✔
1460
                        fi
1✔
1461

1✔
1462
                        local filemask
14✔
1463
                        if $precise
14✔
1464
                        then
1✔
1465
                                filemask=$filemask_precise
11✔
1466
                        else
1✔
1467
                                filemask=$filemask_any
3✔
1468
                        fi
1✔
1469

1✔
1470
                        local dirs=()
28✔
1471
                        if $foreign
14✔
1472
                        then
1✔
1473
                                DetectAurHelper
6✔
1474
                                local -A tried_helper=()
12✔
1475

1✔
1476
                                local helper
6✔
1477
                                for helper in "$aur_helper" "${aur_helpers[@]}"
48✔
1478
                                do
1✔
1479
                                        if [[ ${tried_helper[$helper]+x} ]]
48✔
1480
                                        then
1✔
1481
                                                continue
6✔
1482
                                        fi
1✔
1483
                                        tried_helper[$helper]=y
42✔
1484

1✔
1485
                                        case "$helper" in
42✔
1486
                                                aurman)
1✔
1487
                                                        dirs+=("${XDG_CACHE_HOME:-$HOME/.cache}/aurman/$package")
6✔
1488
                                                        ;;
1✔
1489
                                                pacaur)
1✔
1490
                                                        dirs+=("${XDG_CACHE_HOME:-$HOME/.cache}/pacaur/$package")
6✔
1491
                                                        ;;
1✔
1492
                                                yaourt)
1✔
1493
                                                        # yaourt does not save .pkg.xz files
1✔
1494
                                                        ;;
1✔
1495
                                                yay)
1✔
1496
                                                        dirs+=("${XDG_CACHE_HOME:-$HOME/.cache}/yay/$package")
6✔
1497
                                                        ;;
1✔
1498
                                                paru)
1✔
1499
                                                        dirs+=("${XDG_CACHE_HOME:-$HOME/.cache}/paru/clone/$package")
6✔
1500
                                                        ;;
1✔
1501
                                                aura)
1✔
1502
                                                        dirs+=("${XDG_CACHE_HOME:-$HOME/.cache}/aura/cache")
6✔
1503
                                                        ;;
1✔
1504
                                                makepkg)
1✔
1505
                                                        dirs+=("$aur_dir"/"$package")
6✔
1506
                                                        ;;
1✔
1507
                                                *)
1✔
1508
                                                        Log 'Error: unknown AUR helper %q\n' "$aur_helper"
1✔
1509
                                                        false
1✔
1510
                                                        ;;
1✔
1511
                                        esac
1✔
1512
                                done
1✔
1513
                        else
1✔
1514
                                local dir
9✔
1515
                                ( LC_ALL=C pacman --verbose 2>/dev/null || true ) \
25✔
1516
                                        | sed -n 's/^Cache Dirs: \(.*\)$/\1/p' \
9✔
1517
                                        | sed 's/  /\n/g' \
9✔
1518
                                        | while read -r dir
25✔
1519
                                do
1✔
1520
                                        if [[ -n "$dir" ]]
17✔
1521
                                        then
1✔
1522
                                                dirs+=("$dir")
9✔
1523
                                        fi
1✔
1524
                                done
1✔
1525
                        fi
1✔
1526

1✔
1527
                        local files=()
28✔
1528
                        local dir
14✔
1529
                        for dir in "${dirs[@]}"
44✔
1530
                        do
1✔
1531
                                if sudo test -d "$dir"
44✔
1532
                                then
1✔
1533
                                        sudo find "$dir" -type f -name "$filemask" -not -name '*.sig' -print0 | \
14✔
1534
                                                while read -r -d $'\0' file
28✔
1535
                                                do
1✔
1536
                                                        files+=("$file")
14✔
1537
                                                done
1✔
1538
                                fi
1✔
1539
                        done
1✔
1540

1✔
1541
                        local file
14✔
1542
                        for file in "${files[@]}"
14✔
1543
                        do
1✔
1544
                                local correct
14✔
1545
                                if $precise
14✔
1546
                                then
1✔
1547
                                        correct=true
11✔
1548
                                else
1✔
1549
                                        local pkgname
3✔
1550
                                        pkgname=$(bsdtar -x --to-stdout --file "$file" .PKGINFO | \
1✔
1551
                                                                  sed -n 's/^pkgname = \(.*\)$/\1/p')
9✔
1552
                                        if [[ "$pkgname" == "$package" ]]
3✔
1553
                                        then
1✔
1554
                                                correct=true
3✔
1555
                                        else
1✔
1556
                                                correct=false
1✔
1557
                                        fi
1✔
1558
                                fi
1✔
1559

1✔
1560
                                if $correct
14✔
1561
                                then
1✔
1562
                                        printf '%s' "$file"
14✔
1563
                                        return
14✔
1564
                                fi
1✔
1565
                        done
1✔
1566
                done
1✔
1567

1✔
1568
                if $downloaded
1✔
1569
                then
1✔
1570
                        Log 'Unable to find package file for package %s!\n' "$(Color M %q "$package")"
1✔
1571
                        Exit 1
1✔
1572
                else
1✔
1573
                        if $foreign
1✔
1574
                        then
1✔
1575
                                LogEnter 'Building foreign package %s\n' "$(Color M %q "$package")"
1✔
1576
                                ParanoidConfirm ''
1✔
1577

1✔
1578
                                local helper
1✔
1579
                                for helper in "$aur_helper" "${aur_helpers[@]}"
1✔
1580
                                do
1✔
1581
                                        case "$helper" in
1✔
1582
                                                aurman)
1✔
1583
                                                        # aurman does not have a --makepkg option
1✔
1584
                                                        ;;
1✔
1585
                                                pacaur)
1✔
1586
                                                        if command -v "${pacaur_opts[0]}" > /dev/null
1✔
1587
                                                        then
1✔
1588
                                                                RunExternal "${pacaur_opts[@]}" --makepkg --aur --makepkg "$package" 1>&2
1✔
1589
                                                                break
1✔
1590
                                                        fi
1✔
1591
                                                        ;;
1✔
1592
                                                yaourt)
1✔
1593
                                                        # yaourt does not save .pkg.xz files
1✔
1594
                                                        continue
1✔
1595
                                                        ;;
1✔
1596
                                                yay)
1✔
1597
                                                        # yay does not have a --makepkg option
1✔
1598
                                                        continue
1✔
1599
                                                        ;;
1✔
1600
                                                paru)
1✔
1601
                                                        # paru does not have a --makepkg option
1✔
1602
                                                        continue
1✔
1603
                                                        ;;
1✔
1604
                                                aura)
1✔
1605
                                                        # aura does not have a --makepkg option
1✔
1606
                                                        continue
1✔
1607
                                                        ;;
1✔
1608
                                                makepkg)
1✔
1609
                                                        AconfMakePkg --noinstall "$package"
1✔
1610
                                                        break
1✔
1611
                                                        ;;
1✔
1612
                                                *)
1✔
1613
                                                        Log 'Error: unknown AUR helper %q\n' "$aur_helper"
1✔
1614
                                                        false
1✔
1615
                                                        ;;
1✔
1616
                                        esac
1✔
1617
                                done
1✔
1618

1✔
1619
                                LogLeave
1✔
1620
                        else
1✔
1621
                                LogEnter "Downloading package %s (%s) to pacman's cache\\n" "$(Color M %q "$package")" "$(Color C %s "$filemask_precise")"
1✔
1622
                                ParanoidConfirm ''
1✔
1623
                                sudo "$PACMAN" --sync --download --nodeps --nodeps --noconfirm "$package" 1>&2
1✔
1624
                                LogLeave
1✔
1625
                        fi
1✔
1626
                fi
1✔
1627
        done
1✔
1628
}
1✔
1629

1✔
1630
# Extract the original file from a package to stdout
1✔
1631
function AconfGetPackageOriginalFile() {
1✔
1632
        local package="$1" # Package to extract the file from
14✔
1633
        local file="$2" # Absolute path to file in package
14✔
1634

1✔
1635
        local package_file
14✔
1636
        package_file="$(AconfNeedPackageFile "$package")"
28✔
1637

1✔
1638
        local args=(bsdtar -x --to-stdout --file "$package_file" "${file/\//}")
28✔
1639
        if [[ -r "$package_file" ]]
14✔
1640
        then
6✔
1641
                "${args[@]}"
7✔
1642
        else
1✔
1643
                sudo "${args[@]}"
8✔
1644
        fi
1✔
1645
}
1✔
1646

1✔
1647
function AconfRestoreFile() {
1✔
1648
        local package=$1
1✔
1649
        local file=$2
1✔
1650

1✔
1651
        local package_file
1✔
1652
        package_file="$(AconfNeedPackageFile "$package")"
1✔
1653

1✔
1654
        # If we are restoring a directory, it may be non-empty.
1✔
1655
        # Extract the object to a temporary location first.
1✔
1656
        local tmp_base=${tmp_dir:?}/dir-props
1✔
1657
        sudo rm -rf "$tmp_base"
1✔
1658

1✔
1659
        mkdir -p "$tmp_base"
1✔
1660
        local tmp_file="$tmp_base""$file"
1✔
1661
        sudo tar x --directory "$tmp_base" --file "$package_file" --no-recursion "${file/\//}"
1✔
1662

1✔
1663
        AconfReplace "$tmp_file" "$file"
1✔
1664
        sudo rm -rf "$tmp_base"
1✔
1665
}
1✔
1666

1✔
1667
# Move filesystem object at $1 to $2, replacing any existing one.
1✔
1668
# Attempt to do so atomically, when possible.
1✔
1669
# Do the right thing when filesystem objects differ, but never
1✔
1670
# recursively remove directories (copy their attributes instead).
1✔
1671
function AconfReplace() {
1✔
1672
        local src=$1
1✔
1673
        local dst=$2
1✔
1674

1✔
1675
        # Try direct mv first
1✔
1676
        if ! sudo mv --no-target-directory "$src" "$dst" 2>/dev/null
1✔
1677
        then
1✔
1678
                # Direct mv failed - directory or object type mismatch
1✔
1679
                if sudo rm --force --dir "$dst" 2>/dev/null
1✔
1680
                then
1✔
1681
                        # Deleted target successfully, now overwrite it
1✔
1682
                        sudo mv --no-target-directory "$src" "$dst"
1✔
1683
                else
1✔
1684
                        # rm failed - likely a non-empty directory; copy
1✔
1685
                        # attributes only
1✔
1686
                        sudo chmod --reference="$src" "$dst"
1✔
1687
                        sudo chown --reference="$src" "$dst"
1✔
1688
                        sudo touch --reference="$src" "$dst"
1✔
1689
                fi
1✔
1690
        fi
1✔
1691
}
1✔
1692

1✔
1693
####################################################################################################
1✔
1694

1✔
1695
prompt_mode=normal # never / normal / paranoid
6,601✔
1696

1✔
1697
function Confirm() {
1✔
1698
        local detail_func="$1"
1✔
1699

1✔
1700
        if [[ $prompt_mode == never ]]
1✔
1701
        then
1✔
1702
                return
1✔
1703
        fi
1✔
1704

1✔
1705
        while true
1✔
1706
        do
1✔
1707
                if [[ -n "$detail_func" ]]
1✔
1708
                then
1✔
1709
                        Log 'Proceed? [Y/n/d] '
1✔
1710
                else
1✔
1711
                        Log 'Proceed? [Y/n] '
1✔
1712
                fi
1✔
1713
                read -r -n 1 answer < /dev/tty
1✔
1714
                echo 1>&2
1✔
1715
                case "$answer" in
1✔
1716
                        Y|y|'')
1✔
1717
                                return
1✔
1718
                                ;;
1✔
1719
                        N|n)
1✔
1720
                                Log '%s\n' "$(Color R "User abort")"
1✔
1721
                                Exit 1
1✔
1722
                                ;;
1✔
1723
                        D|d)
1✔
1724
                                $detail_func
1✔
1725
                                continue
1✔
1726
                                ;;
1✔
1727
                        *)
1✔
1728
                                continue
1✔
1729
                                ;;
1✔
1730
                esac
1✔
1731
        done
1✔
1732
}
1✔
1733

1✔
1734
function ParanoidConfirm() {
1✔
1735
        if [[ $prompt_mode == paranoid ]]
95✔
1736
        then
1✔
1737
                Confirm "$@"
95✔
1738
        fi
1✔
1739
}
1✔
1740

1✔
1741
####################################################################################################
1✔
1742

1✔
1743
log_indent=:
6,601✔
1744

1✔
1745
function Log() {
1✔
1746
        if [[ "$#" != 0 && -n "$1" ]]
84,642✔
1747
        then
1✔
1748
                local fmt="$1"
41,711✔
1749
                shift
41,680✔
1750

1✔
1751
                if [[ -z $ANSI_clear_line ]]
41,596✔
1752
                then
1✔
1753
                        # Replace carriage returns in format string with newline
1✔
1754
                        # when colors are disabled. This avoids systemd's journal
1✔
1755
                        # from showing such lines as [# blob data].
1✔
1756

1✔
1757
                        fmt=${fmt//\\r/\\n} # Replace the '\r' sequence
1✔
1758
                                            # (backslash-r) , not actual carriage
1✔
1759
                                            # returns.
1✔
1760
                fi
1✔
1761

1✔
1762
                printf "${ANSI_clear_line}${ANSI_color_B}%s ${ANSI_color_W}${fmt}${ANSI_reset}" "$log_indent" "$@" 1>&2
41,532✔
1763
        fi
1✔
1764
}
1✔
1765

1✔
1766
function LogEnter() {
1✔
1767
        Log "$@"
4,065✔
1768
        log_indent=$log_indent:
4,008✔
1769
}
1✔
1770

1✔
1771
function LogLeave() {
1✔
1772
        if [[ $# == 0 ]]
4,052✔
1773
        then
1✔
1774
                Log 'Done.\n'
2,540✔
1775
        else
1✔
1776
                Log "$@"
1,510✔
1777
        fi
1✔
1778

1✔
1779
        log_indent=${log_indent::-1}
4,053✔
1780
}
1✔
1781

1✔
1782
function ConfigWarning() {
1✔
1783
        Log '%s: '"$1" "$(Color Y "Warning")" "${@:2}"
11✔
1784
        printf W >> "$output_dir"/warnings
6✔
1785
}
1✔
1786

1✔
1787
function FatalError() {
1✔
1788
        Log "$@"
49✔
1789
        false
97✔
1790
        # if we're here, errexit is not set
1✔
1791
        Log 'Continuing after error. This is a bug, please report it.\n'
1✔
1792
        Exit 1
1✔
1793
}
1✔
1794

1✔
1795
function Color() {
1✔
1796
        local var="ANSI_color_$1"
36,694✔
1797
        printf -- "%s" "${!var}"
36,636✔
1798
        shift
36,660✔
1799
        # shellcheck disable=2059
1✔
1800
        printf -- "$@"
36,552✔
1801
        printf -- "%s" "${ANSI_color_W}"
36,512✔
1802
}
1✔
1803

1✔
1804
# The ANSI_color_* variables are looked up by name:
1✔
1805
# shellcheck disable=2034
1✔
1806
function DisableColor() {
1✔
1807
        ANSI_color_R=
1✔
1808
        ANSI_color_G=
1✔
1809
        ANSI_color_Y=
1✔
1810
        ANSI_color_B=
1✔
1811
        ANSI_color_M=
1✔
1812
        ANSI_color_C=
1✔
1813
        ANSI_color_W=
1✔
1814
        ANSI_reset=
1✔
1815
        ANSI_clear_line=
1✔
1816
}
1✔
1817

1✔
1818
####################################################################################################
1✔
1819

1✔
1820
# shellcheck disable=SC2329  # This function is invoked indirectly via trap
1✔
1821
function OnError() {
1✔
1822
        trap '' EXIT ERR
51✔
1823

1✔
1824
        LogEnter '%s! Stack trace:\n' "$(Color R "Fatal error")"
101✔
1825

1✔
1826
        local frame=0 str
51✔
1827
        # shellcheck disable=SC2086  # frame is a controlled integer, no risk of word splitting
1✔
1828
        while str=$(caller $frame)
397✔
1829
        do
1✔
1830
                if [[ $str =~ ^([^\ ]*)\ ([^\ ]*)\ (.*)$ ]]
149✔
1831
                then
1✔
1832
                        Log '%s:%s [%s]\n' "$(Color C "%q" "${BASH_REMATCH[3]}")" "$(Color G "%q" "${BASH_REMATCH[1]}")" "$(Color Y "%q" "${BASH_REMATCH[2]}")"
593✔
1833
                else
1✔
1834
                        Log '%s\n' "$str"
1✔
1835
                fi
1✔
1836

1✔
1837
                frame=$((frame+1))
149✔
1838
        done
1✔
1839

1✔
1840
        LogLeave ''
51✔
1841

1✔
1842
        if [[ -d "$tmp_dir" ]]
51✔
1843
        then
1✔
1844
                local df dir
51✔
1845
                df=$(($(stat -f --format="%a*%S" "$tmp_dir")))
101✔
1846
                if ! dir="$(realpath "$(dirname "$tmp_dir")" 2> /dev/null)"
151✔
1847
                then
1✔
1848
                        dir="$(dirname "$tmp_dir")"
1✔
1849
                fi
1✔
1850
                if [[ $df -lt $warn_tmp_df_threshold ]]
51✔
1851
                then
1✔
1852
                        LogEnter 'Probable cause: low disk space (%s bytes) in %s. Suggestions:\n' "$(Color G %s "$df")" "$(Color C %q "$dir")"
1✔
1853
                        Log '- Ignore more files and directories using %s directives;\n' "$(Color Y IgnorePath)"
1✔
1854
                        Log '- Free up more space in %s;\n' "$(Color C %q "$dir")"
1✔
1855
                        Log '- Set %s to another location before invoking %s.\n' "$(Color Y \$TMPDIR)" "$(Color Y aconfmgr)"
1✔
1856
                        LogLeave ''
1✔
1857
                fi
1✔
1858
        fi
1✔
1859

1✔
1860
        # Ensure complete abort when inside a string expansion
1✔
1861
        exit 1
51✔
1862
}
1✔
1863
trap OnError EXIT ERR
6,601✔
1864

1✔
1865
function Exit() {
1✔
1866
        trap '' EXIT ERR
6,551✔
1867
        exit "${1:-0}"
6,551✔
1868
}
1✔
1869

1✔
1870
####################################################################################################
1✔
1871

1✔
1872
# Print an array, one element per line (assuming IFS starts with \n).
1✔
1873
function PrintArray() {
1✔
1874
        local name="$1" # Name of the global variable containing the array
1,503✔
1875
        local size
1,503✔
1876

1✔
1877
        size="$(eval "echo \${#${name}""[*]}")"
4,509✔
1878
        if [[ $size != 0 ]]
1,503✔
1879
        then
1✔
1880
                eval "echo \"\${${name}[*]}\""
964✔
1881
        fi
1✔
1882
}
1✔
1883

1✔
1884
# Ditto, but terminate elements with a NUL.
1✔
1885
function Print0Array() {
1✔
1886
        local name="$1" # Name of the global variable containing the array
1,414✔
1887

1✔
1888
        eval "$(cat <<EOF
1,623✔
1889
        if [[ \${#${name}[*]} != 0 ]]
1,582✔
1890
        then
359✔
1891
                local item
3,663✔
1892
                for item in "\${${name}[@]}"
1,582✔
1893
                do
3,665✔
1894
                        printf '%s\\0' "\$item"
1,582✔
1895
                done
1,582✔
1896
        fi
1,582✔
1897
EOF
1,582✔
1898
)"
2,623✔
1899
}
1900

604✔
1901
# Ditto, but shell-escape array elements.
1,841✔
1902
# shellcheck disable=SC2329  # This is a utility function called indirectly
1903
function PrintQArray() {
1,840✔
1904
        local name="$1" # Name of the global variable containing the array
825✔
1905
        local size
825✔
1906

1907
        size="$(eval "echo \${#${name}""[*]}")"
2,475✔
1908
        if [[ $size != 0 ]]
825✔
1909
        then
1910
                eval "printf -- %q \"\${${name}[0]}\""
6✔
1911
                if [[ $size -gt 1 ]]
3✔
1912
                then
1913
                        eval "printf -- ' %q' \"\${${name}[@]:1}\""
2✔
1914
                fi
1915
        fi
1916
}
1917

1918
if [[ $EUID == 0 ]]
6,601✔
1919
then
1920
        function sudo() { "$@" ; }
1921
fi
1922

1923
# Run external bash script.
1924
# No-op, except when running under the test suite with bashcov,
1925
# in which case it does not propagate bashcov to the invoked script.
1926
# Unlike `env -i`, does not nuke the environment.
1927
function RunExternal() {
1928
        env -u SHELLOPTS -u PS4 -u SHLVL -u BASH_XTRACEFD "$@"
4✔
1929
}
1930

1931
# cat a file; if it's not readable, cat via sudo.
1932
# shellcheck disable=SC2329  # This is a utility function called indirectly
1933
function SuperCat() {
1934
        local file="$1"
1✔
1935

1936
        if [[ -r "$1" ]]
1✔
1937
        then
UNCOV
1938
                cat "$1"
×
1939
        else
1940
                sudo cat "$1"
1✔
1941
        fi
1942
}
1943

1944
if ! ( empty_array=() ; : "${empty_array[@]}" )
13,202✔
1945
then
1946
        # Old bash versions treat substitution of an empty array
1947
        # synonymous with substituting an unset variable, signaling an
1948
        # error in -u mode and stopping the script in -e mode. We
1949
        # generally want both of these enabled to catch bugs early and
1950
        # fail fast, but making every array substitution conditional on
1951
        # whether it is empty or not is unreasonably onerous, so just
1952
        # disable those checks in old bash versions - it is then up to the
1953
        # test suite ran against newer bash versions to ensure code
1954
        # correctness.
1955

1956
        Log '%s: Old bash detected, disabling unset variable checking.\n' "$(Color Y "Warning")"
×
1957
        set +u
×
1958
fi
1959

1960
: # include in coverage
6,601✔
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