Skip to content

Instantly share code, notes, and snippets.

@joshco
Last active May 10, 2019 18:44
Show Gist options
  • Save joshco/6c84fd30dfbe0118bc42570000eb268d to your computer and use it in GitHub Desktop.
Save joshco/6c84fd30dfbe0118bc42570000eb268d to your computer and use it in GitHub Desktop.
Vagrant Guest Guard HTTP Solution
require 'sinatra'
require 'json'
# Use of guard-yield based on wisdom from https://github.com/e2
# use of HTTP crime by @joshco
class SinatraGuard < Sinatra::Base
set :bind, '0.0.0.0'
set :port, 4000
post '/v1/change' do
obj=JSON.parse(request.body.read,:symbolize_names => true)
modified=obj[:modified]
added=obj[:added]
removed=obj[:removed]
Guard.async_queue_add(modified: modified, added: added, removed: removed)
end
end
sinatra_start = proc do
th=Thread.new do
SinatraGuard.run!
end
end
sinatra_quit = proc do
SinatraGuard.quit!
end
guard :yield, {start: sinatra_start, stop: sinatra_quit } do
# nothing
end
require 'faraday'
require 'listen'
require 'json'
# @joshco
url = 'http://192.168.10.10:4000'
watch_dir='../vb2/tmx'
$abs_path=File.absolute_path(watch_dir) + '/'
def relative_path(file)
return nil if file.nil?
relative_path=file.sub($abs_path,'')
relative_path
end
def relativize_array(array)
return [] if array.empty?
array.map { |m| relative_path(m) }
end
listener = Listen.to(watch_dir) do |modified, added, removed|
modified_relative=relativize_array(modified)
added_relative=relativize_array(added)
removed_relative=relativize_array(removed)
payload = {
modified: modified_relative,
added: added_relative,
removed: removed_relative
}
puts payload
http=Faraday.new(url: url) do |conn|
conn.adapter :net_http
end
http.post do |req|
req.url '/v1/change'
req.headers['Content-Type']='application/json'
req.body=payload.to_json
end
end
listener.start # not blocking
puts "Listening to #{watch_dir}"
sleep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment