Skip to content

Instantly share code, notes, and snippets.

@nnattawat
Last active December 18, 2015 01:12
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 nnattawat/dde8e1d8a38ca0254972 to your computer and use it in GitHub Desktop.
Save nnattawat/dde8e1d8a38ca0254972 to your computer and use it in GitHub Desktop.
Ruby script to sync files locally using rsync

Ruby script to sync files using rsync

Change sources_destinations_mapping array to any of your paths

For other options, please read more about rsync

# array of sources and destinations you want to sync
sources_destinations_mapping = [
["~/important_scripts/", "~/backup-scripts/"]
]
def execute_cmd cmd, silient=true
puts "Executing: #{cmd}" unless silient
output = %x(#{cmd})
unless $? == 0
raise 'The shell script returns error'
else
puts "#{output} \n" unless silient
output
end
end
def list_new_files source, destination
output = execute_cmd "rsync -avzi --dry-run #{source} #{destination}"
output.split(/\n/).inject([]) do |mem, line|
if line.empty?
return mem
elsif !line.include? '... done'
mem << line.split(' ').drop(1).join(' ')
end
mem
end
end
def syn_files source, destination
execute_cmd "rsync -avzi #{source} #{destination}"
end
def push_to_git new_files, local_path
execute_cmd "cd #{local_path} && git add ."
unless (execute_cmd "cd #{local_path} && git diff --cached").empty?
execute_cmd "cd #{local_path} && git commit -m 'Changed files: #{ new_files.join(",") }'"
execute_cmd "cd #{local_path} && git push origin master"
end
end
begin
sources_destinations_mapping.each do |source, destination|
new_files = list_new_files source, destination
if new_files.empty?
puts "Nothing changes from the last sync"
else
puts "Sync file(s):"
new_files.each{|file| puts "\t#{file}"}
syn_files source, destination
push_to_git new_files, destination
end
end
rescue Exception=>e
puts "\nException was caught: #{e}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment