file: fix diname behavior when result is "/"
authorJean Privat <jean@pryen.org>
Tue, 3 Sep 2013 15:40:07 +0000 (11:40 -0400)
committerJean Privat <jean@pryen.org>
Tue, 3 Sep 2013 18:10:39 +0000 (14:10 -0400)
Signed-off-by: Jean Privat <jean@pryen.org>

lib/standard/file.nit

index 764ca75..a6b1aef 100644 (file)
@@ -224,11 +224,24 @@ redef class String
        end
 
        # Extract the dirname of a path
+       #
+       #     assert "/path/to/a_file.ext".dirname         == "/path/to"
+       #     assert "path/to/a_file.ext".dirname          == "path/to"
+       #     assert "path/to".dirname                     == "path"
+       #     assert "path/to/".dirname                    == "path"
+       #     assert "path".dirname                        == "."
+       #     assert "/path".dirname                       == "/"
+       #     assert "/".dirname                           == "/"
+       #     assert "".dirname                            == "."
        fun dirname: String
        do
-               var pos = last_index_of_from('/', _length - 1)
-               if pos >= 0 then
+               var l = _length - 1 # Index of the last char
+               if l > 0 and self[l] == '/' then l -= 1 # remove trailing `/`
+               var pos = last_index_of_from('/', l)
+               if pos > 0 then
                        return substring(0, pos)
+               else if pos == 0 then
+                       return "/"
                else
                        return "."
                end