Search code examples
rubyerror-handlingversion-controlmercurial

How to handle incorrect git/hg clone command in ruby


Is there a way to handle trying to clone a repo that does not exist gracefully? In ruby, I can clone a repo like this:

system("hg clone https://username@bitbucket.org/username/repoThatDoesNotExist")

If the repo can be found, then it works fine. If it cannot, this error message pops up:

abort: HTTP Error 404: Not Found

Is there a way to handle these messages and continue on within the script instead of exiting? I've tried checking error codes and raising exceptions, but it still does not want to continue on with the rest.

Basically, I just want to be able to check if the repo that is trying to be cloned exists without exiting the script.

Thanks for the help.


Solution

  • You can use Open3#capture3 which gives you the status of the command, invoking success? then you can check if it threw an error or was successful.

    require 'open3'
    
    ERROR_MESSAGE = 'abort: HTTP Error 404: Not Found'.freeze
    
    def clone_repo(repo)
      _, _, status = Open3.capture3("hg clone #{repo}")
    
      return ERROR_MESSAGE unless status.success?
    end
    
    p clone_repo('https://username@bitbucket.org/username/repoThatDoesNotExist')