JRUBY-1672: File.rename behavior is different from Ruby

Author: Vladimir Sizikov <vsizikov@gmail.com>

NOTE: apply this patch with 'patch -p1'
---

 src/org/jruby/RubyFile.java |   27 ++++++++++++++++++++++++---
 1 files changed, 24 insertions(+), 3 deletions(-)

diff --git a/src/org/jruby/RubyFile.java b/src/org/jruby/RubyFile.java
index e87cf6d..860057f 100644
--- a/src/org/jruby/RubyFile.java
+++ b/src/org/jruby/RubyFile.java
@@ -1096,9 +1096,30 @@ public class RubyFile extends RubyIO {
         if (!oldFile.exists() || !newFile.getParentFile().exists()) {
             throw runtime.newErrnoENOENTError("No such file or directory - " + oldNameString + " or " + newNameString);
         }
-        oldFile.renameTo(JRubyFile.create(runtime.getCurrentDirectory(), newNameString.toString()));
-        
-        return RubyFixnum.zero(runtime);
+
+        JRubyFile dest = JRubyFile.create(
+                runtime.getCurrentDirectory(), newNameString.toString());
+
+        if (oldFile.renameTo(dest)) {
+            // rename is successful
+            return RubyFixnum.zero(runtime);
+        }
+
+        // rename via Java API call wasn't successful,
+        // let's try some tricks, similar to what MRI does
+
+        if (newFile.exists()) {
+            recv.getRuntime().getPosix().chmod(newNameString.toString(), 0666);
+            newFile.delete();
+        }
+
+        // try to rename one more time
+        if (oldFile.renameTo(dest)) {
+            return RubyFixnum.zero(runtime);
+        }
+
+        throw runtime.newErrnoEACCESError("Permission denied - "
+                + oldNameString + " or " + newNameString);
     }
     
     @JRubyMethod(required = 1, meta = true)

