Skip to content

Instantly share code, notes, and snippets.

@r10r
Created October 17, 2011 13:22
Show Gist options
  • Save r10r/1292594 to your computer and use it in GitHub Desktop.
Save r10r/1292594 to your computer and use it in GitHub Desktop.
Github backup script
#!/usr/bin/env ruby
require 'json'
require 'open-uri'
require 'fileutils'
require 'net/smtp'
BACKUP_DIR='/home/git/github-backup'
USERNAME='my_username'
URL_REPOS="https://api.github.com/users/#{USERNAME}/repos"
URL_CLONE="[email protected]:#{USERNAME}"
def update(repo_path)
puts "## update repo #{repo_path}"
Dir.chdir repo_path
`git remote update`
end
def clone(repo_url)
Dir.chdir BACKUP_DIR
puts "## fetch repo #{repo_url}"
`git clone --bare #{repo_url}`
end
def send_email(to,opts={})
opts[:server] ||= 'localhost'
opts[:from] ||= '[email protected]'
opts[:from_alias] ||= 'Github Backup Script'
opts[:subject] ||= "Github Backup failed"
opts[:body] ||= "Important stuff!"
msg = <<END_OF_MESSAGE
From: #{opts[:from_alias]} <#{opts[:from]}>
To: <#{to}>
Subject: #{opts[:subject]}
#{opts[:body]}
END_OF_MESSAGE
Net::SMTP.start(opts[:server]) do |smtp|
smtp.send_message msg, opts[:from], to
end
end
puts "## BEGIN github backup: #{Time.now.to_s}"
begin
myrepos = JSON.load(open(URL_REPOS)).each do |repo|
repo_name = "#{repo["name"]}.git"
repo_url = repo["ssh_url"]
repo_path = "#{BACKUP_DIR}/#{repo_name}"
if not File.directory? BACKUP_DIR
FileUtils.mkdir_p BACKUP_DIR
end
if File.directory? repo_path
update repo_path
else
clone repo_url
end
end
rescue Exception => e
send_email("[email protected]", body:e.message)
end
puts "## END github backup: #{Time.now.to_s}"
puts
0 */1 * * * git /home/git/helper-scripts/backup_git_repos.rb >>/home/git/github-backup/backup.log 2>&1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment