Class: VagrantPlugins::Fsnotify::Command

Inherits:
Object
  • Object
show all
Includes:
Vagrant::Action::Builtin::MixinSyncedFolders
Defined in:
lib/vagrant-fsnotify/command-fsnotify.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.synopsisObject



7
8
9
# File 'lib/vagrant-fsnotify/command-fsnotify.rb', line 7

def self.synopsis
  'forwards filesystem events to virtual machine'
end

Instance Method Details

#callback(paths, modified, added, removed) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/vagrant-fsnotify/command-fsnotify.rb', line 135

def callback(paths, modified, added, removed)

  @logger.info("File change callback called!")
  @logger.info("  - Modified: #{modified.inspect}")
  @logger.info("  - Added: #{added.inspect}")
  @logger.info("  - Removed: #{removed.inspect}")

  @changes.each do |rel_path, time|
    @changes.delete(rel_path) if time < Time.now.to_i - 2
  end

  tosync = {}
  todelete = []

  paths.each do |hostpath, folder|

    toanalyze = []
    if folder[:opts][:fsnotify] == true
      toanalyze += modified + added + removed
    else
      if folder[:opts][:fsnotify].include? :modified
        toanalyze += modified
      end
      if folder[:opts][:fsnotify].include? :added
        toanalyze += added
      end
      if folder[:opts][:fsnotify].include? :removed
        toanalyze += removed
      end
    end

    toanalyze.each do |file|

      if file.start_with?(hostpath)

        rel_path =  file.sub(hostpath, '')

        if @changes[rel_path] && @changes[rel_path] >= Time.now.to_i - 2
          @logger.info("#{rel_path} was changed less than two seconds ago, skipping")
          next
        end

        @changes[rel_path] = Time.now.to_i
        if modified.include? file
          folder[:machine].ui.info("fsnotify: Changed: #{rel_path}")
        elsif added.include? file
          folder[:machine].ui.info("fsnotify: Added: #{rel_path}")
        elsif removed.include? file
          folder[:machine].ui.info("fsnotify: Removed: #{rel_path}")
        end

        guestpath = folder[:opts][:override_guestpath] || folder[:opts][:guestpath]
        guestpath = File.join(guestpath, rel_path)

        tosync[folder[:machine]] = [] if !tosync.has_key?(folder[:machine])
        tosync[folder[:machine]] << guestpath

        if removed.include? file
          todelete << guestpath
        end
      end

    end

  end

  tosync.each do |machine, files|
    touch_flags = get_touch_flags(machine.config.fsnotify.touch)
    machine.communicate.execute("touch -#{touch_flags} '#{files.join("' '")}'")
    remove_from_this_machine = files & todelete
    unless remove_from_this_machine.empty?
      machine.communicate.execute("rm -rf '#{remove_from_this_machine.join("' '")}'")
    end
  end

rescue => e
  @logger.error("#{e}: #{e.message}")
end

#exclude_to_regexp(exclude) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/vagrant-fsnotify/command-fsnotify.rb', line 214

def exclude_to_regexp(exclude)

  # This is REALLY ghetto, but its a start. We can improve and
  # keep unit tests passing in the future.
  exclude = exclude.gsub("**", "|||GLOBAL|||")
  exclude = exclude.gsub("*", "|||PATH|||")
  exclude = exclude.gsub("|||PATH|||", "[^/]*")
  exclude = exclude.gsub("|||GLOBAL|||", ".*")

  Regexp.new(exclude)

end

#executeObject



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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/vagrant-fsnotify/command-fsnotify.rb', line 11

def execute
  @logger = Log4r::Logger.new("vagrant::commands::fsnotify")

  params = OptionParser.new do |o|
    o.banner = "Usage: vagrant fsnotify [vm-name]"
    o.separator ""
  end

  argv = parse_options(params)
  return if !argv

  paths = {}
  ignores = []
  @changes = {}

  with_target_vms(argv) do |machine|
    if !machine.communicate.ready?
      machine.ui.error("Machine not ready, is it up?")
      return 1
    end

    synced_folders(machine).each do |type, folder|

      folder.each do |id, opts|

        if !(
            (opts[:fsnotify] == true) ||
            (
              opts[:fsnotify].respond_to?(:include?) &&
              (
                opts[:fsnotify].include?(:modified) ||
                opts[:fsnotify].include?(:added) ||
                opts[:fsnotify].include?(:removed)
              )
            )
          )
          next
        end

        # Folder info
        hostpath  = opts[:hostpath]
        hostpath  = File.expand_path(hostpath, machine.env.root_path)
        hostpath  = Vagrant::Util::Platform.fs_real_path(hostpath).to_s

        # Make sure the host path ends with a "/" to avoid creating
        # a nested directory...
        if !hostpath.end_with?("/")
          hostpath += "/"
        end

        machine.ui.info("fsnotify: Watching #{hostpath}")

        paths[hostpath] = {
          id: id,
          machine: machine,
          opts: opts
        }

        if opts[:exclude]
          Array(opts[:exclude]).each do |pattern|
            ignores << exclude_to_regexp(pattern.to_s)
          end
        end

      end

    end

  end

  if paths.empty?
    @env.ui.info(<<-MESSAGE)
Nothing to sync.

Note that the valid values for the `:fsnotify' configuration key on
`Vagrantfile' are either `true' (which forwards all kinds of filesystem events)
or an Array containing symbols among the following options: `:modified',
`:added' and `:removed' (in which case, only the specified filesystem events are
forwarded).

For example, to forward all filesystem events to the default `/vagrant' folder,
add the following to the `Vagrantfile':

  config.vm.synced_folder ".", "/vagrant", fsnotify: true

And to forward only added files events to the default `/vagrant' folder, add the
following to the `Vagrantfile':

  config.vm.synced_folder ".", "/vagrant", fsnotify: [:added]

Exiting...
MESSAGE
    return 1
  end

  @logger.info("Listening to paths: #{paths.keys.sort.inspect}")
  @logger.info("Listening via: #{Listen::Adapter.select.inspect}")
  @logger.info("Ignoring #{ignores.length} paths:")
  ignores.each do |ignore|
    @logger.info("  -- #{ignore.to_s}")
  end

  listener_callback = method(:callback).to_proc.curry[paths]
  listener = Listen.to(*paths.keys, ignore: ignores, &listener_callback)

  # Create the callback that lets us know when we've been interrupted
  queue    = Queue.new
  callback = lambda do
    # This needs to execute in another thread because Thread
    # synchronization can't happen in a trap context.
    Thread.new { queue << true }
  end

  # Run the listener in a busy block so that we can cleanly
  # exit once we receive an interrupt.
  Vagrant::Util::Busy.busy(callback) do
    listener.start
    queue.pop
    listener.stop if listener.state != :stopped
  end

  return 0
end

#get_touch_flags(touch) ⇒ Object



227
228
229
230
231
232
233
234
235
# File 'lib/vagrant-fsnotify/command-fsnotify.rb', line 227

def get_touch_flags(touch)
  if touch.include? :modification and not touch.include? :access
    return "m"
  elsif not touch.include? :modification and touch.include? :access
    return "a"
  else
    return "am"
  end
end