private List<RevCommit> getFirstCommits(Git git, ObjectId objectId, String path, int length) throws MissingObjectException, IncorrectObjectTypeException, NoHeadException, GitAPIException { LogCommand command = git.log(); if (objectId != null) { command.add(objectId); } if (StringUtils.isNotBlank(path)) { command.addPath(path); } Iterator<RevCommit> iterator = command.setMaxCount(length).call().iterator(); List<RevCommit> list = new ArrayList<RevCommit>(); for (int i = 0; i < length; i++) { if (iterator.hasNext()) { list.add(iterator.next()); } else { break; } } return list; }
public static void main(final String[] args) throws NoWorkTreeException, NoHeadException, IOException, GitAPIException { if (args.length != 4) { System.err .println("Usage <datafile> <prefix> <repositoryDir> <outputFilePrefix>"); System.exit(-1); } final SvnToGitMapper mapper = new SvnToGitMapper(args[2]); final RepentDataParser rdp = new RepentDataParser(new File(args[0]), mapper.mapSvnToGit(), args[1], new Predicate<Integer>() { @Override public boolean test(final Integer t) { return t > 250; } }); final List<Renaming> renamings = rdp.parse(); final Multimap<String, Renaming> renamingsPerSha = mapRenamingsToTargetSha(renamings); final BindingExtractor be = new BindingExtractor(args[2], renamingsPerSha); be.doWalk(); writeJson(args[3], "_variables.json", be.renamedVariablesDatapoints); writeJson(args[3], "_methoddeclarations.json", be.renamedMethodDeclarationsDatapoints); }
/** * @param args * @throws IOException * @throws GitAPIException * @throws NoHeadException * @throws NoWorkTreeException */ public static void main(final String[] args) throws IOException, NoWorkTreeException, NoHeadException, GitAPIException { if (args.length != 3) { System.err.println("Usage <datafile> <prefix> <repositoryDir>"); System.exit(-1); } final SvnToGitMapper mapper = new SvnToGitMapper(args[2]); final RepentDataParser rdp = new RepentDataParser(new File(args[0]), mapper.mapSvnToGit(), args[1], new Predicate<Integer>() { @Override public boolean test(final Integer t) { return t < 250; } }); final List<Renaming> renamings = rdp.parse(); for (final Renaming renaming : renamings) { System.out.println(renaming); } System.out.println("Num Renamings: " + renamings.size()); }
public BiMap<Integer, String> mapSvnToGit() throws IOException, NoWorkTreeException, NoHeadException, GitAPIException { final BiMap<Integer, String> mappings = HashBiMap.create(); final Git repository = GitCommitUtils .getGitRepository(repositoryDirectory); for (final RevCommit commit : GitCommitUtils .getAllCommitsTopological(repository)) { final String message = commit.getFullMessage(); if (!message.contains("git-svn-id")) { continue; } final Matcher matcher = svnIdMatcher.matcher(message); matcher.find(); mappings.put(Integer.parseInt(matcher.group(1)), commit.name()); } return mappings; }
public static List<CommitWrapper> getRepositoryHistory(Git git) throws NoHeadException, GitAPIException, MissingObjectException, IncorrectObjectTypeException, IOException { RevWalk walk = new RevWalk(git.getRepository()); RevCommit commit = null; List<CommitWrapper> commits = new ArrayList<>(); Iterable<RevCommit> logs = git.log().call(); Iterator<RevCommit> i = logs.iterator(); while (i.hasNext()) { commit = walk.parseCommit( i.next()); if(null != commit ) { CommitWrapper commitWrapper = new CommitWrapper(commit); commits.add(commitWrapper); } } return commits; }
public static void pullRepository() { try { logger.info("Scanning devices folder for changes."); git.add().addFilepattern(".").call(); Status status = git.status().call(); if (status.getChanged().size()>0 || status.getAdded().size()>0 || status.getModified().size()>0) { logger.info("Changes have been found. Doing a hard reset (removing user modifications)."); ResetCommand reset = git.reset(); reset.setMode(ResetType.HARD); reset.setRef(Constants.HEAD); reset.call(); } logger.info("Pulling changes from github."); git.pull().call(); } catch (NoHeadException e) { logger.info("Pull failed. Trying to clone repository instead"); closeRepository(); cloneRepository(); } catch (Exception e1) { closeRepository(); } }
public Git call(final GitOperationsStep gitOperationsStep, Git git, CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder) throws IllegalArgumentException, IOException, ConcurrentRefUpdateException, InvalidTagNameException, NoHeadException, GitAPIException { TagCommand tc = git.tag().setAnnotated(annotated) .setForceUpdate(forceUpdate).setSigned(signed); if (!Const.isEmpty(this.message)) { tc = tc.setMessage(gitOperationsStep .environmentSubstitute(this.message)); } if (!Const.isEmpty(this.name)) { tc = tc.setName(gitOperationsStep.environmentSubstitute(this.name)); } tc.call(); return git; }
public static int numCommits(final File directory, final List<String> keywords) throws NoHeadException, IOException, GitAPIException { List<String> allCommitMessages = GitCommitUtils .getAllCommitMessages(directory.getAbsolutePath()); int matchingCommits = 0; for (final String message : allCommitMessages) { boolean matches = false; for (final String keyword : keywords) { if (message.contains(keyword)) { matches = true; break; } } matchingCommits += matches ? 1 : 0; } return matchingCommits; }
/** * Return a list of all commit messages. * * @param repositoryDir * @return * @throws IOException * @throws NoHeadException * @throws GitAPIException */ public static List<String> getAllCommitMessages(final String repositoryDir) throws IOException, NoHeadException, GitAPIException { final List<String> commitSet = Lists.newArrayList(); final Git git = getGitRepository(repositoryDir); final RevWalk walk = new RevWalk(git.getRepository()); final Iterable<RevCommit> logs = git.log().call(); final Iterator<RevCommit> i = logs.iterator(); while (i.hasNext()) { final RevCommit commit = walk.parseCommit(i.next()); commitSet.add(commit.getFullMessage()); } return commitSet; }
/** * Get all the commits of a repository in a set. * * @param repositoryDir * the directory of the repository. Should not have trailing * slash. * @return * @throws IOException * @throws GitAPIException * @throws NoHeadException */ public static List<ObjectId> getCommits(final String repositoryDir) throws IOException, NoHeadException, GitAPIException { final List<ObjectId> commitSet = Lists.newArrayList(); final Git git = getGitRepository(repositoryDir); final RevWalk walk = new RevWalk(git.getRepository()); final Iterable<RevCommit> logs = git.log().call(); final Iterator<RevCommit> i = logs.iterator(); while (i.hasNext()) { final RevCommit commit = walk.parseCommit(i.next()); commitSet.add(commit.getId()); } return commitSet; }
/** * Return all the commits given the time. * * @param git * @return * @throws IOException * @throws NoHeadException * @throws GitAPIException */ public static SortedMap<Integer, RevCommit> getCommitsWithTime(final Git git) throws IOException, NoHeadException, GitAPIException { final SortedMap<Integer, RevCommit> commitsInTime = Maps.newTreeMap(); final RevWalk walk = new RevWalk(git.getRepository()); final Iterable<RevCommit> logs = git.log().call(); final Iterator<RevCommit> i = logs.iterator(); while (i.hasNext()) { final RevCommit commit = walk.parseCommit(i.next()); commitsInTime.put(commit.getCommitTime(), commit); } return commitsInTime; }
private void assertCommit(Path dir, String expectedSha1) throws IOException, NoHeadException, GitAPIException { try (Git git = Git.open(dir.toFile())) { Iterable<RevCommit> history = git.log().call(); String foundSha1 = history.iterator().next().getName(); Assert.assertEquals(String.format("Git repository in [%s] not at the expected revision", dir), expectedSha1, foundSha1); } }
@Test public void testCheckout() throws IOException, ScmException, NoHeadException, GitAPIException { Path dir = targetDir.resolve("test-repo"); SrcdepsCoreUtils.ensureDirectoryExistsAndEmpty(dir); /* first clone */ BuildRequest cloningRequest = BuildRequest.builder() // .srcVersion(SrcVersion.parse("0.0.1-SRC-tag-0.0.1")) // .dependentProjectRootDirectory(dir) // .projectRootDirectory(dir) // .scmUrl("git:https://github.com/srcdeps/srcdeps-test-artifact.git") // .versionsMavenPluginVersion(Maven.getDefaultVersionsMavenPluginVersion()) // .gradleModelTransformer(CharStreamSource.defaultModelTransformer()) // .build(); JGitScm jGitScm = new JGitScm(); jGitScm.checkout(cloningRequest); /* ensure that the tag is there through checking that it has a known commit hash */ assertCommit(dir, "19ef91ed30fd8b1a459803ee0c279dcf8e236184"); /* try if the fetch works after we have cloned already */ BuildRequest fetchingRequest = BuildRequest.builder() // .srcVersion(SrcVersion.parse("0.0.1-SRC-revision-0a5ab902099b24c2b13ed1dad8c5f537458bcc89")) // .dependentProjectRootDirectory(dir) // .projectRootDirectory(dir) // .scmUrl("git:https://github.com/srcdeps/srcdeps-test-artifact.git") // .versionsMavenPluginVersion(Maven.getDefaultVersionsMavenPluginVersion()) // .gradleModelTransformer(CharStreamSource.defaultModelTransformer()) // .build(); jGitScm.fetchAndReset(fetchingRequest); /* ensure that the WC's HEAD has the known commit hash */ assertCommit(dir, "0a5ab902099b24c2b13ed1dad8c5f537458bcc89"); }
private List<FileInfo> getFileInfos(Git git, ObjectId objectId, TreeWalk treeWalk) throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException, NoHeadException, GitAPIException { List<FileInfo> files = new ArrayList<>(); while (treeWalk.next()) { RevCommit commit = getFirstCommit(git, objectId, treeWalk.getPathString()); CommitInfo commitInfo = new CommitInfo(commit); files.add(new FileInfo(treeWalk.getObjectId(0), treeWalk.isSubtree(), treeWalk.getNameString(), treeWalk.getPathString(), commitInfo)); } return files; }
/** * @param args * @throws GitAPIException * @throws IOException * @throws NoHeadException * @throws NoWorkTreeException */ public static void main(final String[] args) throws NoWorkTreeException, NoHeadException, IOException, GitAPIException { if (args.length != 1) { System.err.println("Usage <repository>"); System.exit(-1); } final SvnToGitMapper mapper = new SvnToGitMapper(args[0]); System.out.println(mapper.mapSvnToGit()); }
private OneShotEvent doHandle(MergeRequestHookTriggerHandler mergeRequestHookTriggerHandler, MergeRequestObjectAttributesBuilder objectAttributes) throws GitAPIException, IOException, NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, AmbiguousObjectException, IncorrectObjectTypeException, MissingObjectException, InterruptedException { Git.init().setDirectory(tmp.getRoot()).call(); tmp.newFile("test"); Git git = Git.open(tmp.getRoot()); git.add().addFilepattern("test"); RevCommit commit = git.commit().setMessage("test").call(); ObjectId head = git.getRepository().resolve(Constants.HEAD); String repositoryUrl = tmp.getRoot().toURI().toString(); final OneShotEvent buildTriggered = new OneShotEvent(); FreeStyleProject project = jenkins.createFreeStyleProject(); project.setScm(new GitSCM(repositoryUrl)); project.getBuildersList().add(new TestBuilder() { @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { buildTriggered.signal(); return true; } }); project.setQuietPeriod(0); mergeRequestHookTriggerHandler.handle(project, mergeRequestHook() .withObjectAttributes(objectAttributes .withTargetBranch("refs/heads/" + git.nameRev().add(head).call().get(head)) .withLastCommit(commit().withAuthor(user().withName("test").build()).withId(commit.getName()).build()) .build()) .withProject(project() .withWebUrl("https://gitlab.org/test.git") .build() ) .build(), true, BranchFilterFactory.newBranchFilter(branchFilterConfig().build(BranchFilterType.All)), newMergeRequestLabelFilter(null)); buildTriggered.block(10000); return buildTriggered; }
public Git call(final GitOperationsStep gitOperationsStep, Git git, CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder) throws IllegalArgumentException, IOException, WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException, InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException, TransportException, GitAPIException { git.pull().setCredentialsProvider(cp).setRebase(rebase).call(); return git; }
public Git call(final GitOperationsStep gitOperationsStep, Git git, CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder) throws IllegalArgumentException, IOException, NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, GitAPIException { CommitCommand cc = git .commit() .setAuthor( gitOperationsStep .environmentSubstitute(this.authorName == null ? "" : this.authorName), gitOperationsStep .environmentSubstitute(this.authorEmail == null ? "" : this.authorEmail)) .setCommitter( gitOperationsStep .environmentSubstitute(this.committerName == null ? "" : this.committerName), gitOperationsStep .environmentSubstitute(this.committerEmail == null ? "" : this.committerName)); if (!Const.isEmpty(this.commitMessage)) { cc = cc.setMessage(gitOperationsStep .environmentSubstitute(this.commitMessage)); } cc.setAll(all).setInsertChangeId(insertChangeId).setAmend(amend).call(); return git; }
/** * @param args * @throws GitAPIException * @throws IOException * @throws NoHeadException */ public static void main(String[] args) throws NoHeadException, IOException, GitAPIException { if (args.length < 3) { System.err .println("Usage single|multiple <directory> <keywords...>"); System.exit(-1); } File directory = new File(args[1]); checkArgument(directory.isDirectory()); List<String> keywords = Lists.newArrayList(); for (int i = 2; i < args.length; i++) { keywords.add(args[i]); } if (args[0].equals("single")) { System.out.println(numCommits(directory, keywords)); } else if (args[0].equals("multiple")) { for (final File project : directory.listFiles()) { try { System.out.println(project.getName() + "," + numCommits(project, keywords)); } catch (Throwable e) { LOGGER.warning("Failed to get count for project " + project + " because " + ExceptionUtils.getFullStackTrace(e)); } } } else { throw new IllegalArgumentException("Unrecognized " + args[0]); } }
public void buildData(final String gitDirectory) throws NoHeadException, IOException, GitAPIException { final SortedMap<Integer, RevCommit> allCommits = GitCommitUtils .getCommitsWithTime(GitCommitUtils .getGitRepository(gitDirectory)); final Integer startTime = allCommits.firstKey(); final Range<Integer> activityPeriod = Range.closed(startTime, allCommits.lastKey()); final Map<GitCommiterIdentity, Range<Integer>> commitTimeRanges = getCommitActivityTimePerUser( allCommits, GRACE_PERIOD); // Split period into 6 months chunks final int nChunks = (int) Math.ceil(((double) activityPeriod .upperEndpoint() - activityPeriod.lowerEndpoint()) / GRACE_PERIOD); for (int i = 0; i < nChunks; i++) { final Range<Integer> currentPeriod = Range.closedOpen(startTime + i * GRACE_PERIOD, startTime + (i + 1) * GRACE_PERIOD); int nActiveCommiters = 0; for (final Range<Integer> userActivityPeriod : commitTimeRanges .values()) { if (userActivityPeriod.isConnected(currentPeriod)) { nActiveCommiters++; } } numActiveCommiters.put(currentPeriod, nActiveCommiters); } }
/** * Return all the commits in topological order, starting from the first * commit. * * @param git * @return * @throws NoWorkTreeException * @throws IOException * @throws NoHeadException * @throws GitAPIException */ public static List<RevCommit> getAllCommitsTopological(final Git git) throws NoWorkTreeException, IOException, NoHeadException, GitAPIException { if (!git.log().call().iterator().hasNext()) { return Collections.emptyList(); } final List<RevCommit> commitList = Lists.newArrayList(); final RevWalk rw = new RevWalk(git.getRepository()); final AnyObjectId headId = git.getRepository().resolve(Constants.HEAD); final RevCommit head = rw.parseCommit(headId); rw.sort(RevSort.REVERSE, true); rw.sort(RevSort.TOPO, true); rw.markStart(head); commitList.add(head); RevCommit currentCommit = rw.next(); while (currentCommit != null) { commitList.add(currentCommit); currentCommit = rw.next(); } return commitList; }
/** * Recursively walk down a branch creating BranchElement objects. * * @param allCommits * @param git * @throws GitAPIException * @throws NoHeadException */ private CommitNode walkBranch(final Map<String, CommitNode> allCommits, ObjectId objectId, final RevWalk walk, final Git git) throws MissingObjectException, IncorrectObjectTypeException, IOException, NoHeadException, GitAPIException { CommitNode element = null; // RevCommit commit = walk.parseCommit(objectId); RevCommit commit = git.log().setMaxCount(1).add(objectId).call() .iterator().next(); try { // FIXME Change this to use a map of objectId to CommitNode, only // creating objects on the first visit. if (allCommits.containsKey(objectId.getName())) { element = allCommits.get(objectId.getName()); } else { element = new CommitNode(commit); allCommits.put(objectId.getName(), element); } if (commit.getParentCount() > 0) { commit = commit.getParent(0); objectId = commit.getId(); element.addParent(walkBranch(allCommits, objectId, walk, git)); } else { objectId = null; } } catch (final NullPointerException e) { getOutputStream().println("NPE!!"); commit = null; } return element; }
@Before public void createVersionFactory() throws IOException, NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, GitAPIException { repo = createRepository(); git = initializeGitFlow(repo); versionFactory = new TagBasedVersionFactory(); }
@Test public void testHeadPointsAtStable() throws ConcurrentRefUpdateException, InvalidTagNameException, NoHeadException, GitAPIException, NoWorkTreeException, MissingObjectException, IncorrectObjectTypeException, IOException { tag("v1.0.0"); validateStableTag("1.0.0"); }
@Test public void testHeadPointsAtStableWhenUsingPrefix() throws ConcurrentRefUpdateException, InvalidTagNameException, NoHeadException, GitAPIException, NoWorkTreeException, MissingObjectException, IncorrectObjectTypeException, IOException { versionFactory = new TagBasedVersionFactory("myPrefix"); tag("myPrefix-v1.0.0"); validateStableTag("1.0.0"); }
@Test public void testHeadPointsOneAboveStable() throws ConcurrentRefUpdateException, InvalidTagNameException, NoHeadException, GitAPIException, NoWorkTreeException, MissingObjectException, IncorrectObjectTypeException, IOException { tag("v1.0.0"); RevCommit head = makeCommit(); validateUnstable("1.0.0", 1, head, Dirty.NO, DOT); }
@Test public void testCommitCount() throws NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, GitAPIException, NoWorkTreeException, IOException { tag("v0.1.1-rc"); makeCommit(); makeCommit(); RevCommit head = makeCommit(); validateUnstable("0.1.1-rc", 3, head, Dirty.NO, DOT); }
@Test public void testVUnnecessary() throws ConcurrentRefUpdateException, InvalidTagNameException, NoHeadException, GitAPIException, NoWorkTreeException, IOException { makeCommit(); tag("0.1.0"); validateStableTag("0.1.0"); }
@Test public void testUnstableIsDirty() throws ConcurrentRefUpdateException, InvalidTagNameException, NoHeadException, GitAPIException, NoWorkTreeException, MissingObjectException, IncorrectObjectTypeException, IOException { RevCommit commit = makeCommit(); tag("0.1.0-dev"); dirtyRepo(); validateUnstable("0.1.0-dev", 0, commit, Dirty.YES, DOT); }
@Test public void testOrdering() throws ConcurrentRefUpdateException, InvalidTagNameException, NoHeadException, GitAPIException, NoWorkTreeException, MissingObjectException, IncorrectObjectTypeException, IOException { tag("3.0.0"); makeCommit(); RevCommit head = makeCommit(); tag("1.0.0"); validateUnstable("3.0.0", 2, head, Dirty.NO, DASH); }
public static void commit(Repo repo, boolean stageAll, boolean isAmend, String msg, String authorName, String authorEmail) throws Exception, NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, GitAPIException, StopTaskException { Context context = SGitApplication.getContext(); StoredConfig config = repo.getGit().getRepository().getConfig(); String committerEmail = config.getString("user", null, "email"); String committerName = config.getString("user", null, "name"); if (committerName == null || committerName.equals("")) { committerName = Profile.getUsername(context); } if (committerEmail == null || committerEmail.equals("")) { committerEmail = Profile.getEmail(context); } if (committerName.isEmpty() || committerEmail.isEmpty()) { throw new Exception("Please set your name and email"); } if (msg.isEmpty()) { throw new Exception("Please include a commit message"); } CommitCommand cc = repo.getGit().commit() .setCommitter(committerName, committerEmail).setAll(stageAll) .setAmend(isAmend).setMessage(msg); if (authorName != null && authorEmail != null) { cc.setAuthor(authorName, authorEmail); } cc.call(); repo.updateLatestCommitInfo(); }
@Test public void testInit_gitLogApiException() throws RevisionGeneratorException, GitAPIException, IOException { String branch = "master"; String hash = UUID.randomUUID().toString().replaceAll("-", ""); String abbreviatedHash = hash.substring(0, 5); AbbreviatedObjectId abbreviatedObjectId = AbbreviatedObjectId.fromString(abbreviatedHash); Repository repo = mock(Repository.class); Ref headRef = mock(Ref.class); ObjectId headObjectId = mock(ObjectId.class); LogCommand logCmd = mock(LogCommand.class); GitAPIException exception = new NoHeadException("Dummy Git API Exception"); when(git.getRepository()).thenReturn(repo); when(repo.isBare()).thenReturn(Boolean.FALSE); when(repo.getBranch()).thenReturn(branch); when(repo.getRef(eq("HEAD"))).thenReturn(headRef); when(headRef.getObjectId()).thenReturn(headObjectId); when(headObjectId.abbreviate(eq(5))).thenReturn(abbreviatedObjectId); when(git.log()).thenReturn(logCmd); when(logCmd.setMaxCount(1)).thenReturn(logCmd); when(logCmd.call()).thenThrow(exception); exceptions.expect(RevisionGeneratorException.class); exceptions.expectMessage("Issue getting Git CommitTime"); exceptions.expectCause(IsInstanceOf.any(GitAPIException.class)); try { item.init(git, logger); } finally { verify(git).getRepository(); verify(git).log(); verify(repo).isBare(); verify(repo).getRef(eq("HEAD")); verify(repo).getBranch(); verify(headRef, times(2)).getObjectId(); verify(headObjectId).abbreviate(eq(5)); verify(logCmd).setMaxCount(eq(1)); verify(logCmd).call(); verifyNoMoreInteractions(git); verifyNoMoreInteractions(repo); verifyNoMoreInteractions(headRef); verifyNoMoreInteractions(headObjectId); verifyNoMoreInteractions(logCmd); verifyZeroInteractions(logger); } }
@Test public void testInit_gitStatusApiException() throws RevisionGeneratorException, GitAPIException, IOException { String branch = "master"; String hash = UUID.randomUUID().toString().replaceAll("-", "")+UUID.randomUUID().toString().replaceAll("-", "").substring(0,8); String abbreviatedHash = hash.substring(0, 5); AbbreviatedObjectId abbreviatedObjectId = AbbreviatedObjectId.fromString(abbreviatedHash); int commitTime = (int) (System.currentTimeMillis()/1000); RevCommit headCommit = createRevCommit(hash, commitTime); Repository repo = mock(Repository.class); Ref headRef = mock(Ref.class); ObjectId headObjectId = mock(ObjectId.class); LogCommand logCmd = mock(LogCommand.class); StatusCommand statusCmd = mock(StatusCommand.class); GitAPIException exception = new NoHeadException("Dummy Git API Exception"); when(git.getRepository()).thenReturn(repo); when(repo.isBare()).thenReturn(Boolean.FALSE); when(repo.getBranch()).thenReturn(branch); when(repo.getRef(eq("HEAD"))).thenReturn(headRef); when(headRef.getObjectId()).thenReturn(headObjectId); when(headObjectId.abbreviate(eq(5))).thenReturn(abbreviatedObjectId); when(git.log()).thenReturn(logCmd); when(logCmd.setMaxCount(1)).thenReturn(logCmd); when(logCmd.call()).thenReturn(Arrays.asList(headCommit)); when(git.status()).thenReturn(statusCmd); when(statusCmd.call()).thenThrow(exception); exceptions.expect(RevisionGeneratorException.class); exceptions.expectMessage("Issue getting Git Status"); exceptions.expectCause(IsInstanceOf.any(GitAPIException.class)); try { item.init(git, logger); } finally { verify(git).getRepository(); verify(git).log(); verify(repo).isBare(); verify(repo).getRef(eq("HEAD")); verify(repo).getBranch(); verify(headRef, times(2)).getObjectId(); verify(headObjectId).abbreviate(eq(5)); verify(logCmd).setMaxCount(eq(1)); verify(logCmd).call(); verify(git).status(); verify(statusCmd).call(); verifyNoMoreInteractions(git); verifyNoMoreInteractions(repo); verifyNoMoreInteractions(headRef); verifyNoMoreInteractions(headObjectId); verifyNoMoreInteractions(logCmd); verifyNoMoreInteractions(statusCmd); verifyZeroInteractions(logger); } }
private RevCommit getFirstCommit(Git git, ObjectId objectId, String path) throws MissingObjectException, IncorrectObjectTypeException, NoHeadException, GitAPIException { List<RevCommit> commits = getFirstCommits(git, objectId, path, 1); return commits.get(0); }
protected List<GitInformationCommit> loadCommits(Repository repository, Git git, Ref branch) throws GitAPIException, NoHeadException, IOException, MissingObjectException, IncorrectObjectTypeException, AmbiguousObjectException { RevWalk revwalk = new RevWalk(repository); List<GitInformationCommit> result = new ArrayList<>(); for (Ref rbranch : git.branchList().call()) { if (rbranch.getName().equals(branch.getName())) { Iterable<RevCommit> commits = git.log().all().call(); for (RevCommit commit : commits) { boolean foundInThisBranch = false; RevCommit targetCommit = revwalk.parseCommit(repository.resolve(commit.getName())); for (Map.Entry<String, Ref> e : repository.getAllRefs().entrySet()) { if (e.getKey().startsWith(Constants.R_HEADS)) { if (revwalk.isMergedInto(targetCommit, revwalk.parseCommit(e.getValue().getObjectId()))) { String foundInBranch = e.getValue().getName(); if (branch.getName().equals(foundInBranch)) { foundInThisBranch = true; break; } } } } if (foundInThisBranch) { GitInformationCommit cmt = new GitInformationCommit(); cmt.Checksum = commit.getName(); cmt.Author = commit.getAuthorIdent().getName(); cmt.Mail = commit.getAuthorIdent().getEmailAddress(); cmt.Date = new Date(commit.getCommitTime()); cmt.Message = commit.getFullMessage(); result.add(cmt); } } } } return result; }
public static void main(String[] args) throws IOException, URISyntaxException, NoHeadException, GitAPIException { (new MainFrame()).setVisible(true); }
private Ref tag(String tagName) throws ConcurrentRefUpdateException, InvalidTagNameException, NoHeadException, GitAPIException { return git.tag().setMessage("blah").setName(tagName).call(); }
private RevCommit makeCommit() throws NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, GitAPIException { return git.commit().setCommitter(COMMITTER).setMessage("some commit").call(); }