org.eclipse.jgit.diff.DiffEntry.ChangeType Java Examples

The following examples show how to use org.eclipse.jgit.diff.DiffEntry.ChangeType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: APIVersion.java    From apidiff with MIT License 6 votes vote down vote up
public APIVersion(final String path, final File file, final Map<ChangeType, List<GitFile>> mapModifications, Classifier classifierAPI) {
	
	try {
		this.classifierAPI = classifierAPI;
		this.mapModifications = mapModifications;
		this.path = path;
		this.nameProject = file.getAbsolutePath().replaceAll(this.path + "/", "");
    	String prefix = file.getAbsolutePath() + "/";
		for(ChangeType changeType : this.mapModifications.keySet()){
			for(GitFile gitFile: mapModifications.get(changeType)){
				if(gitFile.getPathOld()!= null){
					this.listFilesMofify.add(prefix + gitFile.getPathOld());
				}
				if(gitFile.getPathNew() != null && !gitFile.getPathNew().equals(gitFile.getPathOld())){
					this.listFilesMofify.add(prefix + gitFile.getPathNew());
				}
			}
		}
		this.parseFilesInDir(file, false);
	} catch (IOException e) {
		this.logger.error("Erro ao criar APIVersion", e);
	}
}
 
Example #2
Source File: UIGit.java    From hop with Apache License 2.0 6 votes vote down vote up
@Override
public List<UIFile> getUnstagedFiles() {
  List<UIFile> files = new ArrayList<UIFile>();
  Status status = null;
  try {
    status = git.status().call();
  } catch ( Exception e ) {
    e.printStackTrace();
    return files;
  }
  status.getUntracked().forEach( name -> {
    files.add( new UIFile( name, ChangeType.ADD, false ) );
  } );
  status.getModified().forEach( name -> {
    files.add( new UIFile( name, ChangeType.MODIFY, false ) );
  } );
  status.getConflicting().forEach( name -> {
    files.add( new UIFile( name, ChangeType.MODIFY, false ) );
  } );
  status.getMissing().forEach( name -> {
    files.add( new UIFile( name, ChangeType.DELETE, false ) );
  } );
  return files;
}
 
Example #3
Source File: UIGit.java    From hop with Apache License 2.0 6 votes vote down vote up
@Override
public List<UIFile> getStagedFiles() {
  List<UIFile> files = new ArrayList<UIFile>();
  Status status = null;
  try {
    status = git.status().call();
  } catch ( Exception e ) {
    e.printStackTrace();
    return files;
  }
  status.getAdded().forEach( name -> {
    files.add( new UIFile( name, ChangeType.ADD, true ) );
  } );
  status.getChanged().forEach( name -> {
    files.add( new UIFile( name, ChangeType.MODIFY, true ) );
  } );
  status.getRemoved().forEach( name -> {
    files.add( new UIFile( name, ChangeType.DELETE, true ) );
  } );
  return files;
}
 
Example #4
Source File: UIGit.java    From hop with Apache License 2.0 6 votes vote down vote up
@Override
public List<UIFile> getStagedFiles( String oldCommitId, String newCommitId ) {
  List<UIFile> files = new ArrayList<UIFile>();
  try {
    List<DiffEntry> diffs = getDiffCommand( oldCommitId, newCommitId )
      .setShowNameAndStatusOnly( true )
      .call();
    RenameDetector rd = new RenameDetector( git.getRepository() );
    rd.addAll( diffs );
    diffs = rd.compute();
    diffs.forEach( diff -> {
      files.add( new UIFile( diff.getChangeType() == ChangeType.DELETE ? diff.getOldPath() : diff.getNewPath(),
        diff.getChangeType(), false ) );
    } );
  } catch ( Exception e ) {
    e.printStackTrace();
  }
  return files;
}
 
Example #5
Source File: BlobDiffTitle.java    From onedev with MIT License 6 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	
	add(new Label("renamedTitle", change.getOldBlobIdent().path)
			.setVisible(change.getType() == ChangeType.RENAME));
	add(new Label("title", change.getPath()));

	String modeChange;
	if (change.getOldBlobIdent().mode != null && change.getNewBlobIdent().mode != null
			&& !change.getOldBlobIdent().mode.equals(change.getNewBlobIdent().mode)) {
		modeChange = Integer.toString(change.getOldBlobIdent().mode, 8) 
				+ " <i class='fa fa-long-arrow-right'></i> " 
				+ Integer.toString(change.getNewBlobIdent().mode, 8);
	} else {
		modeChange = null;
	}

	add(new Label("modeChange", modeChange).setEscapeModelStrings(false));
}
 
Example #6
Source File: DiffEntryWrapperTest.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testIsDeleted() {
    DiffEntry diffEntry = Mockito.mock(DiffEntry.class);
    Mockito.when(diffEntry.getChangeType()).thenReturn(ChangeType.DELETE);
    DiffEntryWrapper wrapper = DiffEntryWrapper.builder()
            .diffEntry(diffEntry)
            .build();
    Assert.assertTrue(wrapper.isDeleted());
}
 
Example #7
Source File: LocalFacadeTest.java    From sputnik with Apache License 2.0 5 votes vote down vote up
private void setUpDiff() throws IOException {
    when(modifiedFile.getNewPath()).thenReturn("/path/to/modifiedFile");
    when(modifiedFile.getChangeType()).thenReturn(ChangeType.MODIFY);

    when(newFile.getNewPath()).thenReturn("/path/to/newFile");
    when(newFile.getChangeType()).thenReturn(ChangeType.ADD);

    when(deletedFile.getChangeType()).thenReturn(ChangeType.DELETE);

    ObjectId head = mock(ObjectId.class);
    ObjectId headParent = mock(ObjectId.class);
    when(repo.resolve(Constants.HEAD)).thenReturn(head);
    when(repo.resolve(Constants.HEAD + "^")).thenReturn(headParent);
    when(diffFormatter.scan(headParent, head)).thenReturn(ImmutableList.of(modifiedFile, deletedFile, newFile));
}
 
Example #8
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public void fileTreeDiff(Repository repository, RevCommit currentCommit, List<String> javaFilesBefore, List<String> javaFilesCurrent, Map<String, String> renamedFilesHint) throws Exception {
       if (currentCommit.getParentCount() > 0) {
       	ObjectId oldTree = currentCommit.getParent(0).getTree();
        ObjectId newTree = currentCommit.getTree();
       	final TreeWalk tw = new TreeWalk(repository);
       	tw.setRecursive(true);
       	tw.addTree(oldTree);
       	tw.addTree(newTree);

       	final RenameDetector rd = new RenameDetector(repository);
       	rd.setRenameScore(80);
       	rd.addAll(DiffEntry.scan(tw));

       	for (DiffEntry diff : rd.compute(tw.getObjectReader(), null)) {
       		ChangeType changeType = diff.getChangeType();
       		String oldPath = diff.getOldPath();
       		String newPath = diff.getNewPath();
       		if (changeType != ChangeType.ADD) {
        		if (isJavafile(oldPath)) {
        			javaFilesBefore.add(oldPath);
        		}
        	}
       		if (changeType != ChangeType.DELETE) {
        		if (isJavafile(newPath)) {
        			javaFilesCurrent.add(newPath);
        		}
       		}
       		if (changeType == ChangeType.RENAME && diff.getScore() >= rd.getRenameScore()) {
       			if (isJavafile(oldPath) && isJavafile(newPath)) {
       				renamedFilesHint.put(oldPath, newPath);
       			}
       		}
       	}
       }
}
 
Example #9
Source File: AppraiseDiffViewerPart.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Finds the appropriate title for an individual change given its various attributes.
 */
private String calculateDiffChangeHeader(TaskAttribute diffTaskAttribute) {
  String newPath = diffTaskAttribute.getAttribute(AppraiseReviewTaskSchema.DIFF_NEWPATH).getValue();
  String oldPath = diffTaskAttribute.getAttribute(AppraiseReviewTaskSchema.DIFF_OLDPATH).getValue();
  String type = diffTaskAttribute.getAttribute(AppraiseReviewTaskSchema.DIFF_TYPE).getValue();
  ChangeType changeType = ChangeType.MODIFY;
  try {
    changeType = ChangeType.valueOf(type);
  } catch (Exception e) {
  }

  switch (changeType) {
    case ADD:
      return newPath + " (Added)";

    case COPY:
      return newPath + " (Copied from " + oldPath + ")";

    case DELETE:
      return newPath + " (Deleted)";

    case RENAME:
      return newPath + " (was " + oldPath + ")";

    case MODIFY:
    default:
      return newPath + " (Modified)";
  }
}
 
Example #10
Source File: GitManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private VcsChangeType convertChangeType(ChangeType changeType) {
	switch(changeType) {
		case ADD:
			return VcsChangeType.ADDED;
		case COPY:
			return null;
		case DELETE:
			return VcsChangeType.DELETED;
		case MODIFY:
			return VcsChangeType.UPDATED;
		case RENAME:
			return VcsChangeType.UPDATED;
	}
	return null;
}
 
Example #11
Source File: BlobChange.java    From onedev with MIT License 5 votes vote down vote up
public BlobChange(@Nullable ChangeType type, BlobIdent oldBlobIdent, BlobIdent newBlobIdent, 
		WhitespaceOption whitespaceOption) {
	this.type = type;
	this.oldBlobIdent = oldBlobIdent;
	this.newBlobIdent = newBlobIdent;
	this.whitespaceOption = whitespaceOption;
}
 
Example #12
Source File: BlobChange.java    From onedev with MIT License 5 votes vote down vote up
public BlobChange(String oldRev, String newRev, DiffEntry diffEntry, 
		WhitespaceOption whitespaceOption) {
	if (diffEntry.getChangeType() == ChangeType.RENAME 
			&& diffEntry.getOldPath().equals(diffEntry.getNewPath())) {
		// for some unknown reason, jgit detects rename even if path 
		// is the same
		type = ChangeType.MODIFY;
	} else {
		type = diffEntry.getChangeType();
	}
	this.whitespaceOption = whitespaceOption;
	oldBlobIdent = GitUtils.getOldBlobIdent(diffEntry, oldRev);
	newBlobIdent = GitUtils.getNewBlobIdent(diffEntry, newRev);
}
 
Example #13
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static BlobIdent getNewBlobIdent(DiffEntry diffEntry, String newRev) {
  	BlobIdent blobIdent;
if (diffEntry.getChangeType() != ChangeType.DELETE) {
	blobIdent = new BlobIdent(newRev, diffEntry.getNewPath(), diffEntry.getNewMode().getBits());
} else {
	blobIdent = new BlobIdent(newRev, null, null);
}
return blobIdent;
  }
 
Example #14
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
public static BlobIdent getOldBlobIdent(DiffEntry diffEntry, String oldRev) {
  	BlobIdent blobIdent;
if (diffEntry.getChangeType() != ChangeType.ADD) {
	blobIdent = new BlobIdent(oldRev, diffEntry.getOldPath(), diffEntry.getOldMode().getBits());
} else {
	blobIdent = new BlobIdent(oldRev, null, null);
}
return blobIdent;
  }
 
Example #15
Source File: BlobDiffPanel.java    From onedev with MIT License 5 votes vote down vote up
@Override
protected void onInitialize() {
	super.onInitialize();
	
	if (change.getType() == ChangeType.ADD || change.getType() == ChangeType.COPY) {
		showBlob(change.getNewBlob());
	} else if (change.getType() == ChangeType.DELETE) {
		showBlob(change.getOldBlob());
	} else {
		if (change.getOldText() != null && change.getNewText() != null) {
			if (change.getOldText().getLines().size() + change.getNewText().getLines().size() > DiffUtils.MAX_DIFF_SIZE) {
				add(newFragment("Unable to diff as the file is too large.", true));
			} else if (change.getAdditions() + change.getDeletions() > WebConstants.MAX_SINGLE_DIFF_LINES) {
				add(newFragment("Diff is too large to be displayed.", true));
			} else if (change.getAdditions() + change.getDeletions() == 0 
					&& (commentSupport == null || commentSupport.getComments().isEmpty())) {
				add(newFragment("Content is identical", false));
			} else {
				add(new TextDiffPanel(CONTENT_ID, projectModel, requestModel, change, diffMode, blameModel, commentSupport));
			}
		} else if (change.getOldBlob().isPartial() || change.getNewBlob().isPartial()) {
			add(newFragment("File is too large to be loaded.", true));
		} else if (change.getOldBlob().getMediaType().equals(change.getNewBlob().getMediaType())) {
			Panel diffPanel = null;
			for (DiffRenderer renderer: OneDev.getExtensions(DiffRenderer.class)) {
				diffPanel = renderer.render(CONTENT_ID, change.getNewBlob().getMediaType(), change, diffMode);
				if (diffPanel != null)
					break;
			}
			if (diffPanel != null)
				add(diffPanel);
			else
				add(newFragment("Binary file.", false));
		} else {
			add(newFragment("Binary file.", false));
		}
	}
}
 
Example #16
Source File: UIFile.java    From hop with Apache License 2.0 4 votes vote down vote up
public void setChangeType( ChangeType changeType ) {
  this.changeType = changeType;
}
 
Example #17
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 4 votes vote down vote up
/**
 * Formats a commit into the raw format.
 *
 * @param commit
 *      Commit to format.
 * @param parent
 *      Optional parent commit to produce the diff against. This only matters
 *      for merge commits, and git-log/git-whatchanged/etc behaves differently with respect to this.
 */
@SuppressFBWarnings(value = "VA_FORMAT_STRING_USES_NEWLINE",
        justification = "Windows git implementation requires specific line termination")
void format(RevCommit commit, RevCommit parent, PrintWriter pw, Boolean useRawOutput) throws IOException {
    if (parent!=null)
        pw.printf("commit %s (from %s)\n", commit.name(), parent.name());
    else
        pw.printf("commit %s\n", commit.name());

    pw.printf("tree %s\n", commit.getTree().name());
    for (RevCommit p : commit.getParents())
        pw.printf("parent %s\n",p.name());
    FastDateFormat iso = FastDateFormat.getInstance(ISO_8601);
    PersonIdent a = commit.getAuthorIdent();
    pw.printf("author %s <%s> %s\n", a.getName(), a.getEmailAddress(), iso.format(a.getWhen()));
    PersonIdent c = commit.getCommitterIdent();
    pw.printf("committer %s <%s> %s\n", c.getName(), c.getEmailAddress(), iso.format(c.getWhen()));

    // indent commit messages by 4 chars
    String msg = commit.getFullMessage();
    if (msg.endsWith("\n")) msg=msg.substring(0,msg.length()-1);
    msg = msg.replace("\n","\n    ");
    msg="\n    "+msg+"\n";

    pw.println(msg);

    // see man git-diff-tree for the format
    try (Repository repo = getRepository();
         ObjectReader or = repo.newObjectReader();
         TreeWalk tw = new TreeWalk(or)) {
    if (parent != null) {
        /* Caller provided a parent commit, use it */
        tw.reset(parent.getTree(), commit.getTree());
    } else {
        if (commit.getParentCount() > 0) {
            /* Caller failed to provide parent, but a parent
             * is available, so use the parent in the walk
             */
            tw.reset(commit.getParent(0).getTree(), commit.getTree());
        } else {
            /* First commit in repo has 0 parent count, but
             * the TreeWalk requires exactly two nodes for its
             * walk.  Use the same node twice to satisfy
             * TreeWalk. See JENKINS-22343 for details.
             */
            tw.reset(commit.getTree(), commit.getTree());
        }
    }
    tw.setRecursive(true);
    tw.setFilter(TreeFilter.ANY_DIFF);

    final RenameDetector rd = new RenameDetector(repo);

    rd.reset();
    rd.addAll(DiffEntry.scan(tw));
    List<DiffEntry> diffs = rd.compute(or, null);
    if (useRawOutput) {
     for (DiffEntry diff : diffs) {
         pw.printf(":%06o %06o %s %s %s\t%s",
                 diff.getOldMode().getBits(),
                 diff.getNewMode().getBits(),
                 diff.getOldId().name(),
                 diff.getNewId().name(),
                 statusOf(diff),
                 diff.getChangeType()==ChangeType.ADD ? diff.getNewPath() : diff.getOldPath());

         if (hasNewPath(diff)) {
             pw.printf(" %s",diff.getNewPath()); // copied to
         }
         pw.println();
         pw.println();
     }
        }
    }
}
 
Example #18
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 4 votes vote down vote up
private boolean hasNewPath(DiffEntry d) {
    return d.getChangeType()==ChangeType.COPY || d.getChangeType()==ChangeType.RENAME;
}
 
Example #19
Source File: LocalFacade.java    From sputnik with Apache License 2.0 4 votes vote down vote up
private boolean isNotDeleted(DiffEntry aDiffEntry) {
    return aDiffEntry.getChangeType() != ChangeType.DELETE;
}
 
Example #20
Source File: GitCommit.java    From compiler with Apache License 2.0 4 votes vote down vote up
private void updateChangedFiles(final RevCommit parent, final int parentIndex, final RevCommit child) {
	final DiffFormatter df = new DiffFormatter(NullOutputStream.INSTANCE);
	df.setRepository(repository);
	df.setDiffComparator(RawTextComparator.DEFAULT);
	df.setDetectRenames(true);

	try {
		final AbstractTreeIterator parentIter = new CanonicalTreeParser(null, repository.newObjectReader(), parent.getTree());
		final AbstractTreeIterator childIter = new CanonicalTreeParser(null, repository.newObjectReader(), child.getTree());
		List<DiffEntry> diffs = df.scan(parentIter, childIter);
		for (final DiffEntry diff : diffs) {
			if (diff.getChangeType() == ChangeType.MODIFY) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.MODIFIED);
				}
			// RENAMED file may have the same/different object id(s) for old and new
			} else if (diff.getChangeType() == ChangeType.RENAME) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.RENAMED);
				}
			} else if (diff.getChangeType() == ChangeType.COPY) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.COPIED);
				}
			// ADDED file should not have old path and its old object id is 0's
			} else if (diff.getChangeType() == ChangeType.ADD) {
				if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
					updateChangedFiles(parent, child, diff, ChangeKind.ADDED);
				}
			// DELETED file's new object id is 0's and doesn't have new path
			} else if (diff.getChangeType() == ChangeType.DELETE) {
				if (diff.getOldMode().getObjectType() == Constants.OBJ_BLOB) {
					String oldPath = diff.getOldPath();
					String oldObjectId = diff.getOldId().toObjectId().getName();
					ChangedFile.Builder cfb = getChangedFile(oldPath, ChangeKind.DELETED);
					filePathGitObjectIds.put(oldPath, diff.getNewId().toObjectId());
				}
			}
		}
	} catch (final IOException e) {
		if (debug)
			System.err.println("Git Error getting commit diffs: " + e.getMessage());
	}
	df.close();
}
 
Example #21
Source File: UIFile.java    From hop with Apache License 2.0 4 votes vote down vote up
@Deprecated
public UIFile( String name, ChangeType changeType ) {
  this.name = name;
  this.changeType = changeType;
}
 
Example #22
Source File: UIFile.java    From hop with Apache License 2.0 4 votes vote down vote up
public UIFile( String name, ChangeType changeType, Boolean isStaged ) {
  this.name = name;
  this.changeType = changeType;
  this.isStaged = isStaged;
}
 
Example #23
Source File: UIFile.java    From hop with Apache License 2.0 4 votes vote down vote up
public ChangeType getChangeType() {
  return changeType;
}
 
Example #24
Source File: GitLogTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testDiffFromLog() throws Exception {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	IPath[] clonePaths = createTestProjects(workspaceLocation);

	for (IPath clonePath : clonePaths) {
		// clone a  repo
		JSONObject clone = clone(clonePath);
		String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

		// get project/folder metadata
		WebRequest request = getGetRequest(cloneContentLocation);
		WebResponse response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
		JSONObject folder = new JSONObject(response.getText());

		JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
		String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

		// modify
		JSONObject testTxt = getChild(folder, "test.txt");
		modifyFile(testTxt, "hello");
		addFile(testTxt);

		// commit
		request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "2nd commit", false);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		// get the full log
		JSONArray commits = log(gitHeadUri);
		assertEquals(2, commits.length());
		JSONObject commit = commits.getJSONObject(0);
		assertEquals("2nd commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
		JSONObject diffs = (JSONObject) commit.get(GitConstants.KEY_COMMIT_DIFFS);
		assertEquals(1, diffs.get("Length"));
		JSONArray diffsArray = diffs.getJSONArray(ProtocolConstants.KEY_CHILDREN);

		// check the diff entry
		JSONObject diff = diffsArray.getJSONObject(0);
		assertEquals("test.txt", diff.getString(GitConstants.KEY_COMMIT_DIFF_NEWPATH));
		assertEquals("test.txt", diff.getString(GitConstants.KEY_COMMIT_DIFF_OLDPATH));
		assertEquals(Diff.TYPE, diff.getString(ProtocolConstants.KEY_TYPE));
		assertEquals(ChangeType.MODIFY, ChangeType.valueOf(diff.getString(GitConstants.KEY_COMMIT_DIFF_CHANGETYPE)));
		String contentLocation = diff.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
		String fileContent = getFileContent(new JSONObject().put(ProtocolConstants.KEY_LOCATION, contentLocation));
		assertEquals("hello", fileContent);
		String diffLocation = diff.getString(GitConstants.KEY_DIFF);

		// check diff location
		String[] parts = GitDiffTest.getDiff(diffLocation);

		StringBuilder sb = new StringBuilder();
		sb.append("diff --git a/test.txt b/test.txt").append("\n");
		sb.append("index 30d74d2..b6fc4c6 100644").append("\n");
		sb.append("--- a/test.txt").append("\n");
		sb.append("+++ b/test.txt").append("\n");
		sb.append("@@ -1 +1 @@").append("\n");
		sb.append("-test").append("\n");
		sb.append("\\ No newline at end of file").append("\n");
		sb.append("+hello").append("\n");
		sb.append("\\ No newline at end of file").append("\n");
		assertEquals(sb.toString(), parts[1]);
	}
}
 
Example #25
Source File: GitServiceImpl.java    From apidiff with MIT License 4 votes vote down vote up
@Override
public Map<ChangeType, List<GitFile>> fileTreeDiff(Repository repository, RevCommit commitNew) throws Exception {
       
	Map<ChangeType, List<GitFile>> mapDiff = new HashMap<ChangeType, List<GitFile>>();
	mapDiff.put(ChangeType.ADD, new ArrayList<>());
	mapDiff.put(ChangeType.COPY, new ArrayList<>());
	mapDiff.put(ChangeType.DELETE, new ArrayList<>());
	mapDiff.put(ChangeType.MODIFY, new ArrayList<>());
	mapDiff.put(ChangeType.RENAME, new ArrayList<>());
	
	if(commitNew.getParentCount() == 0){
		this.logger.warn("Commit don't have parent [commitId="+commitNew.getId().getName()+"]");
		return mapDiff;
	}
      
	ObjectId headOld = commitNew.getParent(0).getTree(); //Commit pai no grafo.
	ObjectId headNew = commitNew.getTree(); //Commit corrente.

       // prepare the two iterators to compute the diff between
	ObjectReader reader = repository.newObjectReader();
	
	CanonicalTreeParser treeRepositoryOld = new CanonicalTreeParser();
	treeRepositoryOld.reset(reader, headOld);
	
	CanonicalTreeParser treeRepositoryNew = new CanonicalTreeParser();
	treeRepositoryNew.reset(reader, headNew);
	
	// finally get the list of changed files
	List<DiffEntry> diffs = new Git(repository).diff()
	                    .setNewTree(treeRepositoryNew)
	                    .setOldTree(treeRepositoryOld)
	                    .setShowNameAndStatusOnly(true)
	                    .call();
	
       for (DiffEntry entry : diffs) {
       	if(UtilTools.isJavaFile(entry.getOldPath()) || UtilTools.isJavaFile(entry.getNewPath())) {
       		String pathNew =  "/dev/null".equals(entry.getNewPath())?null:entry.getNewPath();
       		String pathOld =  "/dev/null".equals(entry.getOldPath())?null:entry.getOldPath();
       		GitFile file = new GitFile(pathOld, pathNew, entry.getChangeType());
       		mapDiff.get(entry.getChangeType()).add(file);
       	}
       }
       return mapDiff;
}
 
Example #26
Source File: GitFile.java    From apidiff with MIT License 4 votes vote down vote up
public void setChageType(ChangeType chageType) {
	this.chageType = chageType;
}
 
Example #27
Source File: GitFile.java    From apidiff with MIT License 4 votes vote down vote up
public ChangeType getChageType() {
	return chageType;
}
 
Example #28
Source File: GitFile.java    From apidiff with MIT License 4 votes vote down vote up
public GitFile(final String pathOld, final String pathNew, final ChangeType chageType) {
	this.pathNew = pathNew;
	this.pathOld = pathOld;
	this.chageType = chageType;
}
 
Example #29
Source File: UIGitTest.java    From hop with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetUnstagedAndStagedObjects() throws Exception {
  // Create files
  File a = writeTrashFile( "a.ktr", "1234567" );
  File b = writeTrashFile( "b.kjb", "content" );
  File c = writeTrashFile( "c.kjb", "abcdefg" );

  // Test for unstaged
  List<UIFile> unStagedObjects = uiGit.getUnstagedFiles();
  assertEquals( 3, unStagedObjects.size() );
  assertTrue( unStagedObjects.stream().anyMatch( obj -> obj.getName().equals( "a.ktr" ) ) );

  // Test for staged
  git.add().addFilepattern( "." ).call();
  List<UIFile> stagedObjects = uiGit.getStagedFiles();
  assertEquals( 3, stagedObjects.size() );
  assertTrue( stagedObjects.stream().anyMatch( obj -> obj.getName().equals( "a.ktr" ) ) );

  // Make a commit
  RevCommit commit = git.commit().setMessage( "initial commit" ).call();
  stagedObjects = uiGit.getStagedFiles( commit.getId().name() + "~", commit.getId().name() );
  assertEquals( 3, stagedObjects.size() );
  assertTrue( stagedObjects.stream().anyMatch( obj -> obj.getName().equals( "b.kjb" ) ) );

  // Change
  a.renameTo( new File( git.getRepository().getWorkTree(), "a2.ktr" ) );
  b.delete();
  FileUtils.writeStringToFile( c, "A change" );

  // Test for unstaged
  unStagedObjects = uiGit.getUnstagedFiles();
  assertEquals( ChangeType.DELETE, unStagedObjects.stream().filter( obj -> obj.getName().equals( "b.kjb" ) ).findFirst().get().getChangeType() );

  // Test for staged
  git.add().addFilepattern( "." ).call();
  git.rm().addFilepattern( a.getName() ).call();
  git.rm().addFilepattern( b.getName() ).call();
  stagedObjects = uiGit.getStagedFiles();
  assertEquals( 4, stagedObjects.size() );
  assertEquals( ChangeType.DELETE, stagedObjects.stream().filter( obj -> obj.getName().equals( "b.kjb" ) ).findFirst().get().getChangeType() );
  assertEquals( ChangeType.ADD, stagedObjects.stream().filter( obj -> obj.getName().equals( "a2.ktr" ) ).findFirst().get().getChangeType() );
  assertEquals( ChangeType.MODIFY, stagedObjects.stream().filter( obj -> obj.getName().equals( "c.kjb" ) ).findFirst().get().getChangeType() );
}
 
Example #30
Source File: GitOperation.java    From Getaviz with Apache License 2.0 4 votes vote down vote up
public GitOperation(String description, String oldPath, String newPath, ChangeType operationType) {
	this.description = description;
	this.oldPath = oldPath;
	this.newPath = newPath;
	this.operationType = gitToApiOperationMapping.get(operationType);
}