1#!/usr/bin/env bash
2# SPDX-License-Identifier: LGPL-2.1-or-later
3set -e
4
5# Exclude following paths from the Coccinelle transformations
6EXCLUDED_PATHS=(
7    "src/boot/efi/*"
8    "src/shared/linux/*"
9    "src/basic/linux/*"
10    # Symlinked to test-bus-vtable-cc.cc, which causes issues with the IN_SET macro
11    "src/libsystemd/sd-bus/test-bus-vtable.c"
12    "src/libsystemd/sd-journal/lookup3.c"
13)
14
15TOP_DIR="$(git rev-parse --show-toplevel)"
16ARGS=()
17
18# Create an array from files tracked by git...
19mapfile -t FILES < <(git ls-files ':/*.[ch]')
20# ...and filter everything that matches patterns from EXCLUDED_PATHS
21for excl in "${EXCLUDED_PATHS[@]}"; do
22    # shellcheck disable=SC2206
23    FILES=(${FILES[@]//$excl})
24done
25
26case "$1" in
27    -i)
28        ARGS+=(--in-place)
29        shift
30        ;;
31esac
32
33if ! parallel -h >/dev/null; then
34    echo 'Please install GNU parallel (package "parallel")'
35    exit 1
36fi
37
38[[ ${#@} -ne 0 ]] && SCRIPTS=("$@") || SCRIPTS=("$TOP_DIR"/coccinelle/*.cocci)
39
40for script in "${SCRIPTS[@]}"; do
41    echo "--x-- Processing $script --x--"
42    TMPFILE="$(mktemp)"
43    echo "+ spatch --sp-file $script ${ARGS[*]} ..."
44    parallel --halt now,fail=1 --keep-order --noswap --max-args=20 \
45             spatch --macro-file="$TOP_DIR/coccinelle/macros.h" --sp-file "$script" "${ARGS[@]}" ::: "${FILES[@]}" \
46             2>"$TMPFILE" || cat "$TMPFILE"
47    echo -e "--x-- Processed $script --x--\n"
48done
49