Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guard executes shell scripts twice

Tags:

ruby

guard

I setup an example project with the following structure:

Gemfile
Guardfile

The contents of these files are:

# Gemfile
source :rubygems
gem "guard"
gem "guard-shell"

and

# Guardfile
guard 'shell' do
  watch(/^test\.txt$/) {|m| `echo #{m.inspect} #{File.mtime(m[0])}` }
end

I then continue to run guard. Whenever I echo something into that file, guard registers a change twice. In one shell:

$ echo blah >> test.txt

In the shell running guard:

> [test.txt] 2012-06-26 00:40:22 +0200
> [test.txt] 2012-06-26 00:40:22 +0200

The same behaviour accounts for vim/nano etc. Interestingly, when I just run echo blah > test.txt, guard only fires once.

Any idea how I can prevent this from happening or whether this is expected behaviour?

EDIT: Opened up an issue on github: https://github.com/guard/guard/issues/297#issuecomment-6586266

like image 538
jabalsad Avatar asked Jun 25 '12 22:06

jabalsad


1 Answers

Seems like a bug/feature of guard and/or guard-shell. I'd report in issue on github for it. In the meantime here's an (ugly) workaround to prevent running files where the mtime is the same as last time:

# Guardfile
class GFilter
  def self.run(files, &block)
    @mtimes ||= Hash.new

    files.each { |f|
      mtime = File.mtime(f)
      next if @mtimes[f] == mtime
      @mtimes[f] = mtime

      yield f
    }
  end
end

guard 'shell' do
  watch(/^test\.txt$/) {|m| GFilter.run(m) { |f| puts "File: #{f}" } }
end
like image 83
Casper Avatar answered Oct 12 '22 19:10

Casper