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?
(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.