public
Description: My set of personal Thor scripts.
Homepage:
Clone URL: git://github.com/crnixon/thor_tasks.git
Clinton R. Nixon (author)
Sat Sep 19 08:31:34 -0700 2009
thor_tasks / watch.thor
100644 55 lines (42 sloc) 1.397 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env ruby
 
# Based on rstakeout, originally by Mike Clark, from
# http://www.pragmaticautomation.com/cgi-bin/pragauto.cgi/Monitor/StakingOutFileChanges.rdoc
 
require 'find'
 
class Watch < Thor
  desc "path <command> <path> <path> ...", "Watch the given paths and execute the command every time they change. Put FILE in the filename to substitute it for the changed file."
  def path(command, *paths)
    exit if paths.empty?
    
    files = {}
    paths = paths.select { |path| File.exist?(path) }
    
    paths.each do |path|
      Find.find(File.expand_path(path)) do |file|
        if FileTest.directory?(file)
          if File.basename(file) =~ /^\.\w+/
            Find.prune
          else
            next
          end
        else
          files[file] = File.mtime(file)
        end
      end
    end
            
    puts "Watching #{paths.join(', ')}\n\nFiles: #{files.keys.length}"
 
    trap('INT') do
      puts "\nQuitting..."
      exit
    end
    
    loop do
      sleep 1
 
      changed_file, last_changed = files.find { |file, last_changed|
        File.mtime(file) > last_changed
      }
 
      if changed_file
        files[changed_file] = File.mtime(changed_file)
        puts "=> #{changed_file} changed, running #{command}"
        puts `#{command.gsub(/FILE/, changed_file)}`
        puts "=> done"
      end
    end
  end
end