Skip to content

Instantly share code, notes, and snippets.

@hh
Created February 4, 2014 21:49
Show Gist options
  • Save hh/8813048 to your computer and use it in GitHub Desktop.
Save hh/8813048 to your computer and use it in GitHub Desktop.
rugged library attempt at using gerrit ssh / http remotes
require 'rugged'
require 'digest'
class GitUtils
def initialize(opts={})
path = opts[:path] || Dir.pwd
email = opts[:author_email] || "gerrit@hippiehacker.org"
aname = opts[:author_name] || "Gerrit HH"
@default_repo_name = opts[:repo_name] || "gerrit"
#@default_remote_ref = opts[:remote_ref] || "refs/publish/master"
@default_remote_ref = opts[:remote_ref] || "refs/drafts/master"
@repo = Rugged::Repository.new(Rugged::Repository.discover(path))
@index = @repo.index
@author = { :email => email, :time => Time.now, :name => aname }
end
def add_commit(path, message)
git_add(path)
git_commit(message)
end
# Add a path
def add(path)
# TODO: File.exists?(path)
@index.add(path)
end
def parents
[ @repo.lookup( @repo.head.target ).oid ]
end
def tree
@repo.lookup( @index.write_tree )
end
def gen_cid_line(message)
cid_text = <<EOF
tree #{@index.write_tree}
parent #{parents.first}
author #{@author}
commiter #{@author}
#{message}
EOF
cid = Digest::SHA1.new.hexdigest cid_text
"Change-Id: I#{cid}"
end
def gen_message(message)
message + "\n\n" + gen_cid_line(message)
end
def commit(message)
@index.write # staging the commit, required
Rugged::Commit.create(@repo,
:author => @author,
:message => gen_message(message),
:committer => @author,
:parents => parents,
:tree => tree.oid,
:update_ref => 'HEAD')
end
# def push(repo_name, remote_ref, local_ref)
def push(opts={})
#repo_url = opts[:url]
repo_name = opts[:name] || @default_repo_name
remote_ref = opts[:remote_ref] || @default_remote_ref
local_ref = opts[:local_ref] || 'HEAD'
#repo_url ||= Rugged::Remote.lookup(@repo, @repo_name)
x = `git push #{repo_name} #{local_ref}:#{remote_ref}`
#if $?.success?
#end
end
end
if caller.length == 0
g = GitUtils.new
open("#{Time.now}.txt",'w') do |f|
f.write(Time.now)
end
Dir.glob("*.txt").each do |f|
g.add(f)
end
g.commit("added a datefile on #{Time.now}")
g.push
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment