我有一个执行rake命令的ruby脚本(Guardfile)。

guard :shell do

  watch(%r{^manifests\/.+\.pp$}) do |m|
    spec = `rake spec`
    retval = $?.to_i
    case retval
    when 0
       if spec.length > 0 then
          puts spec
          n "#{m[0]} Tests Failed!", 'Rake Spec', :pending
       else
          puts spec
          n "#{m[0]} Tests Passed!", 'Rake Spec', :pending

       end
    end
end

当我从命令行运行“rake spec”时,输出将变为彩色。
我怎样才能使ruby脚本的输出也被着色?

从命令行:

从 ruby 脚本:

更新

我可以通过使用script来解决该问题

bash command preserve color when piping
spec = `script -q /dev/null rake spec`

这仍然具有不能实时滚动文本的缺点。尽管它确实保留了颜色,但直到最后都不会输出任何内容。

有没有更本地化的方法可以进行滚动显示?

最佳答案

首先,rake spec --color不起作用,因为您要将--color传递给rake,而不是rspec

杰伊·米切尔(Jay Mitchell)关于颜色的建议应该可以起作用-将其放入.rspec文件中:

--color

至于“实时”输出,guard-shell为此具有一个eager命令:

https://github.com/guard/guard-shell/blob/master/lib/guard/shell.rb#L37-L51

不幸的是,guard-shell有两个重要的缺点:
  • 它不能让您访问退出代码
  • 不能正确报告Guard中的失败(这会导致其他任务运行)

    因此,Guard::Shell的eager方法对我们的需求毫无用处。

    而是,以下应该工作:
    # a version of Guard::Shell's 'eager()' which returns the result
    class InPty
      require 'pty'
    
      def self.run(command)
        PTY.spawn(command) do |r, w, pid|
          begin
            $stdout.puts
            r.each {|line| $stdout.print line }
          rescue Errno::EIO
          end
          Process.wait(pid)
        end
    
        $?.success?
      rescue PTY::ChildExited
      end
    end
    
    # A hack so that Guard::Shell properly throws :task_has_failed
    class ProperGuardPluginFailure
      def to_s
        throw :task_has_failed
      end
    end
    
    guard :shell, any_return: true do
      watch(%r{^manifests\/.+\.pp$}) do |m|
        ok = InPty.run('rake spec')
        status, type = ok ? ['Passed', :success] : ['Failed', :failed]
        n "#{m[0]} Tests #{status}!", 'Rake Spec', type
        ok ? nil : ProperGuardPluginFailure.new
      end
    end
    

    上面看起来很适合新的Guard插件-好主意吗?

    关于Ruby-使用彩色输出进行打印,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26047070/

  • 10-12 23:04