From 5e5e489d850eb167cd6a741d5ca9193f9a882d13 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Wed, 28 Dec 2022 14:13:23 -0500 Subject: [PATCH] bashrc: Add utility function to clamp maximum length of file name This is useful when synchronizing to an Rclone encrypted remote --- bash/.bashrc | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/bash/.bashrc b/bash/.bashrc index 1a5afff..2cb0a75 100644 --- a/bash/.bashrc +++ b/bash/.bashrc @@ -124,3 +124,36 @@ export QT_IM_MODULE=fcitx export SDL_IM_MODULE=fcitx export WLR_XWAYLAND=$HOME/.local/bin/Xwayland-noshm $MACHINE_START_SWAY && [[ -z "$DISPLAY" && $(tty) == /dev/tty1 ]] && exec sway + +# Miscellaneous utilities +function clamp_filename() { + [[ -z "$1" ]] && return 1 + + local len="$1" + + for file in *; do + local filename_len=$(echo "$file" | wc -c) + + if [ $filename_len -gt $len ]; then + local extension="${file##*.}" + local filename="${filename%.*}" + if [ ${#extension} -gt 5 ]; then + filename="$file" + extension="" + fi + local clamped_filename="$(echo "$file" | cut -c1-$((len - ${#extension})) | iconv -f utf8 -t utf8 -c -)" + if [ ${#extension} -gt 0 ]; then + clamped_filename="$clamped_filename.$extension" + fi + echo "File '$PWD/$file' clamped to '$PWD/$clamped_filename'" + mv "$file" "$clamped_filename" + file="$clamped_filename" + fi + + if [ -d "$file" ]; then + pushd "$file" > /dev/null + clamp_filename "$1" + popd > /dev/null + fi + done +}