Skip to content

Instantly share code, notes, and snippets.

@jwasham
Forked from mpj/watcher.rb
Last active December 28, 2015 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwasham/7495979 to your computer and use it in GitHub Desktop.
Save jwasham/7495979 to your computer and use it in GitHub Desktop.
Watches local directory (and subdirectories) and does rsync to remote server when a file is added, modified, or deleted.
#!/usr/bin/env ruby
require 'rubygems'
require 'rb-fsevent'
def sync(local, host, remote)
timehack = Time.now;
print "syncing... #{timehack}\n";
# Construct the bash command that runs rsync.
cmd = "rsync " +
'-e "/usr/bin/ssh -i PATH_TO_KEYFILE" ' +
"--recursive " + # Sync all subdirectories.
"--copy-links " + # Include symlinked
"--compress " + # Compress before transferring (faster)
# "--progress " + # Show progress during transfer (quite verbose)
# Exclude stuff that you don't want to transfer.
"--exclude '.git' " +
"--exclude '.svn' " +
"--exclude '.hg' " +
"--exclude '.idea' " + # PHPStorm
"--exclude '.DS_Store' " + # Mac only
"--delete " + # If you delete files locally, then also delete remotely.
local + " " + host + ":" + remote
# Run the command.
system cmd
end
local = 'PATH_TO_LOCAL_FILES'
host = 'USERNAME@TARGET_SERVER_DOMAIN'
remote = 'PATH_ON_TARGET_SERVER'
# 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)
end
fsevent.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment