Skip to content

Instantly share code, notes, and snippets.

@mpj
Last active January 26, 2023 01:05
Show Gist options
  • Save mpj/3749357 to your computer and use it in GitHub Desktop.
Save mpj/3749357 to your computer and use it in GitHub Desktop.
Keep directory in sync with remote server using Rsync and FSEvent.
#!/usr/bin/env ruby
require 'rubygems'
require 'rb-fsevent'
require 'ruby-growl'
def sync(local, host, remote, growl)
# Construct the bash command that runs rsync.
cmd = "rsync " +
"--recursive " + # Sync all subdirectories.
"--copy-links " + # include symlinked
"--compress " + # Compress before transferring (faster)
# Exclude stuff that you don't want to transfer.
"--exclude '.git' " +
"--exclude '.svn' " +
"--delete " + # If you delete files locally,
# also delete remotely.
local + " " + host + ":" + remote
# Notify via Growl that sync is triggered.
growl.notify("ruby-growl Notification", "Sync", "#{local} => #{host}:#{remote}")
# Run the command.
system cmd
end
local = '/Users/mpj/code/web-site-player/'
host = 'my.development.vm.machine.spotify.net'
remote = '/home/mpj/src/web-site-player/'
growl = Growl.new "localhost", "ruby-growl"
growl.add_notification "ruby-growl Notification"
growl.notify "ruby-growl Notification",
"Started watching...",
"#{local} => #{remote}"
# FSevents wont detect changes in subdirectories that are symlinks
# (because technically the symlink has not changed)
# so list all symliks an monitor them separately
paths = []
# Horribly unreadable command to recursively find all symlink paths in a directory:
symlinks_cmd = "find "+ local + " -type l -exec ls -l {} \\; | grep -no '\\->.*$' | cut -c 6-"
f = open("|" + symlinks_cmd)
output = f.read()
output.each_line { |path| paths.push path.sub(/\n/, '') }
# Finally, add the root directory.
paths.push local
fsevent = FSEvent.new
fsevent.watch paths do
sync(local, host, remote, growl)
end
fsevent.run
@parkerproject
Copy link

Why should I place this file locally?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment