Repository navigation
Expand file tree
/
Copy pathstrip-marker-sections
More file actions
executable file
·94 lines (83 loc) · 2.31 KB
/
Copy pathstrip-marker-sections
File metadata and controls
executable file
·94 lines (83 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/bin/bash
#
# Strips TinyPilot marker sections from a file.
#
# If the target file contains marker sections, this script removes the markers
# and any content in between them.
# If the target file doesn’t contain marker sections, running this script is a
# noop.
# If the target file contains unmatched/orphaned markers, this script fails.
# We don’t use `set -x`, because it would output every single iteration of the
# while loop when iterating through the lines of the target file, and hence
# generate a lot of noise.
# Exit on first failure.
set -e
# Exit on unset variable.
set -u
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
readonly SCRIPT_DIR
# shellcheck source=lib/markers.sh
. "${SCRIPT_DIR}/lib/markers.sh"
print_help() {
cat << EOF
Usage: ${0##*/} [--help] TARGET_FILE
Strips TinyPilot marker sections from a file.
TARGET_FILE Path to file with marker sections.
--help Display this help and exit.
EOF
}
# Parse command-line arguments.
TARGET_FILE=''
while (( "$#" > 0 )); do
case "$1" in
--help)
print_help
exit
;;
-*)
echo "Illegal option: $1" >&2
exit 1
;;
*)
TARGET_FILE="$1"
shift
;;
esac
done
readonly TARGET_FILE
# Ensure target file is specified.
if [[ -z "${TARGET_FILE}" ]]; then
echo 'Input parameter missing: TARGET_FILE' >&2
exit 1
fi
# Ensure target file exists and is a file.
if [[ ! -f "${TARGET_FILE}" ]]; then
echo "Not a file: ${TARGET_FILE}" >&2
exit 1
fi
# Read the original file line by line, and remove marker sections.
# This is done by iterating through the lines, and filtering out lines that are
# either markers themselves, or in between markers.
preserved_lines=()
is_in_marker_section='false'
while IFS='' read -r line; do
if [[ "${line}" == "${MARKER_END}" ]]; then
if ! "${is_in_marker_section}"; then
echo 'Unmatched end marker' >&2
exit 1
fi
is_in_marker_section='false'
continue
fi
if "${is_in_marker_section}" || [[ "${line}" == "${MARKER_START}" ]]; then
is_in_marker_section='true'
continue
fi
preserved_lines+=("${line}")
done < "${TARGET_FILE}"
if "${is_in_marker_section}"; then
echo 'Unmatched start marker' >&2
exit 1
fi
# Populate preserved lines to file.
printf "%s\n" "${preserved_lines[@]}" > "${TARGET_FILE}"