Class: Gitrb::Repository

Inherits:
Object
  • Object
show all
Defined in:
lib/gitrb/repository.rb

Constant Summary collapse

SHA_PATTERN =
/^[A-Fa-f0-9]{5,40}$/
REVISION_PATTERN =
/^[\w\-\.]+([\^~](\d+)?)*$/
DEFAULT_ENCODING =
'utf-8'
MIN_GIT_VERSION =
'1.6.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Repository

Initialize a repository.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/gitrb/repository.rb', line 41

def initialize(options = {})
  @bare    = options[:bare] || false
  @branch  = options[:branch] || 'master'
  @logger  = options[:logger] || Logger.new(nil)
  @encoding = options[:encoding] || DEFAULT_ENCODING

  @path = options[:path].chomp('/')
  @path += '/.git' if !@bare

  check_git_version if !options[:ignore_version]
  open_repository(options[:create])

  load_packs
  load
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/gitrb/repository.rb', line 288

def method_missing(name, *args)
  cmd = name.to_s
  if cmd[0..3] == 'git_'
    cmd = cmd[4..-1].tr('_', '-')
    args = args.flatten.compact.map {|a| a.to_s }

    @logger.debug "gitrb: #{self.class.git_path} #{cmd} #{args.inspect}"

    out = IO.popen('-', 'rb') do |io|
      if io
        # Read in binary mode (ascii-8bit) and convert afterwards
        block_given? ? yield(io) : set_encoding(io.read)
      else
        # child's stderr goes to stdout
        STDERR.reopen(STDOUT)
        ENV['GIT_DIR'] = path
        exec(self.class.git_path, cmd, *args)
      end
    end

    if $?.exitstatus > 0
      return '' if $?.exitstatus == 1 && out == ''
      raise CommandError.new("git #{cmd}", args, out)
    end

    out
  else
    super
  end
end

Instance Attribute Details

#branchObject

Returns the value of attribute branch.



19
20
21
# File 'lib/gitrb/repository.rb', line 19

def branch
  @branch
end

#encodingObject (readonly)

Returns the value of attribute encoding.



19
20
21
# File 'lib/gitrb/repository.rb', line 19

def encoding
  @encoding
end

#headObject (readonly)

Returns the value of attribute head.



19
20
21
# File 'lib/gitrb/repository.rb', line 19

def head
  @head
end

#pathObject (readonly)

Returns the value of attribute path.



19
20
21
# File 'lib/gitrb/repository.rb', line 19

def path
  @path
end

#rootObject (readonly)

Returns the value of attribute root.



19
20
21
# File 'lib/gitrb/repository.rb', line 19

def root
  @root
end

Class Method Details

.git_pathObject



21
22
23
24
25
26
27
# File 'lib/gitrb/repository.rb', line 21

def self.git_path
  @git_path ||= begin
    path = `which git`.chomp
    raise 'git not found' if $?.exitstatus != 0
    path
  end
end

Instance Method Details

#bare?Boolean

Bare repository?

Returns:

  • (Boolean)


66
67
68
# File 'lib/gitrb/repository.rb', line 66

def bare?
  @bare
end

#changed?Boolean

Has our repository been changed on disk?

Returns:

  • (Boolean)


77
78
79
# File 'lib/gitrb/repository.rb', line 77

def changed?
  !head || head.id != read_head_id
end

#clearObject

Clear cached objects



87
88
89
90
# File 'lib/gitrb/repository.rb', line 87

def clear
  @objects.clear
  load
end

#commit(message = '', author = nil, committer = nil) ⇒ Object

Write a commit object to disk and set the head of the current branch.

Returns the commit object



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/gitrb/repository.rb', line 141

def commit(message = '', author = nil, committer = nil)
  return if !root.modified?

  author ||= default_user
  committer ||= author
  root.save

  commit = Commit.new(:repository => self,
                      :tree => root,
                      :parents => head,
                      :author => author,
                      :committer => committer,
                      :message => message)
  commit.save

  write_head_id(commit.id)
  load

  commit
end

#default_userObject



319
320
321
322
323
324
325
326
327
# File 'lib/gitrb/repository.rb', line 319

def default_user
  @default_user ||= begin
    name = git_config('user.name').chomp
    email = git_config('user.email').chomp
    name = ENV['USER'] if name.empty?
    email = ENV['USER'] + '@' + `hostname -f`.chomp if email.empty?
    User.new(name, email)
  end
end

#diff(opts) ⇒ Object

Difference between versions Options:

:to             - Required target commit
:from           - Optional source commit (otherwise comparision with empty tree)
:path           - Restrict to path/or paths
:detect_renames - Detect renames O(n^2)
:detect_copies  - Detect copies O(n^2), very slow


99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/gitrb/repository.rb', line 99

def diff(opts)
  from, to = opts[:from], opts[:to]
  if from && !(Commit === from)
    raise ArgumentError, "Invalid sha: #{from}" if from !~ SHA_PATTERN
    from = Reference.new(:repository => self, :id => from)
  end
  if !(Commit === to)
    raise ArgumentError, "Invalid sha: #{to}" if to !~ SHA_PATTERN
    to = Reference.new(:repository => self, :id => to)
  end
  Diff.new(from, to, git_diff_tree('--root', '--full-index', '-u',
                                   opts[:detect_renames] ? '-M' : nil,
                                   opts[:detect_copies] ? '-C' : nil,
                                   from ? from.id : nil, to.id, '--', *opts[:path]))
end

#dupObject



57
58
59
60
61
62
63
# File 'lib/gitrb/repository.rb', line 57

def dup
  super.instance_eval do
    @objects = Trie.new
    load
    self
  end
end

#get(id) ⇒ Object

Get an object by its id.

Returns a tree, blob, commit or tag object.

Raises:

  • (ArgumentError)


197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/gitrb/repository.rb', line 197

def get(id)
  raise ArgumentError, 'Invalid id given' if !(String === id)

  if id =~ SHA_PATTERN
    raise ArgumentError, "Sha too short: #{id}" if id.length < 5

    trie = @objects.find(id)
    raise NotFound, "Sha is ambiguous: #{id}" if trie.size > 1
    return trie.value if !trie.empty?
  elsif id =~ REVISION_PATTERN
    list = git_rev_parse(id).split("\n") rescue nil
    raise NotFound, "Revision not found: #{id}" if !list || list.empty?
    raise NotFound, "Revision is ambiguous: #{id}" if list.size > 1
    id = list.first

    trie = @objects.find(id)
    raise NotFound, "Sha is ambiguous: #{id}" if trie.size > 1
    return trie.value if !trie.empty?
  else
    raise ArgumentError, "Invalid id given: #{id}"
  end

  @logger.debug "gitrb: Loading #{id}"

  path = object_path(id)
  if File.exists?(path) || (glob = Dir.glob(path + '*')).size >= 1
    if glob
      raise NotFound, "Sha is ambiguous: #{id}" if glob.size > 1
      path = glob.first
      id = path[-41..-40] + path[-38..-1]
    end

    buf = File.open(path, 'rb') { |f| f.read }

    raise NotFound, "Not a loose object: #{id}" if !legacy_loose_object?(buf)

    header, content = Zlib::Inflate.inflate(buf).split("\0", 2)
    type, size = header.split(' ', 2)

    raise NotFound, "Bad object: #{id}" if content.length != size.to_i
  else
    trie = @packs.find(id)
	raise NotFound, "Object not found: #{id}" if trie.empty?
	raise NotFound, "Sha is ambiguous: #{id}" if trie.size > 1
    id = trie.key
    pack, offset = trie.value
    content, type = pack.get_object(offset)
  end

  @logger.debug "gitrb: Loaded #{type} #{id}"

  set_encoding(id)
  object = GitObject.factory(type, :repository => self, :id => id, :data => content)
  @objects.insert(id, object)
  object
end

#get_blob(id) ⇒ Object



255
# File 'lib/gitrb/repository.rb', line 255

def get_blob(id)   get_type(id, :blob) end

#get_commit(id) ⇒ Object



256
# File 'lib/gitrb/repository.rb', line 256

def get_commit(id) get_type(id, :commit) end

#get_tree(id) ⇒ Object



254
# File 'lib/gitrb/repository.rb', line 254

def get_tree(id)   get_type(id, :tree) end

#log(opts = {}) ⇒ Object

Returns a list of commits starting from head commit. Options:

:path      - Restrict to path/or paths
:max_count - Maximum count of commits
:skip      - Skip n commits
:start     - Commit to start from


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/gitrb/repository.rb', line 168

def log(opts = {})
  max_count = opts[:max_count]
  skip = opts[:skip]
  start = opts[:start]
  raise ArgumentError, "Invalid commit: #{start}" if start.to_s =~ /^\-/
  log = git_log('--pretty=tformat:%H%n%P%n%T%n%an%n%ae%n%at%n%cn%n%ce%n%ct%n%x00%s%n%b%x00',
                skip ? "--skip=#{skip.to_i}" : nil,
                max_count ? "--max-count=#{max_count.to_i}" : nil, start, '--', *opts[:path]).split(/\n*\x00\n*/)
  commits = []
  log.each_slice(2) do |data, message|
    data = data.split("\n")
    parents = data[1].empty? ? nil : data[1].split(' ').map {|id| Reference.new(:repository => self, :id => id) }
    commits << Commit.new(:repository => self,
                          :id => data[0],
                          :parents => parents,
                          :tree => Reference.new(:repository => self, :id => data[2]),
                          :author => User.new(data[3], data[4], Time.at(data[5].to_i)),
                          :committer => User.new(data[6], data[7], Time.at(data[8].to_i)),
                          :message => message.strip)
  end
  commits
rescue CommandError => ex
  return [] if ex.output =~ /bad default revision 'HEAD'/i
  raise
end

#put(object) ⇒ Object

Write a raw object to the repository.

Returns the object.

Raises:

  • (ArgumentError)


261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/gitrb/repository.rb', line 261

def put(object)
  raise ArgumentError unless object && GitObject === object

  content = object.dump
  data = "#{object.type} #{content.bytesize rescue content.length}\0#{content}"
  id = Digest::SHA1.hexdigest(data)
  path = object_path(id)

  @logger.debug "gitrb: Storing #{id}"

  if !File.exists?(path)
    FileUtils.mkpath(File.dirname(path))
    File.open(path, 'wb') do |f|
      f.write Zlib::Deflate.deflate(data)
    end
  end

  @logger.debug "gitrb: Stored #{id}"

  set_encoding(id)
  object.repository = self
  object.id = id
  @objects.insert(id, object)

  object
end

#refreshObject

Load the repository, if it has been changed on disk.



82
83
84
# File 'lib/gitrb/repository.rb', line 82

def refresh
  load if changed?
end

#set_encoding(s) ⇒ Object



35
# File 'lib/gitrb/repository.rb', line 35

def set_encoding(s); s.force_encoding(@encoding); end

#transaction(message = '', author = nil, committer = nil) ⇒ Object

All changes made inside a transaction are atomic. If some exception occurs the transaction will be rolled back.

Example:

repository.transaction { repository['a'] = 'b' }


121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/gitrb/repository.rb', line 121

def transaction(message = '', author = nil, committer = nil)
  lock = File.open("#{head_path}.lock", 'w')
  lock.flock(File::LOCK_EX)
  refresh

  result = yield
  commit(message, author, committer)
  result
rescue
  @objects.clear
  load
  raise
ensure
  lock.close rescue nil
  File.unlink("#{head_path}.lock") rescue nil
end