Episode #246

Improved Guard Setup for Swift

7 minutes
Published on December 1, 2016

This video is only available to subscribers. Get access to this video and 584 others.

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

This episode uses Guard 2.14, Swift 3.0.