feat: optimize truncate algorithm

This commit is contained in:
Abhishek Keshri 2024-11-04 00:30:04 +05:30
parent 8aa4af617f
commit cde2291466
No known key found for this signature in database

View file

@ -14,38 +14,30 @@ get_pane_dir() {
# truncate the path if it's longer than 30 characters # truncate the path if it's longer than 30 characters
truncate_path() { truncate_path() {
local path="$1" local path="$1" limit=20 truncated_path=""
local limit=30
if [ ${#path} -gt $limit ]; then # If path is greater than limit, then truncate parts to 2 characters
# Split the path into an array by '/' [[ ${#path} -le $limit ]] && echo "$path" && return
IFS='/' read -r -a path_array <<<"$path" IFS='/' read -ra parts <<< "$path"
truncated_path="" for ((i=0; i<${#parts[@]}-1; i++)); do
truncated_path+="${parts[i]:0:2}/"
for ((i = 0; i < ${#path_array[@]} - 1; i++)); do
if [ ${#path_array[i]} -gt 1 ]; then
truncated_path+="${path_array[i]:0:2}/"
else
truncated_path+="${path_array[i]}/"
fi
done done
truncated_path+="${parts[-1]}"
# Add the last component of the current directory path # If there are more than 4 slashes, then we will truncate the middle part
truncated_path+="${path_array[-1]}" if [[ $(tr -cd '/' <<< "$truncated_path" | wc -c) -gt 4 ]]; then
IFS='/' read -ra parts <<< "$truncated_path"
echo "$truncated_path" echo "${parts[0]}/${parts[1]}/.../${parts[-2]}/${parts[-1]}"
else else
echo "$path" echo "$truncated_path"
fi fi
} }
main() { main() {
path=$(get_pane_dir) path=$(get_pane_dir)
# change '/home/user' to '~' # Change '/home/user' to '~'
cwd="${path/"$HOME"/'~'}" cwd="${path/"$HOME"/'~'}"
# Truncate path if it's too long
truncated_cwd=$(truncate_path "$cwd") truncated_cwd=$(truncate_path "$cwd")
echo "$truncated_cwd" echo "$truncated_cwd"