Created
May 16, 2017 19:23
-
-
Save raven-rock/0f34a1bb4b778d811ddcddabfcaf102f to your computer and use it in GitHub Desktop.
myguard.rb - a simple command line tool that acts like Guard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# | |
# a simple command line tool that acts like Guard, but you can run any arbitrary command on any set of arbitrary files that change. | |
# | |
# Example usage: | |
# | |
# # Run test when a certain 3 files are modified. | |
# myguard.rb "ruby test_foo.rb" foo.rb foo_test.rb foo.json | |
# | |
require 'colorize' | |
class MyGuard | |
attr_reader :files, :interval | |
def initialize(*files, interval: 1) | |
@files = [files].flatten | |
@interval = interval | |
end | |
def print_start | |
puts "#{'=' * `tput cols`.to_i}".blue | |
puts "Starting at #{Time.now}".blue | |
end | |
def print_end | |
puts "Finished at #{Time.now}".blue | |
end | |
def run_command(&block) | |
print_start | |
yield | |
print_end | |
end | |
def watch(&block) | |
raise ArgumentError unless block | |
the_mtimes = mtimes(files) | |
run_command &block | |
loop do | |
new_mtimes = mtimes(files) | |
if new_mtimes != the_mtimes | |
run_command &block | |
the_mtimes = new_mtimes | |
end | |
sleep interval | |
end | |
end | |
def mtimes(files) | |
files.map { |f| [f, File.mtime(f)] }.to_h | |
end | |
end | |
if $0 == __FILE__ | |
shell_cmd = ARGV[0] | |
MyGuard.new(ARGV[1..-1]).watch { system shell_cmd } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment