org.kohsuke.github.GHCommit Java Examples

The following examples show how to use org.kohsuke.github.GHCommit. 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: CommitHistoryViewTest.java    From DotCi with MIT License 6 votes vote down vote up
@Test
public void should_group_commit_statueses_by_context() throws IOException {
    final CommitHistoryView commitHistoryView = new CommitHistoryView();
    final DynamicBuild build = mock(DynamicBuild.class);
    final GHRepository githubRepo = mock(GHRepository.class);
    when(build.getGithubRepository()).thenReturn(githubRepo);

    final PagedIterable<GHCommitStatus> commitStatusesList = mock(PagedIterable.class);
    final GHCommitStatus commitStatus1 = mock(GHCommitStatus.class);
    final GHCommitStatus commitStatus2 = mock(GHCommitStatus.class);

    when(commitStatus1.getContext()).thenReturn("Default");
    when(commitStatus2.getContext()).thenReturn("DotCi");

    when(commitStatusesList.asList()).thenReturn(Arrays.asList(commitStatus1, commitStatus2));
    final GHCommit currentCommit = mock(GHCommit.class);
    when(githubRepo.getCommit(null)).thenReturn(currentCommit);
    when(currentCommit.listStatuses()).thenReturn(commitStatusesList);
    when(githubRepo.getLastCommitStatus(null)).thenReturn(commitStatus1);
    commitHistoryView.onLoad(build);
    final Map<String, List<GHCommitStatus>> commitStatuses = commitHistoryView.getCommitStatuses();

    Assert.assertEquals(commitStatuses.get("Default").get(0), commitStatus1);
    Assert.assertEquals(commitStatuses.get("DotCi").get(0), commitStatus2);
}
 
Example #2
Source File: GithubConnector.java    From apollo with Apache License 2.0 6 votes vote down vote up
public Optional<CommitDetails> getCommitDetails(String githubRepo, String sha) {
    try {
        logger.info("Getting commit details for sha {} on url {}", sha, githubRepo);
        GHCommit commit = gitHub.getRepository(githubRepo).getCommit(sha);

        GHUser author = commit.getAuthor();
        logger.info("1) Author of commit sha {} is {}", sha, author);
        String committerName = (author == null) ? null : author.getName();
        if (committerName == null || committerName.isEmpty()) {
            logger.info("2) Committer name of commit sha {} is {}", sha, committerName);
            committerName = author.getLogin();
            logger.info("3) Committer name of commit sha {} is {}", sha, committerName);
        }

        CommitDetails commitDetails = new CommitDetails(sha, commit.getHtmlUrl().toString(),
                commit.getCommitShortInfo().getMessage(), commit.getCommitDate(), commit.getLastStatus(),
                author.getAvatarUrl(), committerName);
        logger.info("CommitDetails: {}", commitDetails);
        return Optional.of(commitDetails);
    } catch (IOException e) {
        logger.warn("Could not get commit details from Github!", e);
        return Optional.empty();
    }
}
 
Example #3
Source File: GithubConnector.java    From apollo with Apache License 2.0 6 votes vote down vote up
public boolean isCommitInBranchHistory(String githubRepo, String branch, String sha) {

        // First get the initial commit so we can reduce the number of requests to github
        Optional<CommitDetails> commit = getCommitDetails(githubRepo, sha);

        if (commit.isPresent()) {

            Optional<List<GHCommit>> allCommitsOnABranch = getAllCommitsOnABranch(githubRepo, branch, commit.get().getCommitDate());
            return allCommitsOnABranch.map(ghCommits -> ghCommits
                    .stream()
                    .anyMatch(ghCommit -> ghCommit.getSHA1().equals(sha)))
                    .orElse(false);
        }

        return false;
    }
 
Example #4
Source File: GitHubStatusNotificationStep.java    From pipeline-githubnotify-step-plugin with MIT License 6 votes vote down vote up
@Override
protected Void run() throws Exception {
    String targetUrl = getTargetUrl();
    String credentialsId = getCredentialsId();
    String repo = getRepo();
    String account = getAccount();
    GHRepository repository = getRepoIfValid(credentialsId, step.getGitApiUrl(), account, repo, run.getParent());
    String sha1 = getSha1();
    GHCommit commit = null;
    try {
        commit = repository.getCommit(sha1);
    } catch (IOException ex) {
        throw new IllegalArgumentException(INVALID_COMMIT, ex);
    }
    repository.createCommitStatus(commit.getSHA1(),
            step.getStatus(), targetUrl, step.getDescription(), step.getContext());
    return null;
}
 
Example #5
Source File: GitHubBranchCommitEventTest.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    when(mockListener.getLogger()).thenReturn(logger);

    commits = new GHCompare.Commit[0];
    check = new GitHubBranchCommitEvent(Arrays.asList(mockCommitCheck)) {
        @Override
        GHCompare.Commit[] getComparedCommits(GitHubBranch localBranch, GHBranch remoteBranch) throws IOException {
            return commits;
        }

        @Override
        GHCommit getLastCommit(GHBranch remoteBranch) throws IOException {
            return mockCommit;
        }
    };
}
 
Example #6
Source File: GitHubBranchCommitEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubBranchCause check(@Nonnull GitHubBranchDecisionContext context) throws IOException {
    GHBranch remoteBranch = context.getRemoteBranch();
    GitHubBranch localBranch = context.getLocalBranch();
    GitHubBranchRepository localRepo = context.getLocalRepo();
    TaskListener listener = context.getListener();
    final PrintStream logger = listener.getLogger();
    Function<GitHubBranchCommitCheck, GitHubBranchCause> function;

    if (isNull(localBranch)) {
        GHCommit commit = getLastCommit(remoteBranch);
        function = event -> event.check(remoteBranch, localRepo, commit);
    } else {
        GHCompare.Commit[] commits = getComparedCommits(localBranch, remoteBranch);
        function = event -> event.check(remoteBranch, localRepo, commits);
    }

    return check(remoteBranch, function, logger);
}
 
Example #7
Source File: TestSequencerCollector.java    From repairnator with MIT License 5 votes vote down vote up
@Test
public void testDiffSaveAndPush() throws GitAPIException, IOException{
    
    ArrayList<SequencerCollectorPatch> emptyList = new ArrayList<SequencerCollectorPatch>();
    ArrayList<SequencerCollectorHunk> mockHunkList = new ArrayList<SequencerCollectorHunk>(); mockHunkList.add(
            new SequencerCollectorHunk(1, "file.java", "hunk1")); 

    //Mock external calls
    Mockito.when(github.getRepository(Mockito.anyString())).thenReturn(mockRepo);
    Mockito.when(mockRepo.getCommit(Mockito.anyString())).thenReturn(mockCommit);
    
    
    //Mock hunk filter since mock commit is used
    Mockito.when(filter.getCommitPatches(Mockito.any(GHCommit.class), Mockito.anyBoolean(), Mockito.anyBoolean())).thenReturn(emptyList);
    Mockito.when(filter.getHunks(Mockito.any(ArrayList.class), Mockito.anyBoolean(), Mockito.anyInt())).thenReturn(mockHunkList);
    
    //Mock save/commit/push methods
    Mockito.doNothing().when(collector).saveFileDiff(Mockito.anyString(), Mockito.anyString());
    Mockito.doNothing().when(collector).commitAndPushDiffs();
    
    //this function gets continuously called as long as the SequencerLearningScanner 
    //is running. Here we test: save on single finding, and commit/push on batch completion
    //batchSize = 100
    for(int sha = 0; sha < 100; ++sha){
        collector.handle("slug/slug" , Integer.toHexString(sha));
    }
    
    Mockito.verify(collector, Mockito.times(100)).saveFileDiff(Mockito.anyString(), Mockito.anyString());
    Mockito.verify(collector, Mockito.times(1)).commitAndPushDiffs();
    
}
 
Example #8
Source File: DotCiUpstreamTriggerCause.java    From DotCi with MIT License 5 votes vote down vote up
private GHCommit getCommitFromSha(DynamicProject targetJob, String sha) {
    try {
        return new GithubRepositoryService(targetJob.getGithubRepoUrl()).getGithubRepository().getCommit(sha);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: DotCiUpstreamTriggerCause.java    From DotCi with MIT License 5 votes vote down vote up
private GHCommit getHeadCommitForBranch(DynamicProject targetJob, String branch) {
    try {
        return new GithubRepositoryService(targetJob.getGithubRepoUrl()).getHeadCommitForBranch(branch);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: DotCiUpstreamTriggerCause.java    From DotCi with MIT License 5 votes vote down vote up
public DotCiUpstreamTriggerCause(DynamicBuild sourceBuild, DynamicProject targetJob, Map<String, String> jobOptions) {
    branch = new GitBranch(jobOptions.get("BRANCH"));
    GHCommit commit;
    if (jobOptions.containsKey("SHA")) {
        commit = getCommitFromSha(targetJob, jobOptions.get("SHA"));
    } else {
        commit = getHeadCommitForBranch(targetJob, branch.toString());
    }
    this.pusher = sourceBuild.getCause().getPusher();
    this.description = "Started by upstream job  " + sourceBuild.getParent().getFullDisplayName() + ".: " + sourceBuild.getNumber();
    this.sha = commit.getSHA1();
    this.parentSha = commit.getParentSHA1s().size() > 0 ? commit.getParentSHA1s().get(0) : null;
    this.commitInfo = new CommitInfo(commit, branch);
}
 
Example #11
Source File: ManualBuildCause.java    From DotCi with MIT License 5 votes vote down vote up
public ManualBuildCause(final GitBranch branch, final GHCommit commit, final String parentSha, final String user) throws IOException {
    this.branch = branch;
    this.parentSha = parentSha;
    this.sha = commit.getSHA1();
    this.user = user;
    this.commitInfo = new CommitInfo(commit, branch);
    this.changeLogEntries = getChangeLogEntriescommit(commit);
}
 
Example #12
Source File: GithubLogEntry.java    From DotCi with MIT License 5 votes vote down vote up
public GithubLogEntry(final GHCommit commit) throws IOException {
    this.message = commit.getCommitShortInfo().getMessage();
    this.githubUrl = commit.getHtmlUrl().toExternalForm();
    this.commitId = commit.getSHA1();
    this.affectedPaths = commit.getFiles().stream().map(file -> file.getFileName()).collect(Collectors.toList());

}
 
Example #13
Source File: BuildCause.java    From DotCi with MIT License 5 votes vote down vote up
public CommitInfo(final GHCommit commit, final GitBranch branch) {
    this.sha = commit.getSHA1();
    try {
        this.message = commit.getCommitShortInfo().getMessage();
        this.committerName = commit.getCommitShortInfo().getCommitter().getName();
        this.committerEmail = commit.getCommitShortInfo().getCommitter().getEmail();
        this.commitUrl = commit.getOwner().getHtmlUrl() + "/commit/" + this.sha;
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    this.branch = branch.toString();
    this.avatarUrl = null;
}
 
Example #14
Source File: DynamicBuildModel.java    From DotCi with MIT License 5 votes vote down vote up
private String getParentSha(final GHCommit commit, final GitBranch gitBranch) throws IOException {
    final String parentSha;
    if (gitBranch.isPullRequest()) {
        final GHPullRequest pullRequest = this.githubRepositoryService.getGithubRepository().getPullRequest(gitBranch.pullRequestNumber());
        parentSha = pullRequest.getBase().getSha();

    } else {
        parentSha = (commit.getParentSHA1s() != null && commit.getParentSHA1s().size() > 0) ? commit.getParentSHA1s().get(0) : null;
    }
    return parentSha;
}
 
Example #15
Source File: TestGitHubRepository.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void createSubmodule(
    TestGitHubRepository pathToRootContentDirectory, String pathForSubmodule) throws IOException {
  String submoduleSha = createTreeWithSubmodule(pathToRootContentDirectory, pathForSubmodule);

  GHCommit treeCommit =
      ghRepo.createCommit().tree(submoduleSha).message("Create submodule").create();

  getReferenceToDefaultBranch().updateTo(treeCommit.getSHA1(), true);
  setupSubmoduleConfig(pathToRootContentDirectory, pathForSubmodule);
}
 
Example #16
Source File: GitHelper.java    From repairnator with MIT License 5 votes vote down vote up
private String getLastKnowParent(GitHub gh, GHRepository ghRepo, Git git, String oldCommitSha, AbstractStep step) throws IOException {
    showGitHubRateInformation(gh, step);
    GHCommit commit = ghRepo.getCommit(oldCommitSha); // get the deleted
    // commit from GH
    List<String> commitParents = commit.getParentSHA1s();

    if (commitParents.isEmpty()) {
        step.addStepError("The following commit does not have any parent in GitHub: " + oldCommitSha
                + ". It cannot be resolved.");
        return null;
    }

    if (commitParents.size() > 1) {
        this.getLogger().debug("Step " + step.getName() + " - The commit has more than one parent : " + commit.getHtmlUrl());
    }

    String parent = commitParents.get(0);

    try {
        ObjectId commitObject = git.getRepository().resolve(parent);
        git.getRepository().open(commitObject);

        return parent;
    } catch (MissingObjectException e) {
        return getLastKnowParent(gh, ghRepo, git, parent, step);
    }
}
 
Example #17
Source File: GithubConnector.java    From apollo with Apache License 2.0 5 votes vote down vote up
private Optional<List<GHCommit>> getAllCommitsOnABranch(String githubRepo, String branch, Date since) {
    try {
        // Reducing 1 hour of the "since" as it is not getting the desired commits on the exact range
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(since);
        calendar.add(Calendar.DATE, -1);

        return Optional.of(gitHub.getRepository(githubRepo).queryCommits().since(calendar.getTime()).from(branch).list().asList());
    } catch (Throwable e) {  // The library is throwing and Error and not an exception, for god sake
        logger.warn("Could not get all commits on branch {} for repo {}", branch, githubRepo, e);
        return Optional.empty();
    }
}
 
Example #18
Source File: GitHubStatusNotificationStep.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
private static GHCommit getCommitIfValid(String credentialsId, String gitApiUrl, String account, String repo, String sha, Item context) throws IOException {
    GHRepository repository = getRepoIfValid(credentialsId, gitApiUrl, account, repo, context);
    GHCommit commit = repository.getCommit(sha);
    if (commit == null) {
        throw new IllegalArgumentException(INVALID_COMMIT);
    }
    return commit;
}
 
Example #19
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void build() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #20
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithFolderCredentials() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

    Folder f = jenkins.jenkins.createProject(Folder.class, "folder" + jenkins.jenkins.getItems().size());
    CredentialsStore folderStore = getFolderStore(f);
    folderStore.addCredentials(Domain.global(),
            new DummyCredentials(CredentialsScope.GLOBAL, "user", "password"));

    WorkflowJob p = f.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #21
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildEnterprise() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.when(ghb.withEndpoint("https://api.example.com")).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', gitApiUrl:'https://api.example.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #22
Source File: GitHubSCMProbe.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private GHCommit commit() throws IOException {
    if (commit == null) {
        synchronized (this) {
            if (commit == null) {
                commit = repo().getCommit(revision.getHash());
            }
        }
    }
    return commit;
}
 
Example #23
Source File: GitHistoryRefactoringMinerImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private String populateWithGitHubAPI(String cloneURL, String currentCommitId,
		List<String> filesBefore, List<String> filesCurrent, Map<String, String> renamedFilesHint) throws IOException {
	logger.info("Processing {} {} ...", cloneURL, currentCommitId);
	GitHub gitHub = connectToGitHub();
	String repoName = extractRepositoryName(cloneURL);
	GHRepository repository = gitHub.getRepository(repoName);
	GHCommit commit = repository.getCommit(currentCommitId);
	String parentCommitId = commit.getParents().get(0).getSHA1();
	List<GHCommit.File> commitFiles = commit.getFiles();
	for (GHCommit.File commitFile : commitFiles) {
		if (commitFile.getFileName().endsWith(".java")) {
			if (commitFile.getStatus().equals("modified")) {
				filesBefore.add(commitFile.getFileName());
				filesCurrent.add(commitFile.getFileName());
			}
			else if (commitFile.getStatus().equals("added")) {
				filesCurrent.add(commitFile.getFileName());
			}
			else if (commitFile.getStatus().equals("removed")) {
				filesBefore.add(commitFile.getFileName());
			}
			else if (commitFile.getStatus().equals("renamed")) {
				filesBefore.add(commitFile.getPreviousFilename());
				filesCurrent.add(commitFile.getFileName());
				renamedFilesHint.put(commitFile.getPreviousFilename(), commitFile.getFileName());
			}
		}
	}
	return parentCommitId;
}
 
Example #24
Source File: GitHubSCMFileSystem.java    From github-branch-source-plugin with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean changesSince(SCMRevision revision, @NonNull OutputStream changeLogStream)
        throws UnsupportedOperationException, IOException, InterruptedException {
    if (Objects.equals(getRevision(), revision)) {
        // special case where somebody is asking one of two stupid questions:
        // 1. what has changed between the latest and the latest
        // 2. what has changed between the current revision and the current revision
        return false;
    }
    int count = 0;
    FastDateFormat iso = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZ");
    StringBuilder log = new StringBuilder(1024);
    String endHash;
    if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl) {
        endHash = ((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash().toLowerCase(Locale.ENGLISH);
    } else {
        endHash = null;
    }
    // this is the format expected by GitSCM, so we need to format each GHCommit with the same format
    // commit %H%ntree %T%nparent %P%nauthor %aN <%aE> %ai%ncommitter %cN <%cE> %ci%n%n%w(76,4,4)%s%n%n%b
    for (GHCommit commit: repo.queryCommits().from(ref).pageSize(GitSCM.MAX_CHANGELOG).list()) {
        if (commit.getSHA1().toLowerCase(Locale.ENGLISH).equals(endHash)) {
            break;
        }
        log.setLength(0);
        log.append("commit ").append(commit.getSHA1()).append('\n');
        log.append("tree ").append(commit.getTree().getSha()).append('\n');
        log.append("parent");
        for (String parent: commit.getParentSHA1s()) {
            log.append(' ').append(parent);
        }
        log.append('\n');
        GHCommit.ShortInfo info = commit.getCommitShortInfo();
        log.append("author ")
                .append(info.getAuthor().getName())
                .append(" <")
                .append(info.getAuthor().getEmail())
                .append("> ")
                .append(iso.format(info.getAuthoredDate()))
                .append('\n');
        log.append("committer ")
                .append(info.getCommitter().getName())
                .append(" <")
                .append(info.getCommitter().getEmail())
                .append("> ")
                .append(iso.format(info.getCommitDate()))
                .append('\n');
        log.append('\n');
        String msg = info.getMessage();
        if (msg.endsWith("\r\n")) {
            msg = msg.substring(0, msg.length() - 2);
        } else  if (msg.endsWith("\n")) {
            msg = msg.substring(0, msg.length() - 1);
        }
        msg = msg.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "\n    ");
        log.append("    ").append(msg).append('\n');
        changeLogStream.write(log.toString().getBytes(StandardCharsets.UTF_8));
        changeLogStream.flush();
        count++;
        if (count >= GitSCM.MAX_CHANGELOG) {
            break;
        }
    }
    return count > 0;
}
 
Example #25
Source File: FunnyGuildsVersion.java    From FunnyGuilds with Apache License 2.0 4 votes vote down vote up
public static void isNewAvailable(CommandSender sender, boolean force) {
    if (!FunnyGuilds.getInstance().getPluginConfiguration().updateInfo && !force) {
        return;
    }

    if (!sender.hasPermission("funnyguilds.admin")) {
        return;
    }

    FunnyGuilds.getInstance().getServer().getScheduler().runTaskAsynchronously(FunnyGuilds.getInstance(), () -> {
        String latest = IOUtils.getContent(VERSION_FILE_URL);

        if (latest != null) {
            String currentNightlyHash = getCurrentNightlyHash(latest);

            if (StringUtils.isNotBlank(currentNightlyHash)) {
                if (FunnyGuilds.getInstance().getPluginConfiguration().updateNightlyInfo) {
                    try {
                        GitHub github = FunnyGuilds.getInstance().getGithubAPI();

                        if (github == null) {
                            return;
                        }

                        GHCommit latestCommit = Iterables.get(
                                github.getOrganization("FunnyGuilds").getRepository("FunnyGuilds").listCommits(), 0);

                        String commitHash = latestCommit.getSHA1().substring(0, 7);

                        if (! commitHash.equals(currentNightlyHash)) {
                            printNewVersionAvailable(sender, latest + "-" + commitHash, true);
                        }
                    }
                    catch (IOException ex) {
                        FunnyGuilds.getInstance().getPluginLogger().debug("Could not retrieve latest nightly version!");
                        FunnyGuilds.getInstance().getPluginLogger().debug(Throwables.getStackTraceAsString(ex));
                    }
                }
            }
            else if (! latest.equalsIgnoreCase(FunnyGuilds.getInstance().getFullVersion())) {
                printNewVersionAvailable(sender, latest, false);
            }
        }
    });
}
 
Example #26
Source File: ManualBuildCause.java    From DotCi with MIT License 4 votes vote down vote up
private List<GithubLogEntry> getChangeLogEntriescommit(final GHCommit commit) throws IOException {
    final List<GithubLogEntry> logEntries = new ArrayList<>();
    logEntries.add(new GithubLogEntry(commit));
    return logEntries;
}
 
Example #27
Source File: UnknownBuildCause.java    From DotCi with MIT License 4 votes vote down vote up
public UnknownBuildCause(final GitBranch branch, final GHCommit commit, final String parentSha) {
    this.branch = branch;
    this.parentSha = parentSha;
    this.sha = commit.getSHA1();
    this.commitInfo = new CommitInfo(commit, branch);
}
 
Example #28
Source File: GitHubBranchCommitCheck.java    From github-integration-plugin with MIT License 4 votes vote down vote up
protected abstract GitHubBranchCause doCheck(GHBranch remoteBranch, GitHubBranchRepository localRepo, GHCommit commit)
throws IOException;
 
Example #29
Source File: GitHubBranchCommitMessageCheck.java    From github-integration-plugin with MIT License 4 votes vote down vote up
@Override
public GitHubBranchCause doCheck(GHBranch remoteBranch, GitHubBranchRepository localRepo, GHCommit commit) throws IOException {
    List<String> messages = Arrays.asList(commit.getCommitShortInfo().getMessage());
    return check(remoteBranch, localRepo, () -> messages);
}
 
Example #30
Source File: GitHubBranchCommitEvent.java    From github-integration-plugin with MIT License 4 votes vote down vote up
GHCommit getLastCommit(GHBranch remoteBranch) throws IOException {
    return remoteBranch.getOwner().getCommit(remoteBranch.getSHA1());
}