Subject: [ JGIT ] incompatiblity found in DirCache

From: "Adam W. Hawks" <[email-masked]>
Date: Wed, 09 Sep 2009 14:55:39 -0400

When using the DirCache interface to the index you can create a invalid/corrupt tree for git 1.6.5.

The problem seems to be you can add a path to the index that starts with a "/" and DirCache creates a entry with a mode but no path.
This causes git 1.6.5 to fail with a corrupt tree.

The following code will create the problem

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import org.spearce.jgit.dircache.DirCache;
import org.spearce.jgit.dircache.DirCacheBuilder;
import org.spearce.jgit.dircache.DirCacheEntry;
import org.spearce.jgit.lib.Commit;
import org.spearce.jgit.lib.FileMode;
import org.spearce.jgit.lib.ObjectId;
import org.spearce.jgit.lib.ObjectWriter;
import org.spearce.jgit.lib.PersonIdent;
import org.spearce.jgit.lib.RefUpdate;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.lib.RefUpdate.Result;

public class BuildTest
{
	private Repository db;
	
	public static void main(String[] args)
	{
		BuildTest bt = new BuildTest();
		bt.doit();
	}
	
	public void doit()
	{		
		Date when = Calendar.getInstance().getTime();
		File gitDir = new File("gitProblem/.git");
		gitDir.mkdirs();
		try
		{
			db = new Repository(gitDir);
			db.create(true);
			DirCache dirc = DirCache.newInCore();
			DirCacheBuilder dcb = dirc.builder();
			byte[] data = "Some File data".getBytes();
			ObjectWriter ow = new ObjectWriter(db);
			ObjectId dataId = ow.writeBlob(data);
			DirCacheEntry newEntry = new DirCacheEntry("/someDir/someFile");
			newEntry.setAssumeValid(false);
			newEntry.setFileMode(FileMode.REGULAR_FILE);
			newEntry.setLastModified(when.getTime());
			newEntry.setLength(data.length);
			newEntry.setObjectId(dataId);
			dcb.add(newEntry );
			dcb.finish();
			dirc = dcb.getDirCache();
			PersonIdent pi = new PersonIdent("someonw","someone@somewhere",when,TimeZone.getDefault());
			ObjectId tree = dirc.writeTree(new ObjectWriter(db));
			Commit commit = new Commit(db);
			commit.setAuthor(pi);
			commit.setCommitter(pi);
			commit.setMessage("This causes a corrupt tree");
			commit.setTreeId(tree);
			commit.commit();
			ObjectId cid = commit.getCommitId();
			RefUpdate ru = db.updateRef("refs/heads/master");		
			ru.setExpectedOldObjectId(ObjectId.zeroId());
			ru.setNewObjectId(cid);
			ru.setRefLogIdent(pi);
			ru.setRefLogMessage("some reflog message", true);
			Result result = ru.update();
			System.out.println("Result = "+result.toString());
		}
		catch (IOException e)
		{
			System.out.println(e);
			e.printStackTrace();
			System.exit(1);
		}
	}	
}