Improved Guard Setup for Swift

Episode #246 | 7 minutes | published on 12/01/2016 | Uses guard-2.14, swift-3.0
Subscribers Only
In the last episode we showed how to run Swift tests automatically with guard, but it wasn't an ideal setup. We couldn't see compiler errors, nor could we see any output from our program using print. In this episode we leverage Ruby's open3 library to capture stdout and stderr so we can output it to the terminal in the appropriate colors.

Episode Links

require 'colored'
require 'open3'

clearing :on

guard :shell do
  watch(/(.*).swift$/) {|m|

    puts "Modified: #{m[0]}"
    puts "Running tests..."

    output = ""
    errors = ""
    exit_status = Open3.popen3("swift test") do |stdin, stdout, stderr, wait_thr|
      stdin.close
      output << stdout.read
      errors << stderr.read
      wait_thr.value
    end

    puts output.yellow

    if exit_status.success?
      puts errors.cyan
      puts "Passed".green
    else
      puts errors.red
      puts "Failed".red
    end
  }
end
blog comments powered by Disqus