From 9485b1c59d1f4858f869ea18ff120f1ab1fab2ba Mon Sep 17 00:00:00 2001 From: jowi Date: Mon, 7 Oct 2024 11:07:04 -0400 Subject: [PATCH] feat(organize): create organize with copy --- bin/dirclean.sh | 2 +- lib/actions.sh | 49 +++++++++++++++++++++++++++++++++++++++---------- 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/bin/dirclean.sh b/bin/dirclean.sh index 4f825e8..81c057c 100755 --- a/bin/dirclean.sh +++ b/bin/dirclean.sh @@ -35,7 +35,7 @@ function main() { # Organize if [[ $dry_run == false ]]; then - organize _mapping "$log" + organize _mapping "$log" "$directory" else echo "Because this was a dry run, no modifications were completed." fi diff --git a/lib/actions.sh b/lib/actions.sh index b737f27..45039ac 100644 --- a/lib/actions.sh +++ b/lib/actions.sh @@ -8,24 +8,34 @@ LOG_DIR=logs # Create a mapping of current file & directory positions, and their new position. function create_mapping() { declare -n mapping="$1" + declare -A ext_mapping cd "$2" || exit 1; files=$(ls) + while IFS=":" read -r key value; do + key_lowercase="${key,,}" + ext_mapping[$key_lowercase]=$value + done < ./config/ext_mapping.txt + while IFS= read -r line; do if [[ -f "$line" ]]; then - # extension="${line##*.}" + extension="${line##*.}" - mapping["$line"]="someDir/$line" #TODO: define a new directory based on extension + if [[ -z "${ext_mapping[$extension]}" ]]; then + mapping["$line"]="Others/$line" + else + mapping["$line"]="${ext_mapping[$extension]}/$line" + fi - # echo "$line -> ${mapping[$line]}" + echo "$line -> ${mapping[$line]}" elif [[ -d "$line" ]]; then - mapping["$line"]="directories/$line" - - # echo "$line -> ${mapping[$line]}" + mapping["$line"]="Directories/$line" + echo "$line -> ${mapping[$line]}" + else print_invalid_file_or_dir "$line" ; exit 1 fi @@ -38,13 +48,32 @@ function organize() { current_datetime=$(date +"%Y-%m-%d-%H:%M:%S") - echo "Organizing..." + echo "Difference" + echo "----------" - if [[ "$2" == true && ! -d $LOG_DIR ]]; then - mkdir $LOG_DIR + if [[ "$2" == true ]]; then + mkdir -p $LOG_DIR fi for key in "${!mapping[@]}"; do - echo "$key -> ${mapping[$key]}" | tee -a "$LOG_DIR/$current_datetime.log" + file_output="$key -> ${mapping[$key]}" + if [[ "$2" == true ]]; then + echo "$file_output" | tee -a "$LOG_DIR/$current_datetime.log" + else + echo "$file_output" + fi + done + + for key in "${!mapping[@]}"; do + target_path="${mapping[$key]}" + target_dir=$(dirname "$target_path") + + mkdir -p "$target_dir" + + if [[ -f "$key" || -d "$key" ]]; then + cp -r "$key" "$target_dir" + else + echo "File '$key' does not exist -> Skipping" + fi done }