How can you check if a file exists (on a remote server) in Capistrano?

Like so many others I saw on Googleverse, I fell prey to the File.exists? trap File.exists? , which, of course, checks your local file system, and not the server you are deploying to.

I found one result that used shell hacking, for example:

 if [[ -d #{shared_path}/images ]]; then ... 

but this is not very good with me, unless it was well wrapped in the Ruby method.

Has anyone decided this is elegant?

+41
ruby file exists capistrano
Nov 02 '09 at 14:23
source share
5 answers

@knocte is correct that capture is problematic because usually everyone is focused on deploying to more than one host (and capture gets only the first result). To check all hosts, you will need to use invoke_command (this is what capture uses internally). Here is an example where I check that the file exists on all mapped servers:

 def remote_file_exists?(path) results = [] invoke_command("if [ -e '#{path}' ]; then echo -n 'true'; fi") do |ch, stream, out| results << (out == 'true') end results.all? end 

Please note that invoke_command uses run by default - check the parameters that you can pass for more control.

+48
Mar 15 '13 at 15:28
source share
β€” -

In capistrano 3 you can:

 on roles(:all) do if test("[ -f /path/to/my/file ]") # the file exists else # the file does not exist end end 

This is good because it returns the result of the remote test back to the local ruby ​​program, and you can work in simpler shell commands.

+55
Jan 02 '14 at 4:28
source share

Inspired by @bhups answer with tests:

 def remote_file_exists?(full_path) 'true' == capture("if [ -e #{full_path} ]; then echo 'true'; fi").strip end namespace :remote do namespace :file do desc "test existence of missing file" task :missing do if remote_file_exists?('/dev/mull') raise "It there!?" end end desc "test existence of present file" task :exists do unless remote_file_exists?('/dev/null') raise "It missing!?" end end end end 
+24
Nov 02 '09 at 15:36
source share

Perhaps you want to:

 isFileExist = 'if [ -d #{dir_path} ]; then echo "yes"; else echo "no"; fi'.strip puts "File exist" if isFileExist == "yes" 
+5
Nov 02 '09 at 14:36
source share

I did this before using the run command in capistrano (which executes the shell command on the remote server)

For example, here is one capistrano task that checks for the presence of a .yml database in the shared / configs directory and links it if it exists.

  desc "link shared database.yml" task :link_shared_database_config do run "test -f #{shared_path}/configs/database.yml && ln -sf #{shared_path}/configs/database.yml #{current_path}/config/database.yml || echo 'no database.yml in shared/configs'" end 
+4
Nov 02 '09 at 22:20
source share



All Articles