Skip to content

Commit e4e43ec

Browse files
committed
feat: 🐛 improve error handling and validation to cli-tips.sh
* **Error Handling** - Add `error` function to display error messages and exit. - Replace existing error messages with calls to `error` function. - Add checks for `TIPS_FOLDER` existence and provide error message if it does not exist. - Add error handling for `mapfile` and `grep` commands. * **Validation** - Validate that the specified language file exists and provide error message if it does not.
1 parent 862eaf0 commit e4e43ec

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

cli-tips.sh

100755100644
+20-13
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ SYSTEM_LANGUAGE="$(echo "$LANG" | cut -d'_' -f1)"
2424
# Default language is based on the user's environment
2525
LANGUAGE="${TIPS_LANGUAGE:-$SYSTEM_LANGUAGE}"
2626

27+
error() {
28+
echo "ERROR: $1"
29+
exit 1
30+
}
31+
2732
show_help() {
2833
echo -e "\e[1mUsage:\e[0m $(basename "$0") \e[1;34m[flags]\e[0m \e[1;32m[options]\e[0m"
2934
echo
@@ -52,8 +57,7 @@ while [[ "$#" -gt 0 ]]; do
5257
case $1 in
5358
-l | --language | --lang)
5459
if [[ -z "$2" ]]; then
55-
echo "Error: No language specified"
56-
exit 1
60+
error "No language specified"
5761
fi
5862
LANGUAGE="$2"
5963
shift
@@ -63,8 +67,7 @@ while [[ "$#" -gt 0 ]]; do
6367
;;
6468
--about)
6569
if [[ -z "$2" ]]; then
66-
echo "Error: No keyword specified"
67-
exit 1
70+
error "No keyword specified"
6871
fi
6972
KEYWORD="$2"
7073
shift
@@ -74,31 +77,35 @@ while [[ "$#" -gt 0 ]]; do
7477
exit 0
7578
;;
7679
*)
77-
echo "Unknown option: $1"
78-
exit 1
80+
error "Unknown option: $1"
7981
;;
8082
esac
8183
shift
8284
done
8385

86+
# Check if the TIPS_FOLDER directory exists
87+
if [ ! -d "$TIPS_FOLDER" ]; then
88+
error "Tips folder '$TIPS_FOLDER' does not exist."
89+
fi
90+
8491
# Find the localized tips file
8592
if [ -f "$TIPS_FOLDER/${LANGUAGE}.txt" ]; then
8693
localized_file="$TIPS_FOLDER/${LANGUAGE}.txt"
8794
else
95+
echo "Language file '$TIPS_FOLDER/${LANGUAGE}.txt' does not exist. Using default language 'en'."
8896
localized_file="$TIPS_FOLDER/en.txt"
8997
fi
9098

9199
# Read tips from the file into an array
92-
mapfile -t tips <"$localized_file"
100+
if ! mapfile -t tips <"$localized_file"; then
101+
error "Failed to read tips from file '$localized_file'."
102+
fi
93103

94104
# Filter tips based on the specified keyword
95105
if [ -n "$KEYWORD" ]; then
96-
filtered_tips=()
97-
for tip in "${tips[@]}"; do
98-
if [[ "$tip" =~ $KEYWORD ]]; then
99-
filtered_tips+=("$tip")
100-
fi
101-
done
106+
if ! filtered_tips=$(grep -i "$KEYWORD" <<<"${tips[@]}"); then
107+
error "Failed to filter tips with keyword '$KEYWORD'."
108+
fi
102109
tips=("${filtered_tips[@]}")
103110
fi
104111

0 commit comments

Comments
 (0)