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 File: Job.java    From onedev with 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 #2
Source File: GitConnector.java    From compiler with 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 File: GitConfigMonitorTest.java    From incubator-gobblin with 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 #4
Source File: GfsCommit.java    From ParallelGit with 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 #5
Source File: Tag.java    From orion.server with 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 File: APIDiff.java    From apidiff with 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 #7
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 #8
Source File: GitContentRepository.java    From studio with 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 File: GitFileSystemProviderNewFileSystemTest.java    From ParallelGit with 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 #10
Source File: ConfigRepositoryTest.java    From gocd with 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 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 #12
Source File: GitServiceImpl.java    From RefactoringMiner with 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 File: VersionControlGit.java    From mdw with 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 File: CommitUtilsGetHistoryTest.java    From ParallelGit with 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 #15
Source File: AppManager.java    From app-runner with 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 #16
Source File: Build.java    From onedev with 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 #17
Source File: APIDiff.java    From apidiff with 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 #18
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 #19
Source File: GitFlowGraphMonitorTest.java    From incubator-gobblin with 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 #20
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 #21
Source File: GitHubNotebookRepoTest.java    From zeppelin with 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 #22
Source File: LayoutHelper.java    From git-as-svn with 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 #23
Source File: GitConnector.java    From compiler with 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 #24
Source File: GitManager.java    From scava with 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 #25
Source File: Project.java    From onedev with 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 #26
Source File: Build.java    From onedev with 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 #27
Source File: ResetTest.java    From netbeans with 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);
}
 
Example #28
Source File: CacheRevision.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
public CacheRevision(
    @Nullable RevCommit svnCommit,
    @NotNull Map<String, String> renames,
    @NotNull Map<String, CacheChange> fileChange
) {
  this(svnCommit == null ? null : svnCommit.copy(), renames, fileChange);
}
 
Example #29
Source File: CommitUtilsCreateCommitTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void createCommitFromTree_theResultCommitRootTreeShouldBeTheSpecifiedTree() throws IOException {
  writeSomethingToCache();
  AnyObjectId treeId = CacheUtils.writeTree(cache, repo);
  RevCommit commit = CommitUtils.createCommit(someCommitMessage(), treeId, null, repo);
  assertEquals(treeId, commit.getTree());
}
 
Example #30
Source File: CommitUtilsCreateCommitTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void createCommit_theResultCommitShouldHaveTheInputMessage() throws IOException {
  writeSomethingToCache();
  String expectedMessage = "test message";
  RevCommit commit = CommitUtils.createCommit(expectedMessage, cache, null, repo);
  assertEquals(expectedMessage, commit.getFullMessage());
}