简体   繁体   中英

JGit - Contents of Commit Into String

I need to store the contents of a commit, this would be the difference from eg. master to the latest commit, in a string.

How to show changes between commits with JGit The bottom answer is very similar to what I want

This is the code from the link

RevCommit headCommit = getHeadCommit(repository);
    RevCommit diffWith = headCommit.getParent(0);
    FileOutputStream stdout = new FileOutputStream(FileDescriptor.out);
    try (DiffFormatter diffFormatter = new DiffFormatter(stdout)) {
        diffFormatter.setRepository(repository);
        for (DiffEntry entry : diffFormatter.scan(diffWith, headCommit)) {
            diffFormatter.format(diffFormatter.toFileHeader(entry));
        }
    }
diffFormatter.format(diffFormatter.toFileHeader(entry));

The format() method is void, and there doesnt seem to be a way to return a string or some sort of outputstream.

I would expect there to be something along the lines of

String commitDiff = diffFormatter.getCommitContents(entry).toString();

I understand this doesnt exist in the library, but there must be something that can put the contents of a commit into something that can be turned into a String

The code was changed to

OutputStream output = new OutputStream() {
    private StringBuilder string = new StringBuilder();
    @Override
    public void write(int b) throws IOException {
        this.string.append((char) b );
    }

    public String toString(){
        return this.string.toString();
    }
};
RevCommit headCommit = getHeadCommit(repository);
RevCommit diffWith = headCommit.getParent(0);
try (DiffFormatter diffFormatter = new DiffFormatter(output)) {
    diffFormatter.setRepository(repository);
    for (DiffEntry entry : diffFormatter.scan(diffWith, headCommit)) {
        diffFormatter.format(diffFormatter.toFileHeader(entry));
    }
String strings = output.toString();
System.out.println(strings);

It is a long way of doing it but it proves it can be done This has now stored the difference into the string

strings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM