5

How can I create a directory on Ruby via SFTP only when the directory doesn't exist?

I have the following code right now:

Net::SFTP.start( ip, id, :password => pass, :port=> port ) do |sftp|
    sftp.mkdir! remotePath
    sftp.upload!(localPath + localfile, remotePath + remotefile)
end

I have no problem creating the directory the first time but it tries to recreate the same directory even if it already exists and it throws me an error.

Anyone who knows how to do this?

In using fileutils, there is this code like:

 FileUtils.mkdir_p(remotePath) unless File.exists?(remotePath)

Is there any way I could do the same over SFTP?

Martin Prikryl
  • 147,050
  • 42
  • 335
  • 704
Laurice Llona
  • 87
  • 1
  • 8
  • I forgot to mention, and I just noticed that whenever I upload a file using the above code, it only uploads a 1kb file which means it isn't working properly. – Laurice Llona May 22 '15 at 05:43
  • Everything is working well now!! Thank you so much :) Wish I could upvote already! – Laurice Llona May 22 '15 at 07:34

1 Answers1

8

In this case, it may be better to simply "ask for forgiveness", then to "ask for permission". It also eliminates a race condition, where you check if the directory exists, discover it doesn't, and then while creating it you error out because it was created by someone else in the meantime.

The following code will work better:

Net::SFTP.start( ip, id, :password => pass, :port=> port ) do |sftp|
    begin
        sftp.mkdir! remotePath
    rescue Net::SFTP::StatusException => e
        # verify if this returns 11. Your server may return
        # something different like 4.
        if e.code == 11
            # directory already exists. Carry on..
        else 
            raise
        end 
    end
    sftp.upload!(localPath + localfile, remotePath + remotefile)
end
Martin Konecny
  • 50,691
  • 18
  • 119
  • 145