views:

83

answers:

3

Is there a way to programmatically download a single file from a remote git repository, in Java?

  1. I prefer a solution which uses as little bandwidth as possible, preferably only downloading that single file. I do not need to browse the repository, I already have the file's path.
  2. I prefer a solution which does not depend on other applications (e.g. an installation of another git client on the machine). A Java library which contains a git client implementation itself would be optimal.

I was able to do something similar with Subversion using SVNKit and I've seen there is a pure java implementation of git (eclipse's JGit) which might be able to do something similar, so I hope there is a positive answer; though from what I understand about how git works - allowing updates only from local repositories - this could prove to be problematic.

A: 

Quoth git-clone(1):

--depth depth

Create a shallow clone with a history truncated to the specified number of revisions. A shallow repository has a number of limitations (you cannot clone or fetch from it, nor push from nor into it), but is adequate if you are only interested in the recent history of a large project with a long history, and would want to send in fixes as patches.

So the granularity is a directory but you can limit the revision history.

msw
You could also use `--no-checkout` to avoid creating the entire work directory. No bandwidth effect, but saves a lot of file creation.
Jefromi
+1  A: 

What sort of access to do you have to the remote repository? Is it via SSH, can you call commands? If so, you can just invoke git show HEAD:$path_to_file.

If you cannot invoke commands on that machine, it is still entirely possible to do this, but you'll have to understand the Git repository format. (That’s much less scary than it sounds, since it is very simple by design. Unlike eg. Subversion, the repository format is not intended as a black box.)

Aristotle Pagaltzis
If you can run gitweb on the remote, you could do it through that too.
Jefromi
+4  A: 

git isn't really designed for single file access from a remote repository but you can abuse git archive for this. The downside is that you have to download a "tree" rather than just the blob that you need.

E.g.

git archive --remote=url://to.git.repo branch path/to/dir | tar -x file

As an alternative, if you have gitweb set up on the remote repository you can use a simple curl or wget command to download any file in its "raw" format.

Charles Bailey
That is an awesome kludge.
Jefromi
Note that for `git://` protocol you have, from what I remember, to explicitely enable appropriate service to allow remote `git archive` access.
Jakub Narębski