Why does the file get removed when commiting second time via rugged?

159 Views Asked by At

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

There are 1 best solutions below

2
On

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