Java Code Examples for org.eclipse.jgit.revwalk.RevCommit#getName()

The following examples show how to use org.eclipse.jgit.revwalk.RevCommit#getName() . 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: GitTool.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 7 votes vote down vote up
public GitTool() {
    File gitWorkDir = new File(".");
    try {
        Git git = Git.open(gitWorkDir);
        Iterable<RevCommit> commits = git.log().all().call();
        Repository repo = git.getRepository();
        branch = repo.getBranch();
        RevCommit latestCommit = commits.iterator().next();
        name = latestCommit.getName();
        message = latestCommit.getFullMessage();
    } catch (Throwable e) {
        name = "";
        message = "";
        branch = "";
    }
}
 
Example 2
Source File: Git.java    From OpenSZZ-Cloud-Native with GNU General Public License v3.0 6 votes vote down vote up
/**
  * It gets blame of a file at a specific commit time
  * index 0 of array ==> line 0
  * index 1 of array ==> line 1
  * index 2 of array ==> line 2
  * @param commitSha
  * @param file
  * @param git
  * @return
  */
//removed unused parameter PrintWriter l
 public  String getBlameAt(String commitSha, String file, int lineNumber) {
  File  localRepo1 = new File(workingDirectory+"");
try {
	if (blame==null){
	  org.eclipse.jgit.api.Git git = org.eclipse.jgit.api.Git.open(localRepo1);
	  Repository repository = git.getRepository();
      BlameCommand blamer = new BlameCommand(repository);
      ObjectId commitID;
	  commitID = repository.resolve(commitSha);
      blamer.setStartCommit(commitID);
      blamer.setFilePath(file);
      blame = blamer.call();}
      RevCommit commit = blame.getSourceCommit(lineNumber);
      return commit.getName();
} catch (Exception e) {
	return null;
}
 }
 
Example 3
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
public String commitFile(Repository repo, String site, String path, String comment, PersonIdent user) {
    String commitId = null;
    String gitPath = getGitPath(path);
    Status status;

    try (Git git = new Git(repo)) {
        status = git.status().addPath(gitPath).call();

        // TODO: SJ: Below needs more thought and refactoring to detect issues with git repo and report them
        if (status.hasUncommittedChanges() || !status.isClean()) {
            RevCommit commit;
            commit = git.commit().setOnly(gitPath).setAuthor(user).setCommitter(user).setMessage(comment).call();
            commitId = commit.getName();
        }

        git.close();
    } catch (GitAPIException e) {
        logger.error("error adding and committing file to git: site: " + site + " path: " + path, e);
    }

    return commitId;
}
 
Example 4
Source File: GitService.java    From youran with Apache License 2.0 6 votes vote down vote up
/**
 * 提交到本地仓库
 *
 * @param repository 本地仓库
 * @return
 */
public String commitAll(Repository repository, String message) {
    Assert.notNull(repository, "本地仓库为空");
    try (Git git = new Git(repository)) {
        // add所有文件
        git.add().addFilepattern(".").call();
        // 全部提交
        RevCommit commit = git.commit()
            .setAll(true)
            .setMessage(message)
            .call();
        return commit.getName();
    } catch (GitAPIException e) {
        LOGGER.error("提交仓库异常", e);
        throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR, "提交仓库异常");
    }
}
 
Example 5
Source File: GitService.java    From youran with Apache License 2.0 6 votes vote down vote up
/**
 * 提交到暂存区
 *
 * @param repository 本地仓库
 * @return
 */
public String createStash(Repository repository) {
    Assert.notNull(repository, "本地仓库为空");
    try (Git git = new Git(repository)) {
        // add所有文件
        git.add().addFilepattern(".").call();
        // 全部提交
        RevCommit commit = git.stashCreate().call();
        if (commit == null) {
            return null;
        }
        return commit.getName();
    } catch (GitAPIException e) {
        LOGGER.error("提交到暂存区异常", e);
        throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR, "提交到暂存区异常");
    }
}
 
Example 6
Source File: GitSCM.java    From repositoryminer with Apache License 2.0 6 votes vote down vote up
private Commit processCommit(RevCommit revCommit) {
	PersonIdent author = revCommit.getAuthorIdent();
	PersonIdent committer = revCommit.getCommitterIdent();

	Developer myAuthor = new Developer(author.getName(), author.getEmailAddress());
	Developer myCommitter = new Developer(committer.getName(), committer.getEmailAddress());

	List<String> parents = new ArrayList<String>();
	for (RevCommit parent : revCommit.getParents()) {
		parents.add(parent.getName());
	}

	List<Change> changes = null;
	try {
		changes = getChangesForCommitedFiles(revCommit.getName());
	} catch (IOException e) {
		close();
		throw new RepositoryMinerException(e);
	}

	return new Commit(null, revCommit.getName(), myAuthor, myCommitter, revCommit.getFullMessage().trim(), changes,
			parents, author.getWhen(), committer.getWhen(), (parents.size() > 1), null);
}
 
Example 7
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
public CommitInfo createCommitInfo(RevCommit entry) {
    final Date date = GitUtils.getCommitDate(entry);
    PersonIdent authorIdent = entry.getAuthorIdent();
    String author = null;
    String name = null;
    String email = null;
    String avatarUrl = null;
    if (authorIdent != null) {
        author = authorIdent.getName();
        name = authorIdent.getName();
        email = authorIdent.getEmailAddress();

        // lets try default the avatar
        if (Strings.isNotBlank(email)) {
            avatarUrl = getAvatarUrl(email);
        }
    }
    boolean merge = entry.getParentCount() > 1;
    String shortMessage = entry.getShortMessage();
    String sha = entry.getName();
    return new CommitInfo(sha, author, name, email, avatarUrl, date, merge, shortMessage);
}
 
Example 8
Source File: PGA.java    From coming with MIT License 6 votes vote down vote up
private void obtainDiff(Repository repository, RevCommit commit, List<String> paths) throws IOException, GitAPIException {
        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        System.out.println("Having tree: " + tree);

        // now try to find a specific file
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(tree);
        treeWalk.setRecursive(true);
        for (String path : paths) {
            String filePath = SIVA_COMMITS_DIR + commit.getName() + "/" + path;
            File file = new File(filePath);
            if (!file.exists()) {
                treeWalk.setFilter(PathFilter.create(path));
                if (!treeWalk.next()) {
                    throw new IllegalStateException("Did not find expected file '" + path + "'");
                }

                ObjectId objectId = treeWalk.getObjectId(0);
                ObjectLoader loader = repository.open(objectId);
                // and then one can the loader to read the file
//                loader.copyTo(System.out);
                loader.copyTo(FileUtils.openOutputStream(file));
            }
        }
    }
 
Example 9
Source File: GitNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public Revision checkpoint(String noteId,
                           String notePath,
                           String commitMessage,
                           AuthenticationInfo subject) throws IOException {
  String noteFileName = buildNoteFileName(noteId, notePath);
  Revision revision = Revision.EMPTY;
  try {
    List<DiffEntry> gitDiff = git.diff().call();
    boolean modified = gitDiff.parallelStream().anyMatch(diffEntry -> diffEntry.getNewPath().equals(noteFileName));
    if (modified) {
      LOGGER.debug("Changes found for pattern '{}': {}", noteFileName, gitDiff);
      DirCache added = git.add().addFilepattern(noteFileName).call();
      LOGGER.debug("{} changes are about to be commited", added.getEntryCount());
      RevCommit commit = git.commit().setMessage(commitMessage).call();
      revision = new Revision(commit.getName(), commit.getShortMessage(), commit.getCommitTime());
    } else {
      LOGGER.debug("No changes found {}", noteFileName);
    }
  } catch (GitAPIException e) {
    LOGGER.error("Failed to add+commit {} to Git", noteFileName, e);
  }
  return revision;
}
 
Example 10
Source File: OldGitNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public Revision checkpoint(String pattern, String commitMessage, AuthenticationInfo subject) {
  Revision revision = Revision.EMPTY;
  try {
    List<DiffEntry> gitDiff = git.diff().call();
    if (!gitDiff.isEmpty()) {
      LOG.debug("Changes found for pattern '{}': {}", pattern, gitDiff);
      DirCache added = git.add().addFilepattern(pattern).call();
      LOG.debug("{} changes are about to be commited", added.getEntryCount());
      RevCommit commit = git.commit().setMessage(commitMessage).call();
      revision = new Revision(commit.getName(), commit.getShortMessage(), commit.getCommitTime());
    } else {
      LOG.debug("No changes found {}", pattern);
    }
  } catch (GitAPIException e) {
    LOG.error("Failed to add+commit {} to Git", pattern, e);
  }
  return revision;
}
 
Example 11
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String copyContent(String site, String fromPath, String toPath) {
    String commitId = null;

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);

        String gitFromPath = helper.getGitPath(fromPath);
        String gitToPath = helper.getGitPath(toPath);

        try (Git git = new Git(repo)) {
            Path sourcePath = Paths.get(repo.getDirectory().getParent(), fromPath);
            File sourceFile = sourcePath.toFile();
            Path targetPath = Paths.get(repo.getDirectory().getParent(), toPath);
            File targetFile = targetPath.toFile();

            // Check if we're copying a single file or whole subtree
            FileUtils.copyDirectory(sourceFile, targetFile);

            // The operation is done on disk, now it's time to commit
            git.add().addFilepattern(gitToPath).call();
            RevCommit commit = git.commit()
                    .setOnly(gitFromPath)
                    .setOnly(gitToPath)
                    .setAuthor(helper.getCurrentUserIdent())
                    .setCommitter(helper.getCurrentUserIdent())
                    .setMessage(helper.getCommitMessage(REPO_COPY_CONTENT_COMMIT_MESSAGE)
                            .replaceAll(PATTERN_FROM_PATH, fromPath).replaceAll(PATTERN_TO_PATH, toPath))
                    .call();
            commitId = commit.getName();

        } catch (IOException | GitAPIException | ServiceLayerException | UserNotFoundException e) {
            logger.error("Error while copying content for site: " + site + " fromPath: " + fromPath +
                    " toPath: " + toPath + " newName: ");
        }
    }

    return commitId;
}
 
Example 12
Source File: GitLabIT.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private String initGitLabProject(String url, boolean addFeatureBranch) throws GitAPIException, IOException {
    // Setup git repository
    Git.init().setDirectory(tmp.getRoot()).call();
    Git git = Git.open(tmp.getRoot());
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", url);
    config.save();

    // Setup remote master branch
    tmp.newFile("test");
    git.add().addFilepattern("test");
    RevCommit commit = git.commit().setMessage("test").call();
    git.push()
        .setRemote("origin").add("master")
        .setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitlab.getUsername(), gitlab.getPassword()))
        .call();

    if (addFeatureBranch) {
        // Setup remote feature branch
        git.checkout().setName("feature").setCreateBranch(true).call();
        tmp.newFile("feature");
        commit = git.commit().setMessage("feature").call();
        git.push().setRemote("origin").add("feature").setCredentialsProvider(new UsernamePasswordCredentialsProvider(gitlab.getUsername(), gitlab.getPassword()))
            .call();
    }

    return commit.getName();
}
 
Example 13
Source File: SMAGit.java    From salesforce-migration-assistant with MIT License 5 votes vote down vote up
/**
 * Creates an SMAGit instance
 *
 * @param pathToWorkspace
 * @param curCommit
 * @param diffAgainst
 * @param smaMode
 * @throws Exception
 */
public SMAGit(String pathToWorkspace,
              String curCommit,
              String diffAgainst,
              Mode smaMode) throws Exception
{
    String pathToRepo = pathToWorkspace + "/.git";
    File repoDir = new File(pathToRepo);
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    repository = builder.setGitDir(repoDir).readEnvironment().build();
    git = new Git(repository);
    this.curCommit = curCommit;

    if (smaMode == Mode.PRB)
    {
        ObjectId branchId = repository.resolve("refs/remotes/origin/" + diffAgainst);
        RevCommit targetCommit = new RevWalk(repository).parseCommit(branchId);

        this.prevCommit = targetCommit.getName();
    }
    else if (smaMode == Mode.STD)
    {
        this.prevCommit = diffAgainst;
    }

    if (smaMode != Mode.INI)
    {
        getDiffs();
    }
}
 
Example 14
Source File: GitUtil.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the git commitId hash
 *
 * @param repository - the Git repository from where the latest commit will be retrieved
 * @return String of Git commit hash
 * @throws GitAPIException - any Git exception that might occur while getting commitId
 */
public static String getGitCommitId(Repository repository) throws GitAPIException {
    try {
        if (repository != null) {
            Iterable<RevCommit> logs = new Git(repository).log().call();
            for (RevCommit rev : logs) {
                return rev.getName();
            }
        }
    } finally {

    }
    return null;
}
 
Example 15
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected String defaultObjectId(Git git, String objectId) {
    if (objectId == null || objectId.trim().length() == 0) {
        RevCommit commit = CommitUtils.getHead(git.getRepository());
        objectId = commit.getName();
    }
    return objectId;
}
 
Example 16
Source File: JGitHelper.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
private Revision getRevisionObj(Repository repository, RevCommit commit) throws IOException {
    String commitSHA = commit.getName();
    Date commitTime = commit.getAuthorIdent().getWhen();
    String comment = commit.getFullMessage().trim();
    String user = commit.getAuthorIdent().getName();
    String emailId = commit.getAuthorIdent().getEmailAddress();
    List<ModifiedFile> modifiedFiles = new ArrayList<ModifiedFile>();
    if (commit.getParentCount() == 0) {
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(commit.getTree());
        treeWalk.setRecursive(false);
        while (treeWalk.next()) {
            modifiedFiles.add(new ModifiedFile(treeWalk.getPathString(), "added"));
        }
    } else {
        RevWalk rw = new RevWalk(repository);
        RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
        DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
        diffFormatter.setRepository(repository);
        diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
        diffFormatter.setDetectRenames(true);
        List<DiffEntry> diffEntries = diffFormatter.scan(parent.getTree(), commit.getTree());
        for (DiffEntry diffEntry : diffEntries) {
            modifiedFiles.add(new ModifiedFile(diffEntry.getNewPath(), getAction(diffEntry.getChangeType().name())));
        }
    }

    return new Revision(commitSHA, commitTime, comment, user, emailId, modifiedFiles);
}
 
Example 17
Source File: Utils.java    From data7 with Apache License 2.0 5 votes vote down vote up
/**
 * Function to generate a commit Object from a revcommit object
 * @param git git repository
 * @param commit to generate the commit object from
 * @param filter whether of not files should be filtered
 * @return a commit object
 * @see Commit
 */
public static Commit generateCommitOfInterest(GitActions git, RevCommit commit,boolean filter) {
    try {
        String hash = commit.getName();
        String commitMessage = commit.getFullMessage();
        int timestamp = commit.getCommitTime();
        List<String> modifiedFiles = git.getListOfModifiedFile(commit.getName(), FILE_EXTENSION);
        List<FileFix> fixes = new ArrayList<>();
        for (String modifiedFile : modifiedFiles) {
            if (!filter || !modifiedFile.toLowerCase().contains("test")) {
                String newName = modifiedFile;
                GitActions.NamedCommit previousCommit = git.previousCommitImpactingAFile(modifiedFile, hash);
                String oldname = previousCommit.getFilePath();
                String oldHash = previousCommit.getRevCommit().getName();
                String oldContent = git.retrievingFileFromSpecificCommit(oldHash, oldname);
                String newContent = git.retrievingFileFromSpecificCommit(hash, newName);
                FileInterest old = new FileInterest(oldContent, oldname);
                FileInterest newer = new FileInterest(newContent, newName);
                fixes.add(new FileFix(old, newer, oldHash, git.getTimeCommit(oldHash)));
            }
        }
        return new Commit(hash, commitMessage, timestamp, fixes);
    } catch (IOException e) {
        System.err.println(e.getMessage());
        return null;
    }
}
 
Example 18
Source File: GitUtil.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the git commitId hash
 *
 * @param repository - the Git repository from where the latest commit will be retrieved
 * @return String of Git commit hash
 * @throws GitAPIException - any Git exception that might occur while getting commitId
 */
public static String getGitCommitId(Repository repository) throws GitAPIException {
    try {
        if (repository != null) {
            Iterable<RevCommit> logs = new Git(repository).log().call();
            for (RevCommit rev : logs) {
                return rev.getName();
            }
        }
    } finally {

    }
    return null;
}
 
Example 19
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Map<String, String> moveContent(String site, String fromPath, String toPath, String newName) {
    Map<String, String> toRet = new TreeMap<String, String>();
    String commitId;
    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX);

        String gitFromPath = helper.getGitPath(fromPath);
        String gitToPath;
        if (StringUtils.isEmpty(newName)) {
            gitToPath = helper.getGitPath(toPath);
        } else {
            gitToPath = helper.getGitPath(toPath + FILE_SEPARATOR + newName);
        }

        try (Git git = new Git(repo)) {
            // Check if destination is a file, then this is a rename operation
            // Perform rename and exit
            Path sourcePath = Paths.get(repo.getDirectory().getParent(), gitFromPath);
            File sourceFile = sourcePath.toFile();
            Path targetPath = Paths.get(repo.getDirectory().getParent(), gitToPath);
            File targetFile = targetPath.toFile();

            if (sourceFile.getCanonicalFile().equals(targetFile.getCanonicalFile())) {
                sourceFile.renameTo(targetFile);
            } else {
                if (targetFile.isFile()) {
                    if (sourceFile.isFile()) {
                        sourceFile.renameTo(targetFile);
                    } else {
                        // This is not a valid operation
                        logger.error("Invalid move operation: Trying to rename a directory to a file " +
                                "for site: " + site + " fromPath: " + fromPath + " toPath: " + toPath +
                                " newName: " + newName);
                    }
                } else if (sourceFile.isDirectory()) {
                    // Check if we're moving a single file or whole subtree
                    File[] dirList = sourceFile.listFiles();
                    for (File child : dirList) {
                        if (!child.equals(sourceFile)) {
                            FileUtils.moveToDirectory(child, targetFile, true);
                        }
                    }
                    FileUtils.deleteDirectory(sourceFile);
                } else {
                    if (sourceFile.isFile()) {
                        FileUtils.moveFile(sourceFile, targetFile);
                    } else {
                        FileUtils.moveToDirectory(sourceFile, targetFile, true);
                    }
                }
            }

            // The operation is done on disk, now it's time to commit
            git.add().addFilepattern(gitToPath).call();

            Status gitStatus = git.status().addPath(gitToPath).call();
            Set<String> changeSet = gitStatus.getAdded();

            for (String pathToCommit : changeSet) {
                String pathRemoved = pathToCommit.replace(gitToPath, gitFromPath);
                RevCommit commit = git.commit()
                        .setOnly(pathToCommit)
                        .setOnly(pathRemoved)
                        .setAuthor(helper.getCurrentUserIdent())
                        .setCommitter(helper.getCurrentUserIdent())
                        .setMessage(helper.getCommitMessage(REPO_MOVE_CONTENT_COMMIT_MESSAGE)
                                .replaceAll(PATTERN_FROM_PATH, fromPath)
                                .replaceAll(PATTERN_TO_PATH, toPath +
                                        (StringUtils.isNotEmpty(newName) ? newName : EMPTY)))
                        .call();
                commitId = commit.getName();
                toRet.put(pathToCommit, commitId);
            }
        } catch (IOException | GitAPIException | ServiceLayerException | UserNotFoundException e) {
            logger.error("Error while moving content for site: " + site + " fromPath: " + fromPath +
                    " toPath: " + toPath + " newName: " + newName);
        }
    }

    return toRet;
}
 
Example 20
Source File: SMAGitTest.java    From salesforce-migration-assistant with MIT License 4 votes vote down vote up
/**
 * Before to setup the test.
 *
 * @throws Exception
 */
@Before
public void setUp() throws Exception
{
    //Setup the fake repository
    localPath = File.createTempFile("TestGitRepository", "");
    localPath.delete();
    repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
    repository.create();

    File classesPath = new File(repository.getDirectory().getParent() + "/src/classes");
    classesPath.mkdirs();
    File pagesPath = new File(repository.getDirectory().getParent() + "/src/pages");
    pagesPath.mkdirs();
    File triggersPath = new File(repository.getDirectory().getParent() + "/src/triggers");
    triggersPath.mkdirs();


    //Add the first collection of files
    deletion = createFile("deleteThis.cls", classesPath);
    deleteMeta = createFile("deleteThis.cls-meta.xml", classesPath);
    modification = createFile("modifyThis.page", pagesPath);
    modifyMeta = createFile("modifyThis.page-meta.xml", pagesPath);
    new Git(repository).add().addFilepattern("src/classes/deleteThis.cls").call();
    new Git(repository).add().addFilepattern("src/classes/deleteThis.cls-meta.xml").call();
    new Git(repository).add().addFilepattern("src/pages/modifyThis.page").call();
    new Git(repository).add().addFilepattern("src/pages/modifyThis.page-meta.xml").call();

    //Create the first commit
    RevCommit firstCommit = new Git(repository).commit().setMessage("Add deleteThis and modifyThis").call();
    oldSha = firstCommit.getName();


    //Delete the deletion file, modify the modification file, and add the addition file
    new Git(repository).rm().addFilepattern("src/classes/deleteThis.cls").call();
    new Git(repository).rm().addFilepattern("src/classes/deleteThis.cls-meta.xml").call();
    modification.setExecutable(true);
    addition = createFile("addThis.trigger", triggersPath);
    addMeta = createFile("addThis.trigger-meta.xml", triggersPath);
    new Git(repository).add().addFilepattern("src/pages/modifyThis.page").call();
    new Git(repository).add().addFilepattern("src/pages/modifyThis.page-meta.xml").call();
    new Git(repository).add().addFilepattern("src/triggers/addThis.trigger").call();
    new Git(repository).add().addFilepattern("src/triggers/addThis.trigger-meta.xml").call();
    new Git(repository).add().addFilepattern("src/classes/deleteThis.cls").call();
    new Git(repository).add().addFilepattern("src/classes/deleteThis.cls-meta.xml").call();

    //Create the second commit
    RevCommit secondCommit = new Git(repository).commit().setMessage("Remove deleteThis. Modify " +
            "modifyThis. Add addThis.").call();
    newSha = secondCommit.getName();

    gitDir = localPath.getPath();
}