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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Repository

Initialize a repository.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/gitrb/repository.rb', line 30

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

  @path = options[:path]
  @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, &block) ⇒ Object



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
287
# File 'lib/gitrb/repository.rb', line 261

def method_missing(name, *args, &block)
  cmd = name.to_s
  if cmd[0..3] == 'git_'
    ENV['GIT_DIR'] = path
    cmd = cmd[4..-1].tr('_', '-')
    args = args.flatten.compact.map {|s| "'" + s.to_s.gsub("'", "'\\\\''") + "'" }.join(' ')
    cmdline = "git #{cmd} #{args} 2>&1"

    @logger.debug "gitrb: #{cmdline}"

	# Read in binary mode (ascii-8bit) and convert afterwards
    out = if block_given?
		IO.popen(cmdline, 'rb', &block)
   else
            set_encoding IO.popen(cmdline, 'rb') {|io| io.read }
          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.



16
17
18
# File 'lib/gitrb/repository.rb', line 16

def branch
  @branch
end

#encodingObject (readonly)

Returns the value of attribute encoding.



16
17
18
# File 'lib/gitrb/repository.rb', line 16

def encoding
  @encoding
end

#headObject (readonly)

Returns the value of attribute head.



16
17
18
# File 'lib/gitrb/repository.rb', line 16

def head
  @head
end

#pathObject (readonly)

Returns the value of attribute path.



16
17
18
# File 'lib/gitrb/repository.rb', line 16

def path
  @path
end

#rootObject (readonly)

Returns the value of attribute root.



16
17
18
# File 'lib/gitrb/repository.rb', line 16

def root
  @root
end

Instance Method Details

#bare?Boolean

Bare repository?

Returns:

  • (Boolean)


50
51
52
# File 'lib/gitrb/repository.rb', line 50

def bare?
  @bare
end

#changed?Boolean

Has our repository been changed on disk?

Returns:

  • (Boolean)


63
64
65
# File 'lib/gitrb/repository.rb', line 63

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

#clearObject

Clear cached objects



73
74
75
76
77
78
# File 'lib/gitrb/repository.rb', line 73

def clear
  @transaction.synchronize do
    @objects.clear
    load
  end
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



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/gitrb/repository.rb', line 123

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



289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/gitrb/repository.rb', line 289

def default_user
  name = git_config('user.name').chomp
  email = git_config('user.email').chomp
  if name.empty?
    require 'etc'
    user = Etc.getpwnam(Etc.getlogin)
    name = user.gecos
  end
  if email.empty?
    require 'etc'
    email = Etc.getlogin + '@' + `hostname -f`.chomp
  end
  User.new(name, email)
end

#diff(from, to, path = nil) ⇒ Object

Diff



86
87
88
89
90
91
92
93
94
95
96
# File 'lib/gitrb/repository.rb', line 86

def diff(from, to, path = nil)
  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', '-u', '--full-index', from && from.id, to.id, '--', path))
end

#get(id) ⇒ Object

Get an object by its id.

Returns a tree, blob, commit or tag object.

Raises:

  • (ArgumentError)


175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
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
# File 'lib/gitrb/repository.rb', line 175

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

  if id =~ SHA_PATTERN
    raise NotFound, "Sha too short: #{id}" if id.length < 5
    list = @objects.find(id).to_a
    raise NotFound, "Sha is ambiguous: #{id}" if list.size > 1
    return list.first if list.size == 1
  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
  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

    id += trie.key[-(41 - id.length)...-1]

    list = trie.to_a
	raise NotFound, "Sha is ambiguous: #{id}" if list.size > 1

    pack, offset = list.first
    content, type = pack.get_object(offset)
  end

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

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

#get_blob(id) ⇒ Object



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

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

#get_commit(id) ⇒ Object



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

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

#get_tree(id) ⇒ Object



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

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

#in_transaction?Boolean

Is there any transaction going on?

Returns:

  • (Boolean)


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

def in_transaction?
  !!@lock[Thread.current.object_id]
end

#log(limit = 10, start = nil, path = nil) ⇒ Object

Returns a list of commits starting from head commit.



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/gitrb/repository.rb', line 145

def log(limit = 10, start = nil, path = nil)
  limit = limit.to_s
  start = start.to_s
  raise ArgumentError, "Invalid limit: #{limit}" if limit !~ /^\d+$/
  raise ArgumentError, "Invalid commit: #{start}" if start =~ /^\-/
  args = ['--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', "-#{limit}" ]
  args << start if !start.empty?
  args << '--' << path if path && !path.empty?
  log = git_log(*args).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 => ex
  return [] if ex.message =~ /bad default revision 'HEAD'/i
  raise
end

#put(object) ⇒ Object

Write a raw object to the repository.

Returns the object.



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/gitrb/repository.rb', line 236

def put(object)
  content = object.dump
  data = "#{object.type} #{content.bytesize rescue content.length}\0#{content}"
  id = sha(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.



68
69
70
# File 'lib/gitrb/repository.rb', line 68

def refresh
  load if changed?
end

#set_encoding(s) ⇒ Object



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

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' }


104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/gitrb/repository.rb', line 104

def transaction(message = '', author = nil, committer = nil)
  @transaction.synchronize do
    begin
      start_transaction
      result = yield
      commit(message, author, committer)
      result
    rescue
      rollback_transaction
      raise
    ensure
      finish_transaction
    end
  end
end