0

I'm trying to wrap my head around using Grit to write to a Git repository. I can easily create a repo and make a commit:

repo = Repo.init_bare("grit.git")
index = Index.new(repo)
index.add('myfile.txt', 'This is the content')
index.commit('first commit')

I can also easily make the second commit, using the first commit as parent:

index.add('myotherfile.txt', 'This is some other content')
index.commit("second commit", [repo.commits.first])

But now how do I get the content of those 2 files without traversing through the entire commit history? Isn't there a smarter way for me to get the current state of the files in a repo?

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
Ronze
  • 1,544
  • 2
  • 18
  • 33

1 Answers1

1
(repo.tree / 'myfile.txt').data

Specifically, the tree method (which can take any commit, but defaults to master) returns a Tree. Tree has a convenient / method which returns a Blob or Tree depending what filename you pass in. Finally, Blob has a data method that returns the exact data.

EDIT: If you want a list of all the filenames in the repo (which may be an expensive operation), one way is:

all_files = repo.status.map { |stat_file| stat_file.path }

This assumes everything is tracked. If you're not sure, you can filter on the untracked attribute.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • But what if I don't know what my file names are? What if it is a repo with 1000 files? Is there a way to do something like repo.tree.all? – Ronze Mar 13 '11 at 04:38
  • Thanks! I think my problem was that I didn't call read_tree on the index before committing the second time (it was in another controller) – Ronze Mar 13 '11 at 05:03