我如何使用rugged来创建和提交类似命令行的文件?

时间:2014-07-03 10:31:53

标签: ruby git libgit2 rugged

我正在尝试使用坚固的东西来做一些非常简单的事情:创建并提交一个文件,使存储库处于与执行相同的状态:

git init
echo "blah blah blah" > blah.txt
git add blah.txt
git commit -m "write blah.txt"

留下git status打印

On branch master
nothing to commit, working directory clean

我正在使用改编自坚固的回购readme的代码,归结为:

name = "blah.txt"
repo = Rugged::Repository.init_at dir

File.open File.join(dir, name), 'w' do |f|
  f.write content
end

oid = Rugged::Blob.from_workdir repo, name
index = repo.index

index.add(:path => name, :oid => oid, :mode => 0100644)

options = {}
options[:tree] = index.write_tree(repo)

options[:author] = {  :email => "testuser@github.com",
                      :name => 'Test Author',
                      :time => Time.now }
options[:committer] = { :email => "testuser@github.com",
                        :name => 'Test Author',
                        :time => Time.now }
options[:message] =  "write #{ name }"
options[:parents] = repo.empty? ? [] : [ repo.head.target ].compact
options[:update_ref] = 'HEAD'

commit = Rugged::Commit.create(repo, options)

这似乎使存储库处于正确的状态,但工作目录在一个奇怪的地方,git status打印

On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    deleted:    blah.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    blah.txt

我不明白git在这一点上发生了什么(blah.txt是否会暂停删除?)。执行git reset --hard会使工作目录恢复到我所知道的所需状态。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

您已忘记将更改保存到索引中。您已更新引用以指向新提交,但索引未更改(因为您从未调用Index#write),因此就git而言,删除是暂存的,因为该文件不在索引,就像你已经运行git rm blah.txt