org.eclipse.jgit.revwalk.RevCommit Java Examples

The following examples show how to use org.eclipse.jgit.revwalk.RevCommit. 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 Project: app-runner   Author: danielflower   File: AppManager.java    License: MIT License 6 votes vote down vote up
private ArrayList<String> getContributorsFromRepo() {
    ArrayList<String> contributors = new ArrayList<>();
    try {
        // get authors
        Iterable<RevCommit> commits = git.log().all().call();
        for (RevCommit commit : commits) {
            String author = commit.getAuthorIdent().getName();
            if (!contributors.contains(author)) {
                contributors.add(author);
            }
        }
        log.info("getting the contributors " + contributors);
    } catch (Exception e) {
        log.warn("Failed to get authors from repo: " + e.getMessage());
    }
    return contributors;
}
 
Example #2
Source Project: compiler   Author: boalang   File: GitConnector.java    License: Apache License 2.0 6 votes vote down vote up
public void countChangedFiles(List<String> commits, Map<String, Integer> counts) {
	RevWalk temprevwalk = new RevWalk(repository);
	try {
		revwalk.reset();
		Set<RevCommit> heads = getHeads();
		revwalk.markStart(heads);
		revwalk.sort(RevSort.TOPO, true);
		revwalk.sort(RevSort.COMMIT_TIME_DESC, true);
		revwalk.sort(RevSort.REVERSE, true);
		for (final RevCommit rc: revwalk) {
			final GitCommit gc = new GitCommit(this, repository, temprevwalk, projectName);
			System.out.println(rc.getName());
			commits.add(rc.getName());
			int count = gc.countChangedFiles(rc);
			counts.put(rc.getName(), count);
		}
	} catch (final IOException e) {
		if (debug)
			System.err.println("Git Error getting parsing HEAD commit for " + path + ". " + e.getMessage());
	} finally {
		temprevwalk.dispose();
		temprevwalk.close();
	}
}
 
Example #3
Source Project: ParallelGit   Author: beijunyi   File: GfsCommit.java    License: Apache License 2.0 6 votes vote down vote up
private void updateStatus(GfsStatusProvider.Update update, RevCommit newHead) throws IOException {
  if(status.isAttached()) {
    MergeNote mergeNote = status.mergeNote();
    if(!amend) {
      if(mergeNote != null) {
        BranchUtils.mergeCommit(status.branch(), newHead, repo);
      } else if(status.isInitialized()) {
        BranchUtils.newCommit(status.branch(), newHead, repo);
      } else {
        BranchUtils.initBranch(status.branch(), newHead, repo);
      }
    } else {
      BranchUtils.amendCommit(status.branch(), newHead, repo);
    }
  }
  update.commit(newHead);
  update.clearMergeNote();
}
 
Example #4
Source Project: zeppelin   Author: apache   File: GitNotebookRepo.java    License: 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 #5
Source Project: orion.server   Author: eclipse   File: Tag.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private RevCommit parseCommit() {
	if (this.commit == null) {
		RevWalk rw = new RevWalk(db);
		RevObject any;
		try {
			any = rw.parseAny(this.ref.getObjectId());
			if (any instanceof RevTag) {
				this.tag = (RevTag) any;
				RevObject o = rw.peel(any);
				if (o instanceof RevCommit) {
					this.commit = (RevCommit) rw.peel(any);
				}
			} else if (any instanceof RevCommit) {
				this.commit = (RevCommit) any;
			}
		} catch (IOException e) {
		} finally {
			rw.dispose();
		}
	}
	return commit;
}
 
Example #6
Source Project: incubator-gobblin   Author: apache   File: GitConfigMonitorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(dependsOnMethods = "testUpdateConfig")
public void testDeleteConfig() throws IOException, GitAPIException, URISyntaxException {
  // delete a config file
  testFlowFile.delete();

  // flow catalog has 1 entry before the config is deleted
  Collection<Spec> specs = this.flowCatalog.getSpecs();
  Assert.assertTrue(specs.size() == 1);

  // add, commit, push
  DirCache ac = this.gitForPush.rm().addFilepattern(formConfigFilePath(this.testGroupDir.getName(), this.testFlowFile.getName()))
      .call();
  RevCommit cc = this.gitForPush.commit().setMessage("Fourth commit").call();
  this.gitForPush.push().setRemote("origin").setRefSpecs(this.masterRefSpec).call();

  this.gitConfigMonitor.processGitConfigChanges();

  specs = this.flowCatalog.getSpecs();
  Assert.assertTrue(specs.size() == 0);
}
 
Example #7
Source Project: ParallelGit   Author: beijunyi   File: GitFileSystemProviderNewFileSystemTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void openWithBranch() throws IOException {
  initFileRepository(true);
  writeToCache("some_file");
  RevCommit commit = commitToBranch("test_branch");
  URI uri = GfsUriBuilder.prepare()
              .repository(repoDir)
              .build();
  try(GitFileSystem gfs = provider.newFileSystem(uri, singletonMap(BRANCH, "test_branch"))) {
    assertEquals("test_branch", gfs.getStatusProvider().branch());

    RevCommit baseCommit = gfs.getStatusProvider().commit();
    assertNotNull(baseCommit);
    assertEquals(commit, baseCommit);
  }
}
 
Example #8
Source Project: studio   Author: craftercms   File: GitContentRepository.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean commitIdExists(String site, String commitId) {
    boolean toRet = false;
    try (Repository repo = helper.getRepository(site, SANDBOX)) {
        if (repo != null) {
            ObjectId objCommitId = repo.resolve(commitId);
            if (objCommitId != null) {
                RevCommit revCommit = repo.parseCommit(objCommitId);
                if (revCommit != null) {
                    toRet = true;
                }
            }
        }
    } catch (IOException e) {
        logger.info("Commit ID " + commitId + " does not exist in sandbox for site " + site);
    }
    return toRet;
}
 
Example #9
Source Project: apidiff   Author: aserg-ufmg   File: APIDiff.java    License: MIT License 6 votes vote down vote up
@Override
public Result detectChangeAtCommit(String commitId, Classifier classifierAPI) {
	Result result = new Result();
	try {
		GitService service = new GitServiceImpl();
		Repository repository = service.openRepositoryAndCloneIfNotExists(this.path, this.nameProject, this.url);
		RevCommit commit = service.createRevCommitByCommitId(repository, commitId);
		Result resultByClassifier = this.diffCommit(commit, repository, this.nameProject, classifierAPI);
		result.getChangeType().addAll(resultByClassifier.getChangeType());
		result.getChangeMethod().addAll(resultByClassifier.getChangeMethod());
		result.getChangeField().addAll(resultByClassifier.getChangeField());
	} catch (Exception e) {
		this.logger.error("Error in calculating commitn diff ", e);
	}
	this.logger.info("Finished processing.");
	return result;
}
 
Example #10
Source Project: gocd   Author: gocd   File: ConfigRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldThrowExceptionWhenThereIsMergeConflict() throws Exception {
    String original = "first\nsecond\n";
    String nextUpdate = "1st\nsecond\n";
    String latestUpdate = "2nd\nsecond\n";
    configRepo.checkin(goConfigRevision(original, "md5-1"));
    configRepo.checkin(goConfigRevision(nextUpdate, "md5-2"));
    RevCommit currentRevCommitOnMaster = configRepo.getCurrentRevCommit();
    try {
        configRepo.getConfigMergedWithLatestRevision(goConfigRevision(latestUpdate, "md5-3"), "md5-1");
        fail("should have bombed for merge conflict");
    } catch (ConfigMergeException e) {
        assertThat(e.getMessage(), is(ConfigFileHasChangedException.CONFIG_CHANGED_PLEASE_REFRESH));
    }

    List<Ref> branches = getAllBranches();
    assertThat(branches.size(), is(1));
    assertThat(branches.get(0).getName().endsWith("master"), is(true));
    assertThat(configRepo.getCurrentRevCommit(), is(currentRevCommitOnMaster));
}
 
Example #11
Source Project: fabric8-forge   Author: fabric8io   File: RepositoryResource.java    License: 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 #12
Source Project: RefactoringMiner   Author: tsantalis   File: GitServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public Churn churn(Repository repository, RevCommit currentCommit) 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);
       	
       	List<DiffEntry> diffs = DiffEntry.scan(tw);
       	DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
   		diffFormatter.setRepository(repository);
   		diffFormatter.setContext(0);
   		
       	int addedLines = 0;
   		int deletedLines = 0;
       	for (DiffEntry entry : diffs) {
   			FileHeader header = diffFormatter.toFileHeader(entry);
           	List<? extends HunkHeader> hunks = header.getHunks();
           	for (HunkHeader hunkHeader : hunks) {
           		for (Edit edit : hunkHeader.toEditList()) {
   					if (edit.getType() == Type.INSERT) {
   						addedLines += edit.getLengthB();
   					} else if (edit.getType() == Type.DELETE) {
   						deletedLines += edit.getLengthA();
   					} else if (edit.getType() == Type.REPLACE) {
   						deletedLines += edit.getLengthA();
   						addedLines += edit.getLengthB();
   					}
   				}
           	}
       	}
       	diffFormatter.close();
       	return new Churn(addedLines, deletedLines);
	}
	return null;
}
 
Example #13
Source Project: mdw   Author: CenturyLinkCloud   File: VersionControlGit.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] readFromCommit(String commitId, String path) throws Exception {
    try (RevWalk revWalk = new RevWalk(localRepo)) {
        RevCommit commit = revWalk.parseCommit(ObjectId.fromString(commitId));
        // use commit's tree to find the path
        RevTree tree = commit.getTree();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (TreeWalk treeWalk = new TreeWalk(localRepo)) {
            treeWalk.addTree(tree);
            treeWalk.setRecursive(true);
            treeWalk.setFilter(PathFilter.create(path));
            if (!treeWalk.next()) {
                return null;
            }

            ObjectId objectId = treeWalk.getObjectId(0);
            ObjectLoader loader = localRepo.open(objectId);

            loader.copyTo(baos);
        }
        revWalk.dispose();
        return baos.toByteArray();
    }
}
 
Example #14
Source Project: onedev   Author: theonedev   File: Build.java    License: MIT License 6 votes vote down vote up
public Collection<RevCommit> getCommits(@Nullable Build.Status sincePrevStatus) {
	if (commitsCache == null) 
		commitsCache = new HashMap<>();
	if (!commitsCache.containsKey(sincePrevStatus)) {
		Collection<RevCommit> commits = new ArrayList<>();
		Build prevBuild = getStreamPrevious(sincePrevStatus);
		if (prevBuild != null) {
			Repository repository = project.getRepository();
			try (RevWalk revWalk = new RevWalk(repository)) {
				revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getCommitHash())));
				revWalk.markUninteresting(revWalk.parseCommit(prevBuild.getCommitId()));

				RevCommit commit;
				while ((commit = revWalk.next()) != null) 
					commits.add(commit);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		} 
		commitsCache.put(sincePrevStatus, commits);
	}
	return commitsCache.get(sincePrevStatus);
}
 
Example #15
Source Project: ParallelGit   Author: beijunyi   File: CommitUtilsGetHistoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getCommitHistoryWhenSkipIsNotZeroAndLimitIsIntegerMax_shouldReturnTailCommits() throws IOException {
  String branch = "orphan_branch";
  writeSomethingToCache();
  RevCommit commit1 = commitToBranch(branch);
  writeSomethingToCache();
  RevCommit commit2 = commitToBranch(branch);
  writeSomethingToCache();
  RevCommit commit3 = commitToBranch(branch);
  writeSomethingToCache();
  RevCommit commit4 = commitToBranch(branch);

  List<RevCommit> expected = Arrays.asList(commit3, commit2, commit1);
  List<RevCommit> actual = CommitUtils.getHistory(commit4, 1, Integer.MAX_VALUE, repo.newObjectReader());
  assertEquals(expected, actual);
}
 
Example #16
Source Project: onedev   Author: theonedev   File: Project.java    License: MIT License 6 votes vote down vote up
public RevCommit getLastCommit() {
	if (lastCommitHolder == null) {
		RevCommit lastCommit = null;
		try {
			for (Ref ref: getRepository().getRefDatabase().getRefsByPrefix(Constants.R_HEADS)) {
				RevCommit commit = getRevCommit(ref.getObjectId(), false);
				if (commit != null) {
					if (lastCommit != null) {
						if (commit.getCommitTime() > lastCommit.getCommitTime())
							lastCommit = commit;
					} else {
						lastCommit = commit;
					}
				}
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		lastCommitHolder = Optional.fromNullable(lastCommit);
	}
	return lastCommitHolder.orNull();
}
 
Example #17
Source Project: scava   Author: crossminer   File: GitManager.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String getFirstRevision(VcsRepository repository) throws Exception {
	Git git = getGit((GitRepository)repository);
	
	Repository repo = git.getRepository();
	RevWalk walk = new RevWalk(repo);
	
	Iterator<RevCommit> iterator = git.log().call().iterator();
	walk.parseCommit(iterator.next());
	
	String revision = null;
	
	// The commits are ordered latest first, so we want the last one.
	while(iterator.hasNext()) { 
		RevCommit commit = iterator.next();
		if (!iterator.hasNext()) {
			revision = commit.getId().getName();
		}
	}
	
	repo.close();
	git.close();
	
	return revision;
}
 
Example #18
Source Project: compiler   Author: boalang   File: GitConnector.java    License: Apache License 2.0 6 votes vote down vote up
public List<String> logCommitIds() {
	List<String> commits = new ArrayList<String>();
	RevWalk temprevwalk = new RevWalk(repository);
	try {
		revwalk.reset();
		Set<RevCommit> heads = getHeads();
		revwalk.markStart(heads);
		revwalk.sort(RevSort.TOPO, true);
		revwalk.sort(RevSort.COMMIT_TIME_DESC, true);
		revwalk.sort(RevSort.REVERSE, true);
		for (final RevCommit rc : revwalk)
			commits.add(rc.getName());
	} catch (final IOException e) {
		e.printStackTrace();
	} finally {
		temprevwalk.dispose();
		temprevwalk.close();
	}
	return commits;
}
 
Example #19
Source Project: git-as-svn   Author: bozaro   File: LayoutHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Nullable
static RevCommit loadOriginalCommit(@NotNull ObjectReader reader, @Nullable ObjectId cacheCommit) throws IOException {
  final RevWalk revWalk = new RevWalk(reader);
  if (cacheCommit != null) {
    final RevCommit revCommit = revWalk.parseCommit(cacheCommit);
    revWalk.parseTree(revCommit.getTree());

    final CanonicalTreeParser treeParser = new CanonicalTreeParser(GitRepository.emptyBytes, reader, revCommit.getTree());
    while (!treeParser.eof()) {
      if (treeParser.getEntryPathString().equals(ENTRY_COMMIT_REF)) {
        return revWalk.parseCommit(treeParser.getEntryObjectId());
      }
      treeParser.next();
    }
  }
  return null;
}
 
Example #20
Source Project: zeppelin   Author: apache   File: GitHubNotebookRepoTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Test the case when the check-pointing (add new files and commit) it pushes the local commits to the remote
 * repository
 */
public void pushLocalChangesToRemoteRepositoryOnCheckpointing() throws IOException, GitAPIException {
  // Add a new paragraph to the local repository
  addParagraphToNotebook();

  // Commit and push the changes to remote repository
  NotebookRepoWithVersionControl.Revision secondCommitRevision = gitHubNotebookRepo.checkpoint(
          TEST_NOTE_ID, TEST_NOTE_PATH, "Second commit from local repository", null);

  // Check all the commits as seen from the remote repository. The commits are ordered chronologically. The last
  // commit is the first in the commit logs.
  Iterator<RevCommit> revisions = remoteGit.log().all().call().iterator();

  assert(secondCommitRevision.id.equals(revisions.next().getName())); // The local commit after adding the paragraph

  // The first commit done on the remote repository
  assert(firstCommitRevision.getName().equals(revisions.next().getName()));
}
 
Example #21
Source Project: coming   Author: SpoonLabs   File: PGA.java    License: 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 #22
Source Project: incubator-gobblin   Author: apache   File: GitFlowGraphMonitorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test (dependsOnMethods = "testUpdateNode")
public void testRemoveEdge() throws GitAPIException, IOException {
  // delete a config file
  edge1File.delete();

  //Node1 has 1 edge before delete
  Set<FlowEdge> edgeSet = this.flowGraph.getEdges("node1");
  Assert.assertEquals(edgeSet.size(), 1);

  // delete, commit, push
  DirCache ac = this.gitForPush.rm().addFilepattern(formEdgeFilePath(this.edge1Dir.getParentFile().getName(),
      this.edge1Dir.getName(), this.edge1File.getName())).call();
  RevCommit cc = this.gitForPush.commit().setMessage("Edge remove commit").call();
  this.gitForPush.push().setRemote("origin").setRefSpecs(this.masterRefSpec).call();

  this.gitFlowGraphMonitor.processGitConfigChanges();

  //Check if edge1 has been deleted from the graph
  edgeSet = this.flowGraph.getEdges("node1");
  Assert.assertTrue(edgeSet.size() == 0);
}
 
Example #23
Source Project: studio   Author: craftercms   File: GitContentRepositoryHelper.java    License: 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 #24
Source Project: apidiff   Author: aserg-ufmg   File: APIDiff.java    License: MIT License 6 votes vote down vote up
@Override
public Result fetchAndDetectChange(List<Classifier> classifiers) {
	Result result = new Result();
	try {
		GitService service = new GitServiceImpl();
		Repository repository = service.openRepositoryAndCloneIfNotExists(this.path, this.nameProject, this.url);
		RevWalk revWalk = service.fetchAndCreateNewRevsWalk(repository, null);
		//Commits.
		Iterator<RevCommit> i = revWalk.iterator();
		while(i.hasNext()){
			RevCommit currentCommit = i.next();
			for(Classifier classifierAPI : classifiers){
				Result resultByClassifier = this.diffCommit(currentCommit, repository, this.nameProject, classifierAPI);
				result.getChangeType().addAll(resultByClassifier.getChangeType());
				result.getChangeMethod().addAll(resultByClassifier.getChangeMethod());
				result.getChangeField().addAll(resultByClassifier.getChangeField());
			}
		}
	} catch (Exception e) {
		this.logger.error("Error in calculating commit diff ", e);
	}

	this.logger.info("Finished processing.");
	return result;
}
 
Example #25
Source Project: onedev   Author: theonedev   File: Build.java    License: MIT License 6 votes vote down vote up
/**
 * Get fixed issue numbers
 * 
 */
public Collection<Long> getFixedIssueNumbers() {
	if (fixedIssueNumbers == null) {
		fixedIssueNumbers = new HashSet<>();
		Build prevBuild = getStreamPrevious(null);
		if (prevBuild != null) {
			Repository repository = project.getRepository();
			try (RevWalk revWalk = new RevWalk(repository)) {
				revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getCommitHash())));
				revWalk.markUninteresting(revWalk.parseCommit(prevBuild.getCommitId()));

				RevCommit commit;
				while ((commit = revWalk.next()) != null) 
					fixedIssueNumbers.addAll(IssueUtils.parseFixedIssueNumbers(commit.getFullMessage()));
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		} 
	}
	return fixedIssueNumbers;
}
 
Example #26
Source Project: onedev   Author: theonedev   File: Job.java    License: MIT License 6 votes vote down vote up
public static List<InputSuggestion> suggestVariables(String matchWith) {
	Component component = ComponentContext.get().getComponent();
	List<InputSuggestion> suggestions = new ArrayList<>();
	ProjectBlobPage page = (ProjectBlobPage) WicketUtils.getPage();
	BuildSpecAware buildSpecAware = WicketUtils.findInnermost(component, BuildSpecAware.class);
	if (buildSpecAware != null) {
		BuildSpec buildSpec = buildSpecAware.getBuildSpec();
		if (buildSpec != null) {
			JobAware jobAware = WicketUtils.findInnermost(component, JobAware.class);
			if (jobAware != null) {
				Job job = jobAware.getJob();
				if (job != null) {
					RevCommit commit;
					if (page.getBlobIdent().revision != null)
						commit = page.getCommit();
					else
						commit = null;
					suggestions.addAll(SuggestionUtils.suggestVariables(
							page.getProject(), commit, buildSpec, job, matchWith));
				}
			}
		}
	}
	return suggestions;
}
 
Example #27
Source Project: studio   Author: craftercms   File: GitRepositoryHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
public RevTree getTreeForCommit(Repository repository, String commitId) throws IOException {
    ObjectId commitObjectId = repository.resolve(commitId);

    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(commitObjectId);

        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        return tree;
    }
}
 
Example #28
Source Project: ParallelGit   Author: beijunyi   File: CommitUtilsListUnmergedCommitsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void listUnmergedCommitsWhenMasterIsAheadOfBranch_shouldReturnEmptyList() throws IOException {
  writeSomethingToCache();
  RevCommit masterFirst = commitToMaster();
  createBranch("test_branch", masterFirst, repo);
  writeSomethingToCache();
  commitToMaster();
  List<RevCommit> unmerged = listUnmergedCommits("test_branch", MASTER, repo);

  assertTrue(unmerged.isEmpty());
}
 
Example #29
Source Project: netbeans   Author: apache   File: GitRevisionInfo.java    License: Apache License 2.0 5 votes vote down vote up
private void listFiles() throws GitException {
    try (RevWalk revWalk = new RevWalk(repository);
        TreeWalk walk = new TreeWalk(repository)) {
        List<GitFileInfo> result;
        walk.reset();
        walk.setRecursive(true);
        RevCommit parentCommit = null;
        if (revCommit.getParentCount() > 0) {
            for (RevCommit commit : revCommit.getParents()) {
                revWalk.markStart(revWalk.lookupCommit(commit));
            }
            revWalk.setRevFilter(RevFilter.MERGE_BASE);
            Iterator<RevCommit> it = revWalk.iterator();
            if (it.hasNext()) {
                parentCommit = it.next();
            }
            if (parentCommit != null) {
                walk.addTree(parentCommit.getTree().getId());
            }
        }
        walk.addTree(revCommit.getTree().getId());
        walk.setFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, PathFilter.ANY_DIFF));
        if (parentCommit != null) {
            result = Utils.getDiffEntries(repository, walk, GitClassFactoryImpl.getInstance());
        } else {
            result = new ArrayList<>();
            while (walk.next()) {
                result.add(new GitFileInfo(new File(repository.getWorkTree(), walk.getPathString()), walk.getPathString(), GitFileInfo.Status.ADDED, null, null));
            }
        }
        this.modifiedFiles = result.toArray(new GitFileInfo[result.size()]);
    } catch (IOException ex) {
        throw new GitException(ex);
    }
}
 
Example #30
Source Project: netbeans   Author: apache   File: ResetTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testResetPathsChangeType () throws Exception {
    File file = new File(workDir, "f"); // index entry will be modified
    File file2 = new File(file, "file");
    write(file, "blablablabla");
    File[] files = new File[] { file, file2 };
    add(files);
    commit(files);

    GitClient client = getClient(workDir);
    client.remove(files, false, NULL_PROGRESS_MONITOR);
    commit(files);
    file.mkdirs();
    write(file2, "aaaa");
    add(file2);
    commit(files);

    Iterator<RevCommit> logs = new Git(repository).log().call().iterator();
    String revisionCurrent = logs.next().getId().getName();
    logs.next();
    String revisionPrevious = logs.next().getId().getName();

    client.reset(files, revisionPrevious, true, NULL_PROGRESS_MONITOR);
    Map<File, GitStatus> statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(2, statuses.size());
    assertStatus(statuses, workDir, file, true, Status.STATUS_ADDED, Status.STATUS_REMOVED, Status.STATUS_NORMAL, false);
    assertStatus(statuses, workDir, file2, true, Status.STATUS_REMOVED, Status.STATUS_ADDED, Status.STATUS_NORMAL, false);

    client.reset(files, revisionCurrent, true, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, file2, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
}