1
mkdir /tmp/scratch
cd /tmp/scratch
git init .

--*-- xx.rb:

SCRATCH = '/tmp/scratch'
repo = Repo.new(SCRATCH)

def add_multiple_commits_same_file_different_content(repo)
  previous_commit = repo.commits.first && repo.commits.first.id
  dir = "./"
  (0...5).each do |count|
    i1 = repo.index
    i1.read_tree('master')
    i1.add("#{dir}foo.txt", "hello foo, count is #{count}.\n")
    dir += "sd#{count}/"
    previous_commit =  i1.commit("my commit - #{count}",
                             previous_commit,
                             Actor.new("j#{count}", "e@e#{count}.zz"),
                             previous_commit.nil? ? nil : repo.commits(previous_commit).first.tree)
  end
end

add_multiple_commits_same_file_different_content(repo)

---* ---

git status:
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       deleted:    ./foo.txt
#       deleted:    ./sd0/foo.txt
#       deleted:    ./sd0/sd1/foo.txt
#       deleted:    ./sd0/sd1/sd2/foo.txt
#       deleted:    ./sd0/sd1/sd2/sd3/foo.txt
#       deleted:    ./sd0/sd1/sd2/sd3/sd4/foo.txt

---*----

If I try to check out the files they get deleted. Any ideas on hwta I am doing wrong.

Thanks John

2 Answers2

4

I know this is an old post, but I was having the same problem and found it when searching for a solution. Looks like you need to be in the repo directory when adding the file(s). Here's what I did to make it work...

repo = Grit::Repo.init('repo/test.git')

File.open('repo/test.git/foo.txt', 'w') { |f| f.puts 'Hello World!' }

Dir.chdir('repo/test.git') { repo.add('foo.txt') }

repo.commit_index('This commit worked!')

The key step is the Dir.chdir block. Hopefully it will work for you too!

Bryan
  • 2,205
  • 1
  • 23
  • 43
0

In my opinion grit is not really following POLA so here is why how to add all changed files. My learning curve here was that Grit returned files (e.g. repo.status.files ) will not work if passed to repo.add. Instead you need to use file names. I needed to go into source code to figure this out.

location = '/foo/bar/my_repo'
repo = Grit::Repo.new(location)
# modified, added, un-tracked files
changed_files = repo.status.files.select { |k,v| (v.type =~ /(M|A)/ || v.untracked) }

Dir.chdir(location) {
  changed_files.each do |changed_file|
    # changed_file here is array, which first element is name of file 
    # e.g. changed_file.first => "example.txt."
    repo.add(changed_file.first)
  end
}

repo.commit_index("Successful commit! yeeeee! ")
Haris Krajina
  • 14,824
  • 12
  • 64
  • 81