automatically push your git repo to a server on shutdown

22 Nov 2011

Sometimes, I forget to push my git commits to our git server at the end of the day. This causes inconvenience to others as they can’t review my code or build upon it. So, today I wrote a small script which syncs all my git repositories with a remote server. Hope it helps you too :)

The setup consists of three files:

core syncing script at ~/.scripts/sync-repos

 1 #!/usr/bin/env ruby
 2 require 'rubygems'
 3 require 'yaml'
 4 
 5 #replace google.com with your git servers domain
 6 `ping -c 1 google.com`
 7 if $?.exitstatus != 0
 8   puts 'UNABLE TO SYNC REPOS AS NW IS DOWN'
 9   exit $?.exitstatus
10 end
11 
12 puts 'syncing repositories'
13 
14 @repos = YAML::load_file File.expand_path( '~/.sync-repos')
15 
16 @repos.each do |repo|
17   path = File.expand_path repo[:path]
18   remotes = repo[:remotes].is_a?(String) ? [repo[:remotes]] : repo[:remotes]
19   unless File.exist? path
20     puts "skipping #{path} as directory not found"
21     next
22   end
23 
24   remotes.each do |remote|
25     cmd = "cd #{path} && git push #{remote}"
26     puts "executing: '#{cmd}'"
27     system(cmd)
28   end
29 end
30 
31 puts 'done syncing repositories'

config file pointing to all the repos at ~/.sync-repos

1 ---
2 - :path: ~/repos/search
3   :remotes:
4   - origin
5 - :path: ~/repos/logbin
6   :remotes:
7   - origin
8   - local

upstart shutdown trigger script at /etc/init/syncrepos.conf

1 start on runlevel [06]
2 
3 /bin/bash -l -c /home/minhajuddin/.scripts/sync-repos