如何检查Capistrano中是否存在文件(在远程服务器上)?

Tef*_*Ted 41 ruby capistrano file exists

像我在Googleverse中看到的许多其他人一样,我成了File.exists?陷阱的受害者,陷阱当然会检查您的本地文件系统,而不是您正在部署的服务器.

我找到了一个使用shell hack的结果:

if [[ -d #{shared_path}/images ]]; then ...
Run Code Online (Sandbox Code Playgroud)

但这并不适合我,除非它在Ruby方法中很好地包装.

谁有人优雅地解决了这个问题?

Mat*_*lly 58

In capistrano 3, you can do:

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

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

  • 马特,你能链接到`test`的文档吗?这是一个难以搜寻的词.谢谢! (2认同)
  • 常见问题示例:http://capistranorb.com/documentation/faq/how-can-i-check-for-existing-remote-file/ (2认同)

Pat*_*gan 48

@knocte是正确的,capture因为通常每个人都将部署目标定位到多个主机(并且捕获只获取第一个主机的输出).为了检查所有主机,您需要使用invoke_command(这是capture内部使用的).这是一个示例,我检查以确保所有匹配的服务器上存在一个文件:

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
Run Code Online (Sandbox Code Playgroud)

请注意默认情况下invoke_command使用run- 查看可以传递选项以获得更多控制权.

  • 在我看来,你应该在`else`案例中做`echo -n'false';` (4认同)

Tef*_*Ted 22

受@bhups响应启发,测试:

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's there!?"
      end
    end

    desc "test existence of present file"
    task :exists do
      unless remote_file_exists?('/dev/null')
        raise "It's missing!?"
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 人!capture()函数只从第一台服务器检索数据,所以请不要以此为基础的任何逻辑!! capistrano是多服务器 (6认同)

bhu*_*ups 5

可能你想做的是:

isFileExist = 'if [ -d #{dir_path} ]; then echo "yes"; else echo "no"; fi'.strip
puts "File exist" if isFileExist == "yes"
Run Code Online (Sandbox Code Playgroud)