質問

少し前に探していたのですが、 Java での埋め込み可能な分散バージョン管理システム、そして私はそれを見つけたと思います JGit, 、これは git の純粋な Java 実装です。ただし、サンプル コードやチュートリアルはあまりありません。

JGit を使用して特定のファイルの HEAD バージョンを取得するにはどうすればよいですか ( svn cat または hg cat するだろうか)?

これには rev-tree ウォーキングが必要だと思いますので、コードサンプルを探しています。

役に立ちましたか?

解決

残念ながらティロの答えは、最新JGitのAPIでは動作しません。ここで私が見つけた解決策があります:

File repoDir = new File("test-git");
// open the repository
Repository repository = new Repository(repoDir);
// find the HEAD
ObjectId lastCommitId = repository.resolve(Constants.HEAD);
// now we have to get the commit
RevWalk revWalk = new RevWalk(repository);
RevCommit commit = revWalk.parseCommit(lastCommitId);
// and using commit's tree find the path
RevTree tree = commit.getTree();
TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tree);
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create(path));
if (!treeWalk.next()) {
  return null;
}
ObjectId objectId = treeWalk.getObjectId(0);
ObjectLoader loader = repository.open(objectId);

// and then one can use either
InputStream in = loader.openStream()
// or
loader.copyTo(out)

私はそれが単純だったなあ。

他のヒント

ここで@directed笑い者からの概念の一部を使用して、@ morisilの答えの簡単なバージョンだとJGit 2.2.0でテストされます:

private String fetchBlob(String revSpec, String path) throws MissingObjectException, IncorrectObjectTypeException,
        IOException {

    // Resolve the revision specification
    final ObjectId id = this.repo.resolve(revSpec);

    // Makes it simpler to release the allocated resources in one go
    ObjectReader reader = this.repo.newObjectReader();

    try {
        // Get the commit object for that revision
        RevWalk walk = new RevWalk(reader);
        RevCommit commit = walk.parseCommit(id);

        // Get the revision's file tree
        RevTree tree = commit.getTree();
        // .. and narrow it down to the single file's path
        TreeWalk treewalk = TreeWalk.forPath(reader, path, tree);

        if (treewalk != null) {
            // use the blob id to read the file's data
            byte[] data = reader.open(treewalk.getObjectId(0)).getBytes();
            return new String(data, "utf-8");
        } else {
            return "";
        }
    } finally {
        reader.release();
    }
}

repoは、他の回答に作成されたオブジェクトリポジトリである。

私はティロさん@やJGit 1.2.0と互換性のあるこれを、取得するmorisilの答え@続きます

File repoDir = new File("test-git/.git");
// open the repository
Repository repo = new Repository(repoDir);
// find the HEAD
Commit head = repo.mapCommit(Constants.HEAD);
// retrieve the tree in HEAD
Tree tree = head.getTree();

// 1.2.0 api version here
// find a file (as a TreeEntry, which contains the blob object id)
TreeWalk treewalk = TreeWalk.forPath(repo, "b/test.txt", tree);
// use the blob id to read the file's data
byte[] data = repo.open(treewalk.getObjectId(0)).getBytes();

私は、Javaのバージョンをテストしていないが、それは動作するはずです。これは、

から変換します
(.getBytes (.open repo (.getObjectId (TreeWalk/forPath repo "b/test.txt" tree) 0)))

のClojureで作業を行い、(頂部と同じセットアップ下記)。

は、自分でそれを考え出しました。 APIは非常に低レベルであるが、それはあまりにも悪くはない。

File repoDir = new File("test-git/.git");
// open the repository
Repository repo = new Repository(repoDir);
// find the HEAD
Commit head = repo.mapCommit(Constants.HEAD);
// retrieve the tree in HEAD
Tree tree = head.getTree();
// find a file (as a TreeEntry, which contains the blob object id)
TreeEntry entry = tree.findBlobMember("b/test.txt");
// use the blob id to read the file's data
byte[] data = repo.openBlob(entry.getId()).getBytes();

というライブラリを書き始めました ギクティヴな これには、JGit を使用して BLOB、コミット、ツリーを操作するための多くのヘルパーが含まれており、MIT ライセンスが付与されており、GitHub で利用できます。

HEADコミットでファイルの内容を取得する

Repository repo = new FileRepository("/repos/project/.git");
String content = BlobUtils.getHeadContent(repo, "src/Buffer.java");

ブランチ上のファイルのコンテンツを取得する

Repository repo = new FileRepository("/repos/project/.git");
String content = BlobUtils.getContent(repo, "master", "src/Buffer.java");

2 つのファイルの差分を比較する

Repository repo = new FileRepository("/repos/project/.git");
ObjectId current = BlobUtils.getId(repo, "master", "Main.java");
ObjectId previous = BlobUtils.getId(repo, "master~1", "Main.java");
Collection<Edit> edit = BlobUtils.diff(repo, previous, current);

提供されるユーティリティのその他の例については、「 お読みください.

JGitチュートリアルのではいくつかの情報があります(が、またどちらもしないことを本当に便利も完了し、彼らは切り替えので、おそらく時代遅れに日食に何のドキュメントはまだ利用できません場合)。

次のように

あなたは与えられたファイルパスの内容を読むことができます。パスが与えられた木の中に見つからなかった場合TreeWalkはのヌルのことができることに注意してください。だから、いくつかの特定の処理が必要です。

public String readFile(RevCommit commit, String filepath) throws IOException {
    try (TreeWalk walk = TreeWalk.forPath(repo, filepath, commit.getTree())) {
        if (walk != null) {
            byte[] bytes = repo.open(walk.getObjectId(0)).getBytes();
            return new String(bytes, StandardCharsets.UTF_8);
        } else {
            throw new IllegalArgumentException("No path found.");
        }
    }
}

ObjectId head = repo.resolve(Constants.HEAD);
RevCommit last = repo.parseCommit(head);
readFile(last, "docs/README.md")

この答えはJGit 4.8.0で記述されます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top