Search code examples
ruby-on-railsrubydirectorysftpfileutils

Creating directory over SFTP on Ruby fails if directory exists already


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?


Solution

  • 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