Categories
Development Software

Synchronizing live edits with fswatch

Synchronize development of a local project to a remote destination as you progress with your work.

fswatch is a great way to monitor for local file system changes, and then act upon them. This is similar to my “FMDMS” utility that I had made a while back.

Use case:
I develop locally, but sometimes I want to see those changes on a remote test server as I work. I keep a sync.bash script in each project that I want to test on a remote server. When I’m ready, I execute sync.bash locally.

Example:
In prior articles, I made extensive use of Docker for local development and remote deployment. When I’m working on a project that will run via Docker Compose, I place everything inside of /srv/ on the remote side, and can expect to see the same results on a remote system that I do on my development machine. From there, I can extend Docker Compose with multiple files (includes have been registered as a GitHub issue), and to differentiate between my Development and Production environments.

You could also add --delete-excluded as an argument to rsync, but when I’m working with systems where a database might exist in both locations, I want to exclude the file(s), but not delete them on the remote side.

#!/usr/bin/env bash

shopt -s expand_aliases

fsSrc="$HOME/srv/"
fsDest='USER@SERVER:~/srv/'

alias run_rsync="rsync \
    --progress \
    --partial \
    --archive \
    --verbose \
    --compress \
    --delete \
    --keep-dirlinks \
    --rsh=/usr/bin/ssh \
    \
    --exclude 'sync.bash' \
    --exclude '.*/' \
    --exclude '.*' \
    --exclude 'tmp/' \
    --exclude 'ignore/' \
    \
    '${fsSrc}' \
    '${fsDest}' \
    "

# Thanks: https://stackoverflow.com/questions/34575374/how-to-use-fswatch-and-rsync-to-automatically-sync-directories
run_rsync; fswatch \
    --print0 \
    --one-per-batch \
    --recursive \
    "${fsSrc}" | while read -d "" event; do run_rsync; done

Leave a Reply

Your email address will not be published. Required fields are marked *