]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
Rename: fix empty 'from' with / in filename.
authorPhilip Hazelden <philip.hazelden@gmail.com>
Sun, 3 Jul 2022 21:46:16 +0000 (22:46 +0100)
committerPhilip Hazelden <philip.hazelden@gmail.com>
Sun, 3 Jul 2022 21:59:28 +0000 (22:59 +0100)
Previously, if we did e.g.

    rename '' _ ./foo.txt

it would try to rename to ._/foo.txt, because `string_replace` was
passed `s="/foo.txt"` and `from` would match at the front. Now we pass
`s="foo.txt"`.

This doesn't affect the case when `to` contains a slash. In that
situation we'll still place `to` at the very beginning of the path, e.g.

    rename '' _/ ./foo.txt # rename to _/./foo.txt
    rename '' /_ ./foo.txt # rename to /_./foo.txt

misc-utils/rename.c
tests/expected/rename/subdir
tests/ts/rename/subdir

index 9979ab15239c7929255624c2d427107cef658a40..e47359c0d953c4195bff88b6fe86c2cf03465bda 100644 (file)
@@ -203,8 +203,13 @@ static int do_file(char *from, char *to, char *s, int verbose, int noact,
                warn(_("stat of %s failed"), s);
                return 2;
        }
-       if (strchr(from, '/') == NULL && strchr(to, '/') == NULL)
+       if (strchr(from, '/') == NULL && strchr(to, '/') == NULL) {
                file = strrchr(s, '/');
+                /* We're going to search for `from` in `file`. If `from` is
+                   empty, we don't want it to match before the '/'. */
+               if (file != NULL)
+                       file++;
+       }
        if (file == NULL)
                file = s;
        if (string_replace(from, to, file, s, &newname) != 0)
index f42960276256b585f63a9c5a486b492eed564094..684cdb8fa842d4ba7006de14613c8a6bb1dceb54 100644 (file)
@@ -27,3 +27,8 @@ renxme/aa
 rename_path_a
 rename_path_b
 rename_path_b/test2
+== empty 'from' ==
+`rename_test' -> `_rename_test'
+`./rename_test' -> `./_rename_test'
+`rename_test' -> `rename_subdir/rename_test'
+`./rename_test' -> `rename_subdir/./rename_test'
index 192c2ff051affa431be22d39435817a76e1f00b0..f6bd7587567655971b33cd2f959fa93b35548b70 100755 (executable)
@@ -65,4 +65,24 @@ rm -f rename_path_a/test2 rename_path_b/test2
 
 rmdir rename_path_a rename_path_b
 
+echo "== empty 'from' ==" >> $TS_OUTPUT
+
+touch rename_test
+$TS_CMD_RENAME -v '' _ rename_test >> $TS_OUTPUT 2>> $TS_ERRLOG
+rm -f *rename_test
+
+touch rename_test
+$TS_CMD_RENAME -v '' _ ./rename_test >> $TS_OUTPUT 2>> $TS_ERRLOG
+rm -f *rename_test
+
+touch rename_test
+mkdir rename_subdir
+$TS_CMD_RENAME -v '' rename_subdir/ rename_test >> $TS_OUTPUT 2>> $TS_ERRLOG
+rm -rf rename_subdir
+
+touch rename_test
+mkdir rename_subdir
+$TS_CMD_RENAME -v '' rename_subdir/ ./rename_test >> $TS_OUTPUT 2>> $TS_ERRLOG
+rm -rf rename_subdir
+
 ts_finalize