Java Code Examples for org.eclipse.jgit.lib.ObjectId

The following are top voted examples for showing how to use org.eclipse.jgit.lib.ObjectId. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: forweaver2.0   File: GitUtil.java   View source code 7 votes vote down vote up
/** 커밋을 입력받으면 당시 파일들을 압축하여 사용자에게 보내줌.
 * @param commitName
 * @param format
 * @param response
 */
public void getRepositoryZip(String commitName,String format, HttpServletResponse response) {

	try {
		ArchiveCommand.registerFormat("zip", new ZipFormat());
		ArchiveCommand.registerFormat("tar", new TarFormat());
		ObjectId revId = this.localRepo.resolve(commitName);
		git.archive().setOutputStream(response.getOutputStream())
		.setFormat(format)
		.setTree(revId)
		.call();

		ArchiveCommand.unregisterFormat("zip");
		ArchiveCommand.unregisterFormat("tar");
		response.flushBuffer();
	} catch (Exception e) {
		System.err.println(e.getMessage());
	}

}
 
Example 2
Project: forweaver2.0   File: GitInfo.java   View source code 6 votes vote down vote up
/**
 * Get line impact of author
 *
 * @param name
 * @return stats
 */
public LineStats getAuthorLineImpact(String name) {
	Set<String> emails = namesToEmails.get(name);
	if (emails == null)
		return new LineStats();
	LineStats stats = new LineStats();
	for (String email : emails) {
		UserCommitActivity activity = authorHistogram.getActivity(email);
		if (activity == null)
			continue;
		for (ObjectId commit : activity.getIds()) {
			CommitImpact impact = mostLines.get(commit);
			if (impact != null) {
				stats.add += impact.getAdd();
				stats.edit += impact.getEdit();
				stats.delete += impact.getDelete();
			}
		}
	}
	return stats;
}
 
Example 3
Project: forweaver2.0   File: GitUtil.java   View source code 6 votes vote down vote up
/** 파일주소와 커밋아이디를 바탕으로 디렉토리인지 검사함.
 * @param commitID
 * @param filePath
 * @return
 */
public boolean isDirectory(String commitID, String filePath){
	if(filePath.length() == 0)
		return true;
	try{
		ObjectId revId = this.localRepo.resolve(commitID);
		TreeWalk treeWalk = new TreeWalk(this.localRepo);
		treeWalk.addTree(new RevWalk(this.localRepo).parseTree(revId));
		treeWalk.setRecursive(true);
		while (treeWalk.next()) {
			if(treeWalk.getPathString().equals(filePath)){
				return false;
			}
		}
		treeWalk.reset(new RevWalk(this.localRepo).parseTree(revId));
		while (treeWalk.next()) {
			if(treeWalk.getPathString().startsWith(filePath)){
				return true;
			}
		}
	}catch(Exception e){
		return false;
	}
	return false;
}
 
Example 4
Project: oxygen-git-plugin   File: GitAccess.java   View source code 6 votes vote down vote up
/**
 * Returns for the given submodule the SHA-1 commit id for the Index if the
 * given index boolean is <code>true</code> or the SHA-1 commit id for the
 * HEAD if the given index boolean is <code>false</code>
 * 
 * @param submodulePath
 *          - the path to get the submodule
 * @param index
 *          - boolean to determine what commit id to return
 * @return the SHA-1 id
 */
public ObjectId submoduleCompare(String submodulePath, boolean index) {
	try {
		SubmoduleStatus submoduleStatus = git.submoduleStatus().addPath(submodulePath).call().get(submodulePath);
		if (submoduleStatus != null) {
		  if (index) {
		    return submoduleStatus.getIndexId();
		  } else {
		    return submoduleStatus.getHeadId();
		  }
		}
	} catch (GitAPIException e) {
		if (logger.isDebugEnabled()) {
			logger.debug(e, e);
		}
	}
	return null;
}
 
Example 5
Project: gmds   File: Commands.java   View source code 6 votes vote down vote up
/**
 * 
 * @param commitBuilder
 * @param treeId
 * @param repo
 * @return
 * @throws UnsupportedEncodingException
 * @throws IOException 
 */
public static ObjectId commit(CommitBuilder commitBuilder, ObjectId treeId, Repository repo) throws UnsupportedEncodingException, IOException {
    commitBuilder.setTreeId(treeId);
    commitBuilder.setMessage(System.currentTimeMillis() + ": My commit!\n");
    PersonIdent person = new PersonIdent("Alex", "[email protected]");
    commitBuilder.setAuthor(person);
    commitBuilder.setCommitter(person);

    commitBuilder.build();

    ObjectInserter commitInserter = repo.newObjectInserter();
    ObjectId commitId = commitInserter.insert(commitBuilder);
    commitInserter.flush();

    updateMasterRecord(repo, commitId);

    System.out.println("Commit Object ID: " + commitId.getName());

    return commitId;
}
 
Example 6
Project: incubator-netbeans   File: CherryPickCommand.java   View source code 6 votes vote down vote up
private ObjectId getOriginalCommit () throws GitException {
    Repository repository = getRepository();
    File seqHead = new File(getSequencerFolder(), SEQUENCER_HEAD);
    ObjectId originalCommitId = null;
    if (seqHead.canRead()) {
        try {
            byte[] content = IO.readFully(seqHead);
            if (content.length > 0) {
                originalCommitId = ObjectId.fromString(content, 0);
            }
            if (originalCommitId != null) {
                originalCommitId = repository.resolve(originalCommitId.getName() + "^{commit}");
            }
        } catch (IOException e) {
        }
    }
    return originalCommitId;
}
 
Example 7
Project: gitplex-mit   File: DefaultPullRequestManager.java   View source code 6 votes vote down vote up
@Transactional
@Override
public void open(PullRequest request) {
	request.setNumber(getNextNumber(request.getTargetProject()));
	dao.persist(request);
	
	RefUpdate refUpdate = GitUtils.getRefUpdate(request.getTargetProject().getRepository(), request.getBaseRef());
	refUpdate.setNewObjectId(ObjectId.fromString(request.getBaseCommitHash()));
	GitUtils.updateRef(refUpdate);
	
	refUpdate = GitUtils.getRefUpdate(request.getTargetProject().getRepository(), request.getHeadRef());
	refUpdate.setNewObjectId(ObjectId.fromString(request.getHeadCommitHash()));
	GitUtils.updateRef(refUpdate);
	
	for (PullRequestUpdate update: request.getUpdates()) {
		pullRequestUpdateManager.save(update, false);
	}
	
	for (ReviewInvitation invitation: request.getReviewInvitations())
		reviewInvitationManager.save(invitation);

	checkAsync(request);
	
	listenerRegistry.post(new PullRequestOpened(request));
}
 
Example 8
Project: gmds   File: Utils.java   View source code 6 votes vote down vote up
/**
     *
     * @param datarepo
     * @param tree
     * @param conn
     * @param clmnTree
     * @return
     * @throws SQLException
     * @throws IOException
     */
    public static ObjectId dataTreeCommit(Repository datarepo, TreeFormatter tree, Connection conn, Boolean clmnTree) throws SQLException, IOException {
        DatabaseMetaData dbmd = conn.getMetaData();
//        ObjectJson dbmdJson = new ObjectJson();
        String mapString = metaDbInfo(dbmd);
        
        // Build Db_Info object, general info about Database
        ObjectInserter objectInserter = datarepo.newObjectInserter();
        ObjectId blobId = objectInserter.insert(Constants.OBJ_BLOB, mapString.getBytes());
        objectInserter.flush();

        tree.append("DATABASE", FileMode.REGULAR_FILE, blobId);
        
        // Continue building Database Tree
        Utils.putTableMeta(datarepo, conn, dbmd, objectInserter, tree, clmnTree);

        ObjectId treeId = objectInserter.insert(tree);
        objectInserter.flush();

        System.out.println("Tree ID: " + treeId.getName());

        return treeId;
    }
 
Example 9
Project: gitplex-mit   File: DefaultCommitInfoManager.java   View source code 6 votes vote down vote up
@Nullable
@Override
public ObjectId getLastCommit(Project project) {
	Environment env = getEnv(project.getId().toString());
	Store defaultStore = getStore(env, DEFAULT_STORE);

	return env.computeInTransaction(new TransactionalComputable<ObjectId>() {
		
		@Override
		public ObjectId compute(Transaction txn) {
			byte[] bytes = getBytes(defaultStore.get(txn, LAST_COMMIT_KEY));
			return bytes != null? ObjectId.fromRaw(bytes): null;
		}
		
	});
}
 
Example 10
Project: incubator-netbeans   File: CheckoutTest.java   View source code 6 votes vote down vote up
private void checkJGitFix (String branch, File file) throws Exception {
    ObjectId headTree = null;
    try {
        headTree = Utils.findCommit(repository, Constants.HEAD).getTree();
    } catch (GitException.MissingObjectException ex) { }

    DirCache cache = repository.lockDirCache();
    RevCommit commit;
    commit = Utils.findCommit(repository, branch);
    DirCacheCheckout dco = new DirCacheCheckout(repository, headTree, cache, commit.getTree());
    dco.setFailOnConflict(false);
    dco.checkout();
    if (file.exists()) {
        // and do not forget to remove WA in checkout command when JGit is fixed.
        fail("Hey, JGit is fixed, why don't you fix me as well?");
    }
    cache.unlock();
}
 
Example 11
Project: gmds   File: Commands.java   View source code 6 votes vote down vote up
/**
 *
 * @param repo
 * @param objectId
 * @throws IOException
 */
public static void updateMasterRecord(Repository repo, ObjectId objectId) throws IOException {

    RefUpdate refUpdate = repo.updateRef(Constants.HEAD);
    refUpdate.setNewObjectId(objectId);
    final RefUpdate.Result result = refUpdate.forceUpdate();

    switch (result) {
        case NEW:
            System.out.println("New commit!\n");
            break;
        case FORCED:
            System.out.println("Forced change commit!\n");
            break;
        default: {
            System.out.println(result.name());
        }
    }
}
 
Example 12
Project: centraldogma   File: GitRepository.java   View source code 6 votes vote down vote up
@VisibleForTesting
static void doRefUpdate(org.eclipse.jgit.lib.Repository jGitRepository, RevWalk revWalk,
                        String ref, ObjectId commitId) throws IOException {

    if (ref.startsWith(Constants.R_TAGS)) {
        final Ref oldRef = jGitRepository.exactRef(ref);
        if (oldRef != null) {
            throw new StorageException("tag ref exists already: " + ref);
        }
    }

    final RefUpdate refUpdate = jGitRepository.updateRef(ref);
    refUpdate.setNewObjectId(commitId);

    final Result res = refUpdate.update(revWalk);
    switch (res) {
        case NEW:
        case FAST_FORWARD:
            // Expected
            break;
        default:
            throw new StorageException("unexpected refUpdate state: " + res);
    }
}
 
Example 13
Project: centraldogma   File: GitRepository.java   View source code 6 votes vote down vote up
private void notifyWatchers(Revision newRevision, ObjectId prevTreeId, ObjectId nextTreeId) {
    final List<DiffEntry> diff = compareTrees(prevTreeId, nextTreeId, TreeFilter.ALL);
    for (DiffEntry e: diff) {
        switch (e.getChangeType()) {
        case ADD:
            commitWatchers.notify(newRevision, e.getNewPath());
            break;
        case MODIFY:
        case DELETE:
            commitWatchers.notify(newRevision, e.getOldPath());
            break;
        default:
            throw new Error();
        }
    }
}
 
Example 14
Project: centraldogma   File: GitRepositoryTest.java   View source code 6 votes vote down vote up
private static void testDoUpdateRef(String ref, ObjectId commitId, boolean tagExists) throws Exception {
    final org.eclipse.jgit.lib.Repository jGitRepo = mock(org.eclipse.jgit.lib.Repository.class);
    final RevWalk revWalk = mock(RevWalk.class);
    final RefUpdate refUpdate = mock(RefUpdate.class);

    when(jGitRepo.exactRef(ref)).thenReturn(tagExists ? mock(Ref.class) : null);
    when(jGitRepo.updateRef(ref)).thenReturn(refUpdate);

    when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.NEW);
    GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId);

    when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.FAST_FORWARD);
    GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId);

    when(refUpdate.update(revWalk)).thenReturn(RefUpdate.Result.LOCK_FAILURE);
    assertThatThrownBy(() -> GitRepository.doRefUpdate(jGitRepo, revWalk, ref, commitId))
            .isInstanceOf(StorageException.class);
}
 
Example 15
Project: centraldogma   File: CommitIdDatabaseTest.java   View source code 6 votes vote down vote up
@Test
public void simpleAccess() throws Exception {
    final int numCommits = 10;
    final ObjectId[] expectedCommitIds = new ObjectId[numCommits + 1];
    for (int i = 1; i <= numCommits; i++) {
        final Revision revision = new Revision(i);
        final ObjectId commitId = randomCommitId();
        expectedCommitIds[i] = commitId;
        db.put(revision, commitId);
        assertThat(db.headRevision()).isEqualTo(revision);
    }

    for (int i = 1; i <= numCommits; i++) {
        assertThat(db.get(new Revision(i))).isEqualTo(expectedCommitIds[i]);
    }

    assertThatThrownBy(() -> db.get(Revision.HEAD))
            .isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining("absolute revision");
    assertThatThrownBy(() -> db.get(new Revision(numCommits + 1)))
            .isInstanceOf(RevisionNotFoundException.class);
}
 
Example 16
Project: gitplex-mit   File: BlobEditsTest.java   View source code 6 votes vote down vote up
@Test
public void shouldFailIfNewPathIsNotUnderTreeWhenRename() throws IOException {
	createDir("client");
	addFileAndCommit("client/a.java", "a", "add a");
	addFileAndCommit("client/b.java", "b", "add b");
	
	createDir("server/src/com/example/a");
	createDir("server/src/com/example/b");
	addFileAndCommit("server/src/com/example/a/a.java", "a", "add a");
	addFileAndCommit("server/src/com/example/b/b.java", "b", "add b");
	
	String refName = "refs/heads/master";
	ObjectId oldCommitId = git.getRepository().resolve(refName);
	
	Map<String, BlobContent> newBlobs = new HashMap<>();
	newBlobs.put("client/a.java/a.java", new BlobContent.Immutable("a".getBytes(), FileMode.REGULAR_FILE));
	BlobEdits edits = new BlobEdits(Sets.newHashSet("server/src/com/example/a/a.java"), newBlobs);
	try {
		edits.commit(git.getRepository(), refName, oldCommitId, oldCommitId, user, "test rename tree");
		assertTrue("A NotTreeException should be thrown", false);
	} catch (NotTreeException e) {
	}
}
 
Example 17
Project: RefDiff   File: GitHelper.java   View source code 6 votes vote down vote up
public RevWalk fetchAndCreateNewRevsWalk(Repository repository, String branch) throws Exception {
	List<ObjectId> currentRemoteRefs = new ArrayList<ObjectId>();
	for (Ref ref : repository.getAllRefs().values()) {
		String refName = ref.getName();
		if (refName.startsWith(REMOTE_REFS_PREFIX)) {
			currentRemoteRefs.add(ref.getObjectId());
		}
	}
	
	List<TrackingRefUpdate> newRemoteRefs = this.fetch(repository);
	
	RevWalk walk = new RevWalk(repository);
	for (TrackingRefUpdate newRef : newRemoteRefs) {
		if (branch == null || newRef.getLocalName().endsWith("/" + branch)) {
			walk.markStart(walk.parseCommit(newRef.getNewObjectId()));
		}
	}
	for (ObjectId oldRef : currentRemoteRefs) {
		walk.markUninteresting(walk.parseCommit(oldRef));
	}
	walk.setRevFilter(commitsFilter);
	return walk;
}
 
Example 18
Project: gitplex-mit   File: DefaultProjectManager.java   View source code 6 votes vote down vote up
private Set<String> getChangedFiles(Project project, ObjectId oldObjectId, ObjectId newObjectId) {
	Set<String> changedFiles = new HashSet<>();
	try (TreeWalk treeWalk = new TreeWalk(project.getRepository())) {
		treeWalk.setFilter(TreeFilter.ANY_DIFF);
		treeWalk.setRecursive(true);
		RevCommit oldCommit = project.getRevCommit(oldObjectId);
		RevCommit newCommit = project.getRevCommit(newObjectId);
		treeWalk.addTree(oldCommit.getTree());
		treeWalk.addTree(newCommit.getTree());
		while (treeWalk.next()) {
			changedFiles.add(treeWalk.getPathString());
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
	return changedFiles;
}
 
Example 19
Project: gitplex-mit   File: BlobEditsTest.java   View source code 6 votes vote down vote up
@Test
public void testRemoveFile() throws IOException {
	createDir("client");
	addFileAndCommit("client/a.java", "a", "add a");
	addFileAndCommit("client/b.java", "b", "add b");
	
	createDir("server/src/com/example/a");
	createDir("server/src/com/example/b");
	addFileAndCommit("server/src/com/example/a/a.java", "a", "add a");
	addFileAndCommit("server/src/com/example/b/b.java", "b", "add b");
	
	String refName = "refs/heads/master";
	ObjectId oldCommitId = git.getRepository().resolve(refName);
	
	BlobEdits edits = new BlobEdits(Sets.newHashSet("/server/src/com/example/a//a.java"), Maps.newHashMap());
	ObjectId newCommitId = edits.commit(git.getRepository(), refName, oldCommitId, oldCommitId, user, "test delete");
	
	try (RevWalk revWalk = new RevWalk(git.getRepository())) {
		RevTree revTree = revWalk.parseCommit(newCommitId).getTree();
		assertNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/a", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/b/b.java", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/a.java", revTree));
		assertNotNull(TreeWalk.forPath(git.getRepository(), "client/b.java", revTree));
	}
}
 
Example 20
Project: gmds   File: Utils.java   View source code 6 votes vote down vote up
/**
 *
 * @param columns
 * @param objectInserter
 * @param tblTree
 * @param walkTbl
 * @return
 * @throws SQLException
 * @throws IOException
 */
public static ObjectId putColumnMetaAsTree(ResultSet columns, 
        ObjectInserter objectInserter, TreeFormatter tblTree, RevWalk walkTbl) throws SQLException, IOException {

    // Add tree for the column Metadata
    TreeFormatter clmnMetaTree = new TreeFormatter();

    // Build tree for column attributs
    buildMetaTree(columns, Consts.COLUMN_META_ATTRIBUTES, objectInserter, clmnMetaTree);

    ObjectId clmnMetaTreeId = objectInserter.insert(clmnMetaTree);
    objectInserter.flush();

    tblTree.append(Consts.COLUMN_META, walkTbl.parseTree(clmnMetaTreeId));

    // Add empty tree for the column content
    TreeFormatter clmnDataTree = new TreeFormatter();
    ObjectId clmnDataTreeId = objectInserter.insert(clmnDataTree);
    objectInserter.flush();

    tblTree.append(Consts.COLUMN_DATA, walkTbl.parseTree(clmnDataTreeId));

    return clmnMetaTreeId;
}
 
Example 21
Project: pdi-git-plugin   File: UIGit.java   View source code 6 votes vote down vote up
private boolean mergeBranch( String value, String mergeStrategy ) {
  try {
    ObjectId obj = git.getRepository().resolve( value );
    MergeResult result = git.merge()
      .include( obj )
      .setStrategy( MergeStrategy.get( mergeStrategy ) )
      .call();
    if ( result.getMergeStatus().isSuccessful() ) {
      showMessageBox( BaseMessages.getString( PKG, "Dialog.Success" ), BaseMessages.getString( PKG, "Dialog.Success" ) );
      return true;
    } else {
      showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), result.getMergeStatus().toString() );
      if ( result.getMergeStatus() == MergeStatus.CONFLICTING ) {
        result.getConflicts().keySet().forEach( path -> {
          checkout( path, Constants.HEAD, ".ours" );
          checkout( path, getExpandedName( value, IVCS.TYPE_BRANCH ), ".theirs" );
        } );
        return true;
      }
    }
  } catch ( Exception e ) {
    showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() );
  }
  return false;
}
 
Example 22
Project: gitplex-mit   File: BlobEditsTest.java   View source code 6 votes vote down vote up
@Test
public void testObsoleteOldCommit() throws IOException {
	addFileAndCommit("a.java", "a", "add a");
	
	String refName = "refs/heads/master";
	ObjectId oldCommitId = git.getRepository().resolve(refName);
	
	addFileAndCommit("b.java", "b", "add b");
	
	ObjectId newCommitId = git.getRepository().resolve(refName);

	Map<String, BlobContent> newBlobs = new HashMap<>();
	newBlobs.put("/server/src/com/example/c/c.java", new BlobContent.Immutable("c".getBytes(), FileMode.REGULAR_FILE));
	BlobEdits edits = new BlobEdits(Sets.newHashSet(), newBlobs);
	try {
		edits.commit(git.getRepository(), refName, oldCommitId, oldCommitId, user, "test add");
		assertTrue("An ObsoleteCommitException should be thrown", false);
	} catch (ObsoleteCommitException e) {
		assertTrue(newCommitId.equals(e.getOldCommitId()));
	}
}
 
Example 23
Project: oxygen-git-plugin   File: GitAccess.java   View source code 6 votes vote down vote up
/**
 * Gets the loader for a file from a specified commit and its path
 * 
 * @param commit
 *          - the commit from which to get the loader
 * @param path
 *          - the path to the file
 * @return the loader
 * @throws MissingObjectException
 * @throws IncorrectObjectTypeException
 * @throws CorruptObjectException
 * @throws IOException
 */
public ObjectLoader getLoaderFrom(ObjectId commit, String path)
		throws IOException {
	Repository repository = git.getRepository();
	RevWalk revWalk = new RevWalk(repository);
	RevCommit revCommit = revWalk.parseCommit(commit);
	// and using commit's tree find the path
	RevTree tree = revCommit.getTree();
	TreeWalk treeWalk = new TreeWalk(repository);
	treeWalk.addTree(tree);
	treeWalk.setRecursive(true);
	treeWalk.setFilter(PathFilter.create(path));

	ObjectLoader loader = null;
	if (treeWalk.next()) {
		ObjectId objectId = treeWalk.getObjectId(0);
		loader = repository.open(objectId);
	}

	treeWalk.close();
	revWalk.close();
	return loader;
}
 
Example 24
Project: gitplex-mit   File: DefaultProjectManager.java   View source code 6 votes vote down vote up
@Override
public boolean isPushNeedsQualityCheck(User user, Project project, String branch, ObjectId oldObjectId, ObjectId newObjectId) {
	BranchProtection branchProtection = project.getBranchProtection(branch);
	if (branchProtection != null) {
		if (branchProtection.getReviewAppointment(project) != null 
				&& !branchProtection.getReviewAppointment(project).matches(user)) {
			return true;
		}

		Map<String, Verification> verifications = verificationManager.getVerifications(project, newObjectId.name());
		if (!verifications.keySet().containsAll(branchProtection.getVerifications()))
			return true;
		
		for (String changedFile: getChangedFiles(project, oldObjectId, newObjectId)) {
			FileProtection fileProtection = branchProtection.getFileProtection(changedFile);
			if (fileProtection != null && !fileProtection.getReviewAppointment(project).matches(user))
				return true;
		}
	}
	return false;
}
 
Example 25
Project: RefDiff   File: GitServiceImpl.java   View source code 5 votes vote down vote up
@Override
public RevCommit resolveCommit(Repository repository, String commitId) throws Exception {
    ObjectId oid = repository.resolve(commitId);
    if (oid == null) {
        return null;
    }
    try (RevWalk rw = new RevWalk(repository)) {
        return rw.parseCommit(oid);
    } catch (MissingObjectException e) {
    	return null;
    }
   }
 
Example 26
Project: gitplex-mit   File: Project.java   View source code 5 votes vote down vote up
public InputStream getInputStream(BlobIdent ident) {
	try (RevWalk revWalk = new RevWalk(getRepository())) {
		ObjectId commitId = getObjectId(ident.revision);
		RevTree revTree = revWalk.parseCommit(commitId).getTree();
		TreeWalk treeWalk = TreeWalk.forPath(getRepository(), ident.path, revTree);
		if (treeWalk != null) {
			ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
			return objectLoader.openStream();
		} else {
			throw new ObjectNotFoundException("Unable to find blob path '" + ident.path + "' in revision '" + ident.revision + "'");
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 27
Project: incubator-netbeans   File: GitMergeResult.java   View source code 5 votes vote down vote up
private String[] getMergedCommits (MergeResult result) {
    ObjectId[] mergedObjectIds = result.getMergedCommits();
    String[] commits = new String[mergedObjectIds.length];
    for (int i = 0; i < mergedObjectIds.length; ++i) {
        commits[i] = ObjectId.toString(mergedObjectIds[i]);
    }
    return commits;
}
 
Example 28
Project: incubator-netbeans   File: StatusCommand.java   View source code 5 votes vote down vote up
private Map<String, DiffEntry> detectRenames (Repository repository, DirCache cache, ObjectId commitId) {
    List<DiffEntry> entries;
    TreeWalk treeWalk = new TreeWalk(repository);
    try {
        treeWalk.setRecursive(true);
        treeWalk.reset();
        if (commitId != null) {
            treeWalk.addTree(new RevWalk(repository).parseTree(commitId));
        } else {
            treeWalk.addTree(new EmptyTreeIterator());
        }
        // Index
        treeWalk.addTree(new DirCacheIterator(cache));
        treeWalk.setFilter(TreeFilter.ANY_DIFF);
        entries = DiffEntry.scan(treeWalk);
        RenameDetector d = new RenameDetector(repository);
        d.addAll(entries);
        entries = d.compute();
    } catch (IOException ex) {
        entries = Collections.<DiffEntry>emptyList();
    } finally {
        treeWalk.release();
    }
    Map<String, DiffEntry> renames = new HashMap<String, DiffEntry>();
    for (DiffEntry e : entries) {
        if (e.getChangeType().equals(DiffEntry.ChangeType.COPY) || e.getChangeType().equals(DiffEntry.ChangeType.RENAME)) {
            renames.put(e.getNewPath(), e);
        }
    }
    return renames;
}
 
Example 29
Project: incubator-netbeans   File: Utils.java   View source code 5 votes vote down vote up
public static RevCommit findCommit (Repository repository, String revision, RevWalk walk) throws GitException.MissingObjectException, GitException {
    ObjectId commitId = parseObjectId(repository, revision);
    if (commitId == null) {
        throw new GitException.MissingObjectException(revision, GitObjectType.COMMIT);
    }
    return findCommit(repository, commitId, walk);
}
 
Example 30
Project: incubator-netbeans   File: Utils.java   View source code 5 votes vote down vote up
/**
 * Transforms references into pairs of tag name/id
 * @param allRefs all references found
 * @return 
 */
public static Map<String, String> refsToTags (Collection<Ref> allRefs) {
    Map<String, String> tags = new LinkedHashMap<String, String>();
    
    // get all refs/tags
    for (final Ref ref : RefComparator.sort(allRefs)) {
        String refName = ref.getLeaf().getName();
        if (refName.startsWith(Constants.R_TAGS)) {
            String name = refName.substring(Constants.R_TAGS.length());
            tags.put(name, ObjectId.toString(ref.getLeaf().getObjectId()));
        }
    }
    return tags;
}
 
Example 31
Project: incubator-netbeans   File: GitTransportUpdate.java   View source code 5 votes vote down vote up
GitTransportUpdate (URIish uri, RemoteRefUpdate update, Map<String, GitBranch> remoteBranches) {
    this.localName = stripRefs(update.getSrcRef());
    this.remoteName = stripRefs(update.getRemoteName());
    this.oldObjectId = getOldRevisionId(remoteBranches.get(remoteName));
    this.newObjectId = update.getNewObjectId() == null || ObjectId.zeroId().equals(update.getNewObjectId()) ? null : update.getNewObjectId().getName();
    this.result = GitRefUpdateResult.valueOf(update.getStatus().name());
    this.uri = uri.toString();
    this.type = getType(update.getRemoteName());
}
 
Example 32
Project: oxygen-git-plugin   File: GitAccess.java   View source code 5 votes vote down vote up
/**
 * Finds the last local commit in the repository
 * 
 * @return the last local commit
 */
public ObjectId getLastLocalCommit() {
	Repository repo = git.getRepository();
	try {
		return repo.resolve("HEAD^{commit}");
	} catch (IOException e) {
		if (logger.isDebugEnabled()) {
			logger.debug(e, e);
		}
	}
	return null;
}
 
Example 33
Project: incubator-netbeans   File: AddTest.java   View source code 5 votes vote down vote up
public void testAddNested () throws Exception {
    File f = new File(workDir, "f");
    write(f, "file");
    
    GitClient client = getClient(workDir);
    client.add(new File[] { f }, NULL_PROGRESS_MONITOR);
    client.commit(new File[] { f }, "init commit", null, null, NULL_PROGRESS_MONITOR);
    
    Thread.sleep(1100);
    File nested = new File(workDir, "nested");
    nested.mkdirs();
    File f2 = new File(nested, "f");
    write(f2, "file");
    GitClient clientNested = getClient(nested);
    clientNested.init(NULL_PROGRESS_MONITOR);
    clientNested.add(new File[] { f2 }, NULL_PROGRESS_MONITOR);
    clientNested.commit(new File[] { f2 }, "aaa", null, null, NULL_PROGRESS_MONITOR);
    write(f2, "change");
    
    Thread.sleep(1000);
    client.add(new File[] { workDir }, NULL_PROGRESS_MONITOR);
    Map<File, GitStatus> statuses = client.getStatus(new File[] { workDir }, NULL_PROGRESS_MONITOR);
    assertEquals(2, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
    // nested should be added as gitlink
    assertStatus(statuses, workDir, nested, true, Status.STATUS_ADDED, Status.STATUS_NORMAL, Status.STATUS_ADDED, false);
    DirCacheEntry e = repository.readDirCache().getEntry("nested");
    assertEquals(FileMode.GITLINK, e.getFileMode());
    assertEquals(nested.length(), e.getLength());
    assertNotSame(ObjectId.zeroId().name(), e.getObjectId().getName());
    
    statuses = clientNested.getStatus(new File[] { nested }, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, nested, f2, true, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, Status.STATUS_MODIFIED, false);
}
 
Example 34
Project: gmds   File: Commands.java   View source code 5 votes vote down vote up
/**
 * 
 * @param repo
 * @param lastCommitId
 * @return
 * @throws LargeObjectException
 * @throws IOException 
 */
public static ObjectId getLastCommitTreeId(Repository repo, ObjectId lastCommitId) throws LargeObjectException, IOException {

    if (lastCommitId == null) {
        return null;
    } else {
        ObjectReader objectReader = repo.newObjectReader();
        ObjectLoader objectLoader = objectReader.open(lastCommitId);
        RevCommit oldCommit = RevCommit.parse(objectLoader.getBytes());

        return oldCommit.getTree().getId();
    }
}
 
Example 35
Project: centraldogma   File: GitRepository.java   View source code 5 votes vote down vote up
/**
 * Compares the old tree and the new tree to get the list of the affected files.
 */
private List<DiffEntry> compareTrees(ObjectId prevTreeId, ObjectId nextTreeId, TreeFilter filter) {
    try (DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE)) {
        diffFormatter.setRepository(jGitRepository);
        diffFormatter.setPathFilter(filter);

        return diffFormatter.scan(prevTreeId, nextTreeId);
    } catch (IOException e) {
        throw new StorageException("failed to compare two trees: " + prevTreeId + " vs. " + nextTreeId, e);
    }
}
 
Example 36
Project: centraldogma   File: GitRepository.java   View source code 5 votes vote down vote up
private ObjectId toTreeId(RevWalk revWalk, Revision revision) {
    final ObjectId commitId = commitIdDatabase.get(revision);
    try {
        return revWalk.parseCommit(commitId).getTree().getId();
    } catch (IOException e) {
        throw new StorageException("failed to parse a commit: " + commitId, e);
    }
}
 
Example 37
Project: gitplex-mit   File: Project.java   View source code 5 votes vote down vote up
/**
 * Get cached object id of specified revision.
 * 
 * @param revision
 * 			revision to resolve object id for
 * @param mustExist
 * 			true to have the method throwing exception instead 
 * 			of returning null if the revision does not exist
 * @return
 * 			object id of specified revision, or <tt>null</tt> if revision 
 * 			does not exist and mustExist is specified as false
 */
@Nullable
public ObjectId getObjectId(String revision, boolean mustExist) {
	if (objectIdCache == null)
		objectIdCache = new HashMap<>();
	
	Optional<ObjectId> optional = objectIdCache.get(revision);
	if (optional == null) {
		optional = Optional.fromNullable(GitUtils.resolve(getRepository(), revision));
		objectIdCache.put(revision, optional);
	}
	if (mustExist && !optional.isPresent())
		throw new ObjectNotFoundException("Unable to find object '" + revision + "'");
	return optional.orNull();
}
 
Example 38
Project: centraldogma   File: CommitIdDatabase.java   View source code 5 votes vote down vote up
ObjectId get(Revision revision) {
    final Revision headRevision = this.headRevision;
    checkState(headRevision != null, "initial commit not available yet: %s", path);
    checkArgument(!revision.isRelative(), "revision: %s (expected: an absolute revision)", revision);
    if (revision.major() > headRevision.major()) {
        throw new RevisionNotFoundException(revision);
    }

    final ByteBuffer buf = threadLocalBuffer.get();
    buf.clear();
    long pos = (long) (revision.major() - 1) * RECORD_LEN;
    try {
        do {
            final int readBytes = channel.read(buf, pos);
            if (readBytes < 0) {
                throw new EOFException();
            }
            pos += readBytes;
        } while (buf.hasRemaining());
    } catch (IOException e) {
        throw new StorageException("failed to read the commit ID database: " + path, e);
    }

    buf.flip();

    final int actualRevision = buf.getInt();
    if (actualRevision != revision.major()) {
        throw new StorageException("incorrect revision number in the commit ID database: " + path +
                                   "(actual: " + actualRevision + ", expected: " + revision.major() + ')');
    }

    return new ObjectId(buf.getInt(), buf.getInt(), buf.getInt(), buf.getInt(), buf.getInt());
}
 
Example 39
Project: centraldogma   File: CommitIdDatabase.java   View source code 5 votes vote down vote up
private synchronized void put(Revision revision, ObjectId commitId, boolean safeMode) {
    if (safeMode) {
        final Revision expected;
        if (headRevision == null) {
            expected = Revision.INIT;
        } else {
            expected = headRevision.forward(1);
        }
        checkState(revision.equals(expected), "incorrect revision: %s (expected: %s)", revision, expected);
    }

    // Build a record.
    final ByteBuffer buf = threadLocalBuffer.get();
    buf.clear();
    buf.putInt(revision.major());
    commitId.copyRawTo(buf);
    buf.flip();

    // Append a record to the file.
    long pos = (long) (revision.major() - 1) * RECORD_LEN;
    try {
        do {
            pos += channel.write(buf, pos);
        } while (buf.hasRemaining());

        if (safeMode && fsync) {
            channel.force(true);
        }
    } catch (IOException e) {
        throw new StorageException("failed to update the commit ID database: " + path, e);
    }

    if (safeMode ||
        headRevision == null ||
        headRevision.major() < revision.major()) {
        headRevision = revision;
    }
}
 
Example 40
Project: centraldogma   File: GitRepositoryTest.java   View source code 5 votes vote down vote up
@Test
public void testDoUpdateRef() throws Exception {
    final ObjectId commitId = mock(ObjectId.class);

    // A commit on the mainlane
    testDoUpdateRef(Constants.R_TAGS + '1', commitId, false);
    testDoUpdateRef(Constants.R_HEADS + Constants.MASTER, commitId, false);
}