-
-
Save threez/3683424 to your computer and use it in GitHub Desktop.
Github backup script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'json' | |
require 'fileutils' | |
require 'net/smtp' | |
require 'net/https' | |
require 'uri' | |
BACKUP_DIR='/srv/git/repositories' | |
USERNAME='threez' | |
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 | |
uri = URI.parse(URL_REPOS) | |
http = Net::HTTP.new(uri.host, uri.port) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_PEER | |
# it's from curl from http://curl.haxx.se/ca/cacert.pem | |
http.ca_file = "/etc/cacert.pem" | |
headers = { "Accept" => "application/vnd.github.v3+json" } | |
repo_json = http.get(uri.path, headers).body | |
JSON.load(repo_json).each do |repo| | |
repo_name = "#{repo["name"]}.git" | |
repo_url = repo["git_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 | |
puts e | |
send_email("[email protected]", :body => e.message) | |
end | |
puts "## END github backup: #{Time.now.to_s}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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