org.eclipse.jgit.blame.BlameResult Java Examples

The following examples show how to use org.eclipse.jgit.blame.BlameResult. 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: BlameCalculator.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
public List<BlameResult> calculate(
        File repoDir,
        List<String> filePathList,
        String startRev) throws Exception {
    try (Git git = Git.open(repoDir);
            ObjectReader reader = git.getRepository().newObjectReader();
            RevWalk rw = new RevWalk(git.getRepository())) {
        RevCommit startCommit = rw.parseCommit(git.getRepository().resolve(startRev));
        List<BlameResult> resultList = new ArrayList<>();
        for (String filePath : filePathList) {
            BlameResult result = calculateBlame(filePath, startCommit, git);
            resultList.add(result);
        }
        return resultList;
    }
}
 
Example #2
Source File: GitParser.java    From SZZUnleashed with MIT License 6 votes vote down vote up
/**
 * Map lines between one commit and another.
 *
 * @param foundCommit a blameresult containing information about a commit that have made changes
 *     to a file.
 * @param filePath the file that the commit have made changes to.
 * @return a mapping with the original revision file lines as keys and the values the
 *     corresponding lines in the other commit.
 */
private List<Integer> getLineMappings(BlameResult foundCommit, String filePath)
    throws IOException, GitAPIException {
  foundCommit.computeAll();
  RawText foundContent = foundCommit.getResultContents();

  /*
   * Easiest solution, maybe better with a list and a pair class?
   */
  List<Integer> lineMappings = new LinkedList<>();

  for (int line = 0; line < foundContent.size(); line++) {
    lineMappings.add(foundCommit.getSourceLine(line));
  }
  return lineMappings;
}
 
Example #3
Source File: GitBlameCommand.java    From mojito with Apache License 2.0 6 votes vote down vote up
/**
 * Gets {@link BlameResult} from the cache.
 *
 * @param filePath file path to be blamed
 * @return
 * @throws CommandException    something unexpected happened
 * @throws NoSuchFileException if the file is missing and can't be blamed
 */
BlameResult getBlameResultForFileCached(final String filePath) throws CommandException, NoSuchFileException {
    try {
        return getBlameResultForFileCache.get(filePath, new Callable<BlameResult>() {
            @Override
            public BlameResult call() throws Exception {
                BlameResult blameResult = gitRepository.getBlameResultForFile(filePath);
                if (blameResult == null) {
                    throw new NoSuchFileException(filePath);
                }
                return blameResult;
            }
        });
    } catch (ExecutionException ee) {
        Throwable cause = ee.getCause();

        if (cause instanceof NoSuchFileException) {
            throw (NoSuchFileException) cause;
        } else {
            throw new CommandException(cause);
        }
    }
}
 
Example #4
Source File: BlameCommand.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    org.eclipse.jgit.api.BlameCommand cmd = new Git(repository).blame();
    cmd.setFilePath(Utils.getRelativePath(getRepository().getWorkTree(), file));
    if (revision != null) {
        cmd.setStartCommit(Utils.findCommit(repository, revision));
    } else if (repository.getConfig().get(WorkingTreeOptions.KEY).getAutoCRLF() != CoreConfig.AutoCRLF.FALSE) {
        // work-around for autocrlf
        cmd.setTextComparator(new AutoCRLFComparator());
    }
    cmd.setFollowFileRenames(true);
    try {
        BlameResult cmdResult = cmd.call();
        if (cmdResult != null) {
            result = getClassFactory().createBlameResult(cmdResult, repository);
        }
    } catch (GitAPIException ex) {
        throw new GitException(ex);
    }
}
 
Example #5
Source File: GitRepository.java    From mojito with Apache License 2.0 6 votes vote down vote up
/**
 * Get the git-blame information for entire file
 *
 * @param filePath
 * @return
 * @throws CommandException
 */
public BlameResult getBlameResultForFile(String filePath) throws CommandException {

    logger.debug("getBlameResultForFile: {}", filePath);
    try {
        BlameCommand blamer = new BlameCommand(jgitRepository);
        ObjectId commitID = jgitRepository.resolve("HEAD");
        blamer.setStartCommit(commitID);
        blamer.setFilePath(filePath);
        BlameResult blame = blamer.call();

        return blame;
    } catch (GitAPIException | IOException e) {
        String msg = MessageFormat.format("Can't get blame result for file: {0}", filePath);
        logger.error(msg, e);
        throw new CommandException(msg, e);
    }
}
 
Example #6
Source File: PersonFilter.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
@SuppressWarnings("unchecked")
public PersonFilter(MavenProject project, File gitDir, PersonInfo personInfo, List<BlameResult> blameResults) {
    List<String> modules = project.getModules();
    if (project.getParent() != null && CollectionUtils.isNotEmpty(project.getParent().getModules())) {
        modules.addAll(project.getParent().getModules());
    }
    for (BlameResult blameResult : blameResults) {
        String name = blameResult.getResultPath();
        if (CollectionUtils.isNotEmpty(modules)) {
            for (String module : modules) {
                if (name.startsWith(module)) {
                    name = StringUtils.replaceOnce(name, module, "");
                    break;
                }
            }
        }
        if (!name.startsWith(SOURCE_PATH_PREFIX)) {
            continue;
        }
        name = StringUtils.replaceOnce(name, SOURCE_PATH_PREFIX, "");
        classPathBlameResultMap.put(name, blameResult);
    }
    this.personInfo = personInfo;
}
 
Example #7
Source File: GitRepository.java    From mojito with Apache License 2.0 6 votes vote down vote up
/**
 * Get the git-blame information for given line number
 *
 * @param lineNumber
 * @param blameResultForFile
 * @return
 */
public GitBlame getBlameResults(int lineNumber, BlameResult blameResultForFile) throws LineMissingException {

    GitBlame gitBlame = new GitBlame();

    try {
        gitBlame.setAuthorName(blameResultForFile.getSourceAuthor(lineNumber).getName());
        gitBlame.setAuthorEmail(blameResultForFile.getSourceAuthor(lineNumber).getEmailAddress());
        gitBlame.setCommitName(blameResultForFile.getSourceCommit(lineNumber).getName());
        gitBlame.setCommitTime(Integer.toString(blameResultForFile.getSourceCommit(lineNumber).getCommitTime()));
    } catch (ArrayIndexOutOfBoundsException e) {
        String msg = MessageFormat.format("The line: {0} is not available in the file anymore", lineNumber);
        logger.debug(msg);
        throw new LineMissingException(msg);
    }

    return gitBlame;

}
 
Example #8
Source File: BlameTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testBlameMixedLineEndings () throws Exception {
    File f = new File(workDir, "f");
    String content = "";
    for (int i = 0; i < 10000; ++i) {
        content += i + "\r\n";
    }
    write(f, content);

    // lets turn autocrlf on
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();

    File[] files = new File[] { f };
    GitClient client = getClient(workDir);
    client.add(files, NULL_PROGRESS_MONITOR);
    GitRevisionInfo info = client.commit(files, "commit", null, null, NULL_PROGRESS_MONITOR);

    content = content.replaceFirst("0", "01");
    write(f, content);

    // it should be up to date again
    org.eclipse.jgit.api.BlameCommand cmd = new Git(repository).blame();
    cmd.setFilePath("f");
    BlameResult blameResult = cmd.call();
    assertEquals(info.getRevision(), blameResult.getSourceCommit(1).getName());
    
    GitBlameResult res = client.blame(f, null, NULL_PROGRESS_MONITOR);
    assertNull(res.getLineDetails(0));
    assertLineDetails(f, 1, info.getRevision(), info.getAuthor(), info.getCommitter(), res.getLineDetails(1));
    
    // without autocrlf it should all be modified
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "false");
    cfg.save();
    res = client.blame(f, null, NULL_PROGRESS_MONITOR);
    assertNull(res.getLineDetails(1));
}
 
Example #9
Source File: GitBlameCommandTest.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void getSourceCommitsAccessOutOfBound() throws CommandException, NoSuchFileException {
    GitBlameCommand gitBlameCommand = new GitBlameCommand();
    gitBlameCommand.commandDirectories = new CommandDirectories(getBaseDir().getAbsolutePath());
    gitBlameCommand.initGitRepository();
    BlameResult blameResult = gitBlameCommand.getBlameResultForFileCached("pom.xml");
    blameResult.getSourceCommit(100000);
}
 
Example #10
Source File: GitBlameCommandTest.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Test(expected = NoSuchFileException.class)
public void updateGitBlameOMissingFile() throws CommandException, NoSuchFileException, LineMissingException {
    GitBlameCommand gitBlameCommand = new GitBlameCommand();
    gitBlameCommand.commandDirectories = new CommandDirectories(getBaseDir().getAbsolutePath());
    gitBlameCommand.initGitRepository();
    BlameResult blameResult = gitBlameCommand.getBlameResultForFileCached("somemissginfile");
    GitBlameWithUsage gitBlameWithUsage = new GitBlameWithUsage();
    gitBlameCommand.updateBlameResultsInGitBlameWithUsage(10, blameResult, gitBlameWithUsage);
    assertNull(gitBlameWithUsage.getGitBlame().getAuthorName());
}
 
Example #11
Source File: GitBlameCommandTest.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Test(expected = LineMissingException.class)
public void updateGitBlameOutOfBousnd() throws CommandException, NoSuchFileException, LineMissingException {
    GitBlameCommand gitBlameCommand = new GitBlameCommand();
    gitBlameCommand.commandDirectories = new CommandDirectories(getBaseDir().getAbsolutePath());
    gitBlameCommand.initGitRepository();
    BlameResult blameResult = gitBlameCommand.getBlameResultForFileCached("pom.xml");
    GitBlameWithUsage gitBlameWithUsage = new GitBlameWithUsage();
    gitBlameCommand.updateBlameResultsInGitBlameWithUsage(100000, blameResult, gitBlameWithUsage);
    assertNull(gitBlameWithUsage.getGitBlame().getAuthorName());
}
 
Example #12
Source File: GitBlameCommandTest.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Test
public void getBlameResultForFileWhenFileIsMissing() throws CommandException, NoSuchFileException {
    GitBlameCommand gitBlameCommand = new GitBlameCommand();
    gitBlameCommand.commandDirectories = new CommandDirectories(getInputResourcesTestDir().getAbsolutePath());
    gitBlameCommand.initGitRepository();
    BlameResult blameResult = gitBlameCommand.gitRepository.getBlameResultForFile("forSomeMissingFile");
    assertNull(blameResult);
}
 
Example #13
Source File: GitBlameCommandTest.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Test
public void getBlameResultForLines() throws Exception {

    if (shallowClone) {
        // that won't work on a shallow clone / on travis. Keep it for local testing
        return;
    }

    File sourceDirectory = getInputResourcesTestDir("source");
    String filepath = sourceDirectory.getAbsolutePath();

    GitBlameCommand gitBlameCommand = new GitBlameCommand();
    gitBlameCommand.commandDirectories = new CommandDirectories(filepath);
    gitBlameCommand.initGitRepository();

    String relativePath = gitBlameCommand.gitRepository.getDirectory().toPath().getParent().relativize(sourceDirectory.toPath()).toString();
    relativePath = relativePath + "/res/values/strings.xml";
    BlameResult blameResult = gitBlameCommand.gitRepository.getBlameResultForFile(relativePath);

    // Will not hold up if file is committed by another person and/or at another time
    String expectedAuthor = "Liz Magalindan";
    String expectedEmail = "[email protected]";
    String expectedSourceCommit = "88025e7b8b0f5d0f12f90c4ed9f86623074bc2ee";
    int expectedTime = 1537477876;
    for (int lineNumber = 0; lineNumber < blameResult.getResultContents().size(); lineNumber++) {
        PersonIdent actualAuthor = blameResult.getSourceAuthor(lineNumber);
        RevCommit actualCommit = blameResult.getSourceCommit(lineNumber);
        assertEquals(expectedAuthor, actualAuthor.getName());
        assertEquals(expectedEmail, actualAuthor.getEmailAddress());
        assertEquals(expectedSourceCommit, actualCommit.getName());
        assertEquals(expectedTime, actualCommit.getCommitTime());
    }
}
 
Example #14
Source File: GitBlameCommand.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Reads in the lines of the file and runs git-blame on usage locations given by file
 *
 * @param gitBlameWithUsages
 * @throws CommandException
 */
void blameWithTextUnitUsages(List<GitBlameWithUsage> gitBlameWithUsages) throws CommandException {
    logger.debug("blameWithTextUnitUsages");

    for (GitBlameWithUsage gitBlameWithUsage : gitBlameWithUsages) {

        if (gitBlameWithUsage.getUsages() != null && gitBlameWithUsage.getUsages().size() > 0) {

            for (String usage : gitBlameWithUsage.getUsages()) {
                String filename = getFileName(usage);
                int line = getLineNumber(usage);

                if (extractedFilePrefix != null) {
                    filename = filename.replace(extractedFilePrefix, "");
                }

                try {
                    BlameResult blameResultForFile = getBlameResultForFileCached(filename);
                    updateBlameResultsInGitBlameWithUsage(line, blameResultForFile, gitBlameWithUsage);
                    break;
                } catch (NoSuchFileException e) {
                    logger.debug("Can't blame file: {} for asset text unit: {}", filename, gitBlameWithUsage.getAssetTextUnitId());
                } catch (LineMissingException lme) {
                    logger.debug("Missing line: {} in file: {} for asset text unit: {}", lme, filename, gitBlameWithUsage.getAssetTextUnitId());
                }
            }
        }
    }
}
 
Example #15
Source File: GitBlameCommand.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Runs git-blame on each line of the file
 *
 * @param gitBlameWithUsages
 * @throws CommandException
 */
void blameSourceFiles(List<GitBlameWithUsage> gitBlameWithUsages) throws CommandException {
    logger.debug("blameSourceFiles");

    ArrayList<FileMatch> sourceFileMatches = commandHelper.getSourceFileMatches(commandDirectories, fileType, sourceLocale, sourcePathFilterRegex);

    for (FileMatch sourceFileMatch : sourceFileMatches) {
        if (GitBlameType.TEXT_UNIT_USAGES.equals(sourceFileMatch.getFileType().getGitBlameType())) {
            continue;
        }
        logger.debug("Processing source file: {}", sourceFileMatch.getPath().toString());

        Path sourceRelativePath = gitRepository.getDirectory().getParentFile().toPath().relativize(sourceFileMatch.getPath());
        BlameResult blameResultForFile = gitRepository.getBlameResultForFile(sourceRelativePath.toString());

        if (blameResultForFile != null) {
            for (int i = 0; i < blameResultForFile.getResultContents().size(); i++) {
                String lineText = blameResultForFile.getResultContents().getString(i);

                List<GitBlameWithUsage> gitBlameWithUsageList = getGitBlameWithUsagesFromLine(lineText, gitBlameWithUsages, sourceFileMatch.getFileType());
                for (GitBlameWithUsage gitBlameWithUsage : gitBlameWithUsageList) {
                    try {
                        updateBlameResultsInGitBlameWithUsage(i, blameResultForFile, gitBlameWithUsage);
                    } catch (LineMissingException lme) {
                        throw new RuntimeException("Processing source file, this must not happen", lme);
                    }
                }
            }
        } else {
            consoleWriter.a("Source file:").fg(CYAN).a(sourceRelativePath.toString()).reset().a(" not in Git. Skip it.");
        }
    }
}
 
Example #16
Source File: GitManagerImpl.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public List<GitBlame> blame(Workspace ws, String path) throws AccessDeniedException, GitAPIException {
    Repository repository = getRepository(ws.getSpaceKey());

    String relativePath = ws.getRelativePath(path).toString();

    try (Git git = Git.wrap(repository)) {
        BlameResult blameResult = git.blame()
                .setFilePath(relativePath)
                .setFollowFileRenames(true)
                .call();

        if (blameResult == null) { // file not exist
            return Lists.newArrayList();
        }

        int lineCnt = blameResult.getResultContents().size();

        return IntStream.range(0, lineCnt)
                .mapToObj(i -> {
                    org.eclipse.jgit.lib.PersonIdent author = blameResult.getSourceAuthor(i);
                    RevCommit commit = blameResult.getSourceCommit(i);

                    GitBlame.GitBlameBuilder builder = GitBlame.builder()
                            .author(mapper.map(author, PersonIdent.class));

                    if (commit != null) {
                        builder.shortName(commit.abbreviate(ABBREVIATION_LENGTH).name());
                    }

                    return builder.build();
                }).collect(Collectors.toList());
    }
}
 
Example #17
Source File: GitBlameResult.java    From netbeans with Apache License 2.0 5 votes vote down vote up
GitBlameResult (BlameResult result, Repository repository) {
    this.lineCount = result.getResultContents().size();
    this.lineDetails = new GitLineDetails[lineCount];

    Map<String, File> cachedFiles = new HashMap<String, File>(lineCount);
    this.blamedFile = getFile(cachedFiles, result.getResultPath(), repository.getWorkTree());

    Map<RevCommit, GitRevisionInfo> cachedRevisions = new HashMap<RevCommit, GitRevisionInfo>(lineCount);
    Map<PersonIdent, GitUser> cachedUsers = new HashMap<PersonIdent, GitUser>(lineCount * 2);
    for (int i = 0; i < lineCount; ++i) {
        RevCommit commit = result.getSourceCommit(i);
        if (commit == null) {
            lineDetails[i] = null;
        } else {
            GitRevisionInfo revInfo = cachedRevisions.get(commit);
            if (revInfo == null) {
                revInfo = new GitRevisionInfo(commit, repository);
                cachedRevisions.put(commit, revInfo);
            }
            GitUser author = getUser(cachedUsers, result.getSourceAuthor(i));
            GitUser committer = getUser(cachedUsers, result.getSourceCommitter(i));
            File sourceFile = getFile(cachedFiles, result.getSourcePath(i), repository.getWorkTree());
            String content = result.getResultContents().getString(i);
            lineDetails[i] = new GitLineDetails(content, revInfo, author, committer, sourceFile, result.getSourceLine(i));
        }
    }
}
 
Example #18
Source File: GitParser.java    From SZZUnleashed with MIT License 5 votes vote down vote up
private int getSourceLine(BlameResult foundCommit, int index)
    throws IOException, GitAPIException {
  foundCommit.computeAll();

  try {
    return foundCommit.getSourceLine(index);
  } catch (ArrayIndexOutOfBoundsException e) {
    return -1;
  }
}
 
Example #19
Source File: BlameCalculator.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private BlameResult calculateBlame(
        String filePath,
        RevCommit startCommit,
        Git git) throws GitAPIException {
    return git.blame().setFilePath(filePath)
            .setStartCommit(startCommit)
            .setTextComparator(comparator)
            .setFollowFileRenames(true)
            .call();
}
 
Example #20
Source File: GitClassFactoryImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public GitBlameResult createBlameResult (BlameResult result, Repository repository) {
    return new GitBlameResult(result, repository);
}
 
Example #21
Source File: GitBlameCommand.java    From mojito with Apache License 2.0 4 votes vote down vote up
void updateBlameResultsInGitBlameWithUsage(int lineNumber, BlameResult blameResultForFile, GitBlameWithUsage gitBlameWithUsage) throws LineMissingException {
    GitBlame gitBlame = gitRepository.getBlameResults(lineNumber, blameResultForFile);
    gitBlameWithUsage.setGitBlame(gitBlame);
}
 
Example #22
Source File: GitRevisionInformationProvider.java    From jdt-codemining with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RevisionInformation getRevisionInformation(IResource resource) {
	RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
	if (mapping == null) {
		return null;
	}
	Repository repository = mapping.getRepository();
	if (repository == null) {
		return null;
	}
	String path = mapping.getRepoRelativePath(resource);
	if (path == null) {
		return null;
	}
	final BlameCommand command = new BlameCommand(repository).setFollowFileRenames(true).setFilePath(path);
	try {
		command.setStartCommit(repository.resolve(Constants.HEAD));
	} catch (IOException e) {
		return null;
	}

	command.setTextComparator(RawTextComparator.WS_IGNORE_ALL);

	BlameResult result;
	try {
		result = command.call();
	} catch (Exception e1) {
		// Activator.error(e1.getMessage(), e1);
		return null;
	}
	// progress.worked(1);
	if (result == null)
		return null;

	RevisionInformation info = new RevisionInformation();
	Map<RevCommit, BlameRevision> revisions = new HashMap<>();
	int lineCount = result.getResultContents().size();
	BlameRevision previous = null;
	for (int i = 0; i < lineCount; i++) {
		RevCommit commit = result.getSourceCommit(i);
		String sourcePath = result.getSourcePath(i);
		if (commit == null) {
			// Unregister the current revision
			if (previous != null) {
				previous.register();
				previous = null;
			}
			continue;
		}
		BlameRevision revision = revisions.get(commit);
		if (revision == null) {
			revision = new ExtendedBlameRevision();
			revision.setRepository(repository);
			revision.setCommit(commit);
			revision.setSourcePath(sourcePath);
			revisions.put(commit, revision);
			info.addRevision(revision);
		}
		revision.addSourceLine(i, result.getSourceLine(i));
		if (previous != null)
			if (previous == revision)
				previous.addLine();
			else {
				previous.register();
				previous = revision.reset(i);
			}
		else
			previous = revision.reset(i);
	}
	if (previous != null)
		previous.register();
	return info;
}
 
Example #23
Source File: PersonFilter.java    From diff-check with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public PersonIdent getPerson(BlameResult blameResult, int line) {
    return blameResult.getSourceCommitter(line);
}
 
Example #24
Source File: PersonFilter.java    From diff-check with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public PersonIdent getPerson(BlameResult blameResult, int line) {
    return blameResult.getSourceAuthor(line);
}
 
Example #25
Source File: GitClassFactory.java    From netbeans with Apache License 2.0 votes vote down vote up
public abstract GitBlameResult createBlameResult (BlameResult result, Repository repository); 
Example #26
Source File: PersonFilter.java    From diff-check with GNU Lesser General Public License v2.1 votes vote down vote up
public abstract PersonIdent getPerson(BlameResult blameResult, int line);