0

I want to store text files in a Git repo. I am using Ruby rugged gem 0.19.0 for this. The problem is that adding a second file f2 seems to automatically delete the first one f1. I have isolated the code to reproduce this (basically code straight from rugged gem docs):

require 'rugged'

def commit(file_name, message, content)
    user = { email: 'email', name: 'name', time: Time.now }

    repo = Rugged::Repository.new('repo')
    oid = repo.write(content, :blob)
    index = repo.index
    index.add(path: file_name, oid: oid, mode: 0100644)

    options = {}
    options[:tree] = index.write_tree(repo)
    options[:author] = user
    options[:committer] = user
    options[:message] = message
    options[:parents] = repo.empty? ? [] : [ repo.head.target ].compact
    options[:update_ref] = 'HEAD'
    Rugged::Commit.create(repo, options)
end

Rugged::Repository.init_at('repo', :bare)
commit('f1', 'create f1', 'f1 content')
commit('f2', 'create f2', 'f2 content')

After running above code and cloning the bare repo created, the git log --name-status shows that second commit removes f1 file.

How do I fix this to not mess with files stored previously in the repo?

1 Answer 1

0

Rugged README

oid = repo.write("This is a blob.", :blob)
index = repo.index
index.read_tree(repo.head.target.tree)   # notice
index.add(:path => "README.md", :oid => oid, :mode => 0100644)

but repo.head.target is a string in 0.19.0

oid = repo.write(content, :blob)
index = repo.index

begin
  commit = repo.lookup(repo.head.target)
  tree = commit.tree
  index.read_tree(tree)
rescue
end

index.add(path: file_name, oid: oid, mode: 0100644)

It works

2
  • Thanks. This does run (no errors), but still this does not end up with a repo with both files - only second file is present, while first one gets deleted. Jun 26, 2014 at 17:21
  • I tested in my computer, it's ok. ruby 2.0.0p451 (2014-02-24 revision 45167) [x86_64-darwin13.1.0] OSX rugged(0.19.0)
    – chengguyun
    Jun 27, 2014 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.