49d34d00cdaf132f318700398bf42120ff1af8e7

Author
Marc Cornellà <hello@mcornella.com>
Committer
Marc Cornellà <hello@mcornella.com>
Date

Message

fix(extract): fix conflict if compressed file has a folder of the same name

This change fixes the case where the compressed file (e.g. tools.tgz) only
contains a folder with the same name (e.g. tools) in its root folder.

tools.tgz:
|- tools
   |- fileA.txt
   |- fileB.txt
   \- fileC.txt

In that case, the "smart" folder creation mechanism will extract the files in
a folder "tools", and this extraction folder will contain a single folder with
the same name.

Before this fix, the tool would try to move out the inside folder to the parent
one, but there would already be a folder named "tools", so it would generate a
conflict.

This change first renames the inside folder to a random string, and only then
it is moved outside and the old extraction folder is deleted.

Diff

 1diff --git a/plugins/extract/extract.plugin.zsh b/plugins/extract/extract.plugin.zsh
 2index 40e67575f813ea1a3561bb4e1fcc087504b5596f..34c0806537589d075f868f814b12f6d49e21f67d 100644
 3--- a/plugins/extract/extract.plugin.zsh
 4+++ b/plugins/extract/extract.plugin.zsh
 5@@ -98,8 +98,22 @@ EOF
 6     local -a content
 7     content=("${extract_dir}"/*(DNY2))
 8     if [[ ${#content} -eq 1 && -d "${content[1]}" ]]; then
 9-      command mv -f "${content[1]}" .
10-      command rmdir "$extract_dir"
11+      # The extracted folder (${content[1]}) may have the same name as $extract_dir
12+      # If so, we need to rename it to avoid conflicts in a 3-step process
13+      #
14+      # 1. Move and rename the extracted folder to a temporary random name
15+      # 2. Delete the empty folder
16+      # 3. Rename the extracted folder to the original name
17+      if [[ "${content[1]:t}" == "$extract_dir" ]]; then
18+        # =(:) gives /tmp/zsh<random>, with :t it gives zsh<random>
19+        local tmp_dir==(:); tmp_dir="${tmp_dir:t}"
20+        command mv -f "${content[1]}" "$tmp_dir" \
21+        && command rmdir "$extract_dir" \
22+        && command mv -f "$tmp_dir" "$extract_dir"
23+      else
24+        command mv -f "${content[1]}" . \
25+        && command rmdir "$extract_dir"
26+      fi
27     elif [[ ${#content} -eq 0 ]]; then
28       command rmdir "$extract_dir"
29     fi