Skip to content

Instantly share code, notes, and snippets.

@ematvey
Last active November 3, 2017 13:21
Show Gist options
  • Save ematvey/c2da27bcff99c90917040d7c7acf9e74 to your computer and use it in GitHub Desktop.
Save ematvey/c2da27bcff99c90917040d7c7acf9e74 to your computer and use it in GitHub Desktop.
rsync-watch
#!/usr/bin/env python3
import os
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('source')
parser.add_argument('destination')
args = parser.parse_args()
source = os.path.abspath(os.path.expanduser(args.source))
destination = args.destination
print("rsync-watch [{} -> {}]".format(source, destination))
def norm(l):
return l.decode('utf-8').strip('\n')
print('\ninitial sync\n')
cmd = 'rsync -r -v {} {}'.format(source, destination)
pop = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for l in pop.stdout:
print(norm(l))
print('\ninitial sync done, starting watch')
def watch(path):
uname = os.uname().sysname
if uname == 'Darwin':
cmd = "fswatch --exclude '.git' {}".format(path)
abspath = os.path.abspath(path)
for l in subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout:
print(l)
fn = norm(l).replace(abspath, '').strip('/')
yield abspath, fn
else:
cmd = "inotifywait --exclude '.git/' -e CLOSE_WRITE -m -q -r --format '%w %f' {}".format(
path)
for l in subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout:
path, fn = norm(l).split(' ')
yield path, fn
for path, fn in watch(source):
p_src = os.path.join(path, fn)
p_dest_path = p_src.replace(source, '')
p_dest = destination.rstrip('/') + '/' + p_dest_path.lstrip('/')
rsync_proc = subprocess.Popen('rsync -v {} {}'.format(p_src, p_dest),
shell=True, stdout=subprocess.PIPE)
print('\n@>> {} -> {}\n'.format(p_src, p_dest))
for l in rsync_proc.stdout:
print(norm(l))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment