Skip to content

Instantly share code, notes, and snippets.

@mtmtcode
Last active September 2, 2022 00:30
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save mtmtcode/5006645 to your computer and use it in GitHub Desktop.
Save mtmtcode/5006645 to your computer and use it in GitHub Desktop.
auto-rsync.el - Emacs minor mode to execute rsync automaticlly
;;; auto-rsync-mode -- minor mode for auto rsync
;;
;; Author: @l3msh0
;;
;;; Example
;;
;; (require 'auto-rsync)
;; (auto-rsync-mode t)
;; (setq auto-rsync-dir-alist
;; (("/path/to/src1/" . "/path/to/dest1/")
;; ("/path/to/src2/" . "username@hostname:/path/to/dest2/")))
;;; Customize
;;
(defgroup auto-rsync nil "Auto rsync")
(defcustom auto-rsync-command "rsync" "rsync command path" :group 'auto-rsync)
(defcustom auto-rsync-command-option "-avzq" "rsync command option" :group 'auto-rsync)
;;; TODO
;;
;; open remote counterpart
;;
(defvar auto-rsync-dir-alist nil "Pair of rsync source and destination dir")
(defvar auto-rsync-normalized-alist nil)
;;; Code
(defun auto-rsync-exec-rsync ()
"execute rsync if editing file path matches src dir"
(interactive)
(let* ((normalized-alist (mapcar (lambda (x) (cons (file-name-as-directory (expand-file-name (car x)))
(file-name-as-directory (cdr x))))
auto-rsync-dir-alist))
(sync-pair (assoc-if (lambda (key) (string-match key buffer-file-name)) normalized-alist)))
(when sync-pair
(save-window-excursion
;; avoid annoying shell comannd window
(shell-command (format "%s %s %s %s&" auto-rsync-command auto-rsync-command-option (car sync-pair) (cdr sync-pair)) nil)))))
(define-minor-mode auto-rsync-mode
"automatically execute rsync when editing file's path matches `auto-rsync-dir-alist`"
:lighter " rsync"
:global t
(cond (auto-rsync-mode
(add-hook 'after-save-hook 'auto-rsync-exec-rsync))
(t
(remove-hook 'after-save-hook 'auto-rsync-exec-rsync))))
(provide 'auto-rsync)
@etu
Copy link

etu commented Jan 15, 2016

Why not package this as a mode and put it in melpa? Would be nice ;)

@jayeye
Copy link

jayeye commented Aug 15, 2017

excellent. You missed a quote in the example -- the alist should be quoted!

@kkonevets
Copy link

Thanks! This code made my day.
As of 2021 use cl-assoc-if instead of assoc-if and what @jayeye said is also helpful

@larrasket
Copy link

Thanks

@grzs
Copy link

grzs commented Sep 1, 2022

@mtmtcode It's great, thanks! I added exclude and multiple flags options. I would create a PR, but it's not possible with a Gist I suppose.

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