org.kohsuke.github.GHIssueComment Java Examples

The following examples show how to use org.kohsuke.github.GHIssueComment. 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: UpdatePullRequests.java    From updatebot with Apache License 2.0 6 votes vote down vote up
/**
 * Lets load the old command context from comments on the PullRequest so that we can re-run a command to rebase things.
 */
protected CompositeCommand loadCommandsFromPullRequest(CommandContext context, GHRepository ghRepository, GHPullRequest pullRequest) throws IOException {
    List<GHIssueComment> comments = pullRequest.getComments();
    String lastCommand = null;
    for (GHIssueComment comment : comments) {
        String command = updateBotCommentCommand(context, comment);
        if (command != null) {
            lastCommand = command;
        }
    }
    if (lastCommand == null) {
        context.warn(LOG, "No UpdateBot comment found on pull request " + pullRequest.getHtmlUrl() + " so cannot rebase!");
        return null;
    }
    return parseUpdateBotCommandComment(context, lastCommand);
}
 
Example #2
Source File: GitHubPRCommentEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
private GitHubPRCause checkComment(GitHubPRDecisionContext prDecisionContext,
                                   GHIssueComment issueComment,
                                   GitHubPRUserRestriction userRestriction,
                                   TaskListener listener) {
    GitHubPRCause cause = null;
    try {
        String body = issueComment.getBody();

        if (isNull(userRestriction) || userRestriction.isWhitelisted(issueComment.getUser())) {
            final Matcher matcher = Pattern.compile(comment).matcher(body);
            if (matcher.matches()) {
                listener.getLogger().println(DISPLAY_NAME + ": matching comment " + body);
                LOG.trace("Event matches comment '{}'", body);
                cause = prDecisionContext.newCause("Comment matches to criteria.", false);
                cause.withCommentBody(body);
                if (matcher.groupCount() > 0) {
                    cause.withCommentBodyMatch(matcher.group(1));
                }
            }
        }
    } catch (IOException ex) {
        LOG.error("Couldn't check comment #{}, skipping it.", issueComment.getId(), ex);
    }
    return cause;
}
 
Example #3
Source File: GitHubPRCommentEventTest.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Test
public void testNullLocalComment() throws IOException {
    when(listener.getLogger()).thenReturn(logger);

    when(issue.getCreatedAt()).thenReturn(new Date());
    when(comment.getBody()).thenReturn("body");

    final ArrayList<GHIssueComment> ghIssueComments = new ArrayList<>();
    ghIssueComments.add(comment);
    when(remotePr.getComments()).thenReturn(ghIssueComments);

    GitHubPRCause cause = new GitHubPRCommentEvent("Comment")
            .check(newGitHubPRDecisionContext()
                    .withPrTrigger(trigger)
                    .withRemotePR(remotePr)
                    .withListener(listener)
                    .build()
            );

    assertNull(cause);
}
 
Example #4
Source File: GitHubPRCommentEventTest.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Test
public void testNullLocalPR() throws IOException {
    commonExpectations(emptySet());
    causeCreationExpectations();

    final String body = "test foo, bar tags please.";
    when(issue.getCreatedAt()).thenReturn(new Date());
    when(comment.getCreatedAt()).thenReturn(new Date());
    when(comment.getBody()).thenReturn(body);

    final ArrayList<GHIssueComment> ghIssueComments = new ArrayList<>();
    ghIssueComments.add(comment);
    when(remotePr.getComments()).thenReturn(ghIssueComments);

    GitHubPRCause cause = new GitHubPRCommentEvent("test ([A-Za-z0-9 ,!]+) tags please.")
            .check(newGitHubPRDecisionContext()
                    .withPrTrigger(trigger)
                    .withRemotePR(remotePr)
                    .withListener(listener)
                    .build()
            ); // localPR is null

    assertThat(cause.getCommentBody(), is(body));
    assertThat(cause.getCommentBodyMatch(), is("foo, bar"));
    assertNotNull(cause);
}
 
Example #5
Source File: UpdatePullRequests.java    From updatebot with Apache License 2.0 5 votes vote down vote up
private String updateBotCommentCommand(CommandContext context, GHIssueComment comment) throws IOException {
    GHUser user = comment.getUser();
    if (user != null) {
        if (Objects.equal(context.getConfiguration().getGithubUsername(), user.getLogin())) {
            String body = comment.getBody();
            if (body != null) {
                body = body.trim();
                if (body.startsWith(PullRequests.COMMAND_COMMENT_PREFIX)) {
                    return body;
                }
            }
        }
    }
    return null;
}
 
Example #6
Source File: Issues.java    From updatebot with Apache License 2.0 5 votes vote down vote up
public static List<DependencyVersionChange> loadPendingChangesFromIssue(CommandContext context, GHIssue issue) throws IOException {
    List<GHIssueComment> comments = issue.getComments();
    String lastCommand = null;
    for (GHIssueComment comment : comments) {
        String command = updateBotIssuePendingChangesComment(context, comment);
        if (command != null) {
            lastCommand = command;
        }
    }
    if (lastCommand == null) {
        LOG.warn("No UpdateBot comment found on issue " + issue.getHtmlUrl());
        return new ArrayList<>();
    }
    return parseUpdateBotIssuePendingChangesComment(lastCommand);
}
 
Example #7
Source File: Issues.java    From updatebot with Apache License 2.0 5 votes vote down vote up
public static String updateBotIssuePendingChangesComment(CommandContext context, GHIssueComment comment) throws IOException {
    GHUser user = comment.getUser();
    if (user != null) {
        if (Objects.equal(context.getConfiguration().getGithubUsername(), user.getLogin())) {
            String body = comment.getBody();
            if (body != null) {
                body = body.trim();
                if (body.startsWith(PENDING_CHANGE_COMMENT_PREFIX)) {
                    return body;
                }
            }
        }
    }
    return null;
}
 
Example #8
Source File: GitHubPRCommentEvent.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) {
    final TaskListener listener = prDecisionContext.getListener();
    final PrintStream llog = listener.getLogger();
    final GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();
    final GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final GitHubPRUserRestriction prUserRestriction = prDecisionContext.getPrUserRestriction();

    GitHubPRCause cause = null;
    try {
        for (GHIssueComment issueComment : remotePR.getComments()) {
            if (isNull(localPR) // test all comments for trigger word even if we never saw PR before
                    || isNull(localPR.getLastCommentCreatedAt()) // PR was created but had no comments
                    // don't check comments that we saw before
                    || localPR.getLastCommentCreatedAt().compareTo(issueComment.getCreatedAt()) < 0) {
                llog.printf("%s: state has changed (new comment found - '%s')%n",
                        DISPLAY_NAME, issueComment.getBody());

                cause = checkComment(prDecisionContext, issueComment, prUserRestriction, listener);
                if (nonNull(cause)) {
                    break;
                }
            }
        }
    } catch (Exception e) {
        LOG.warn("Couldn't obtain comments: {}", e);
        listener.error("Couldn't obtain comments", e);
    }

    if (isNull(cause)) {
        LOG.debug("No matching comments found for {}", remotePR.getNumber());
        llog.println("No matching comments found for " + remotePR.getNumber());
    }

    return cause;
}
 
Example #9
Source File: GitHubPRCommentEventTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Test
public void testNullLocalCommentRemoteMatch() throws IOException {
    commonExpectations(emptySet());
    causeCreationExpectations();

    final String body = "test foo, bar tags please.";
    when(issue.getCreatedAt()).thenReturn(new Date());
    when(comment.getCreatedAt()).thenReturn(new Date());
    when(comment.getBody()).thenReturn(body);

    final ArrayList<GHIssueComment> ghIssueComments = new ArrayList<>();
    ghIssueComments.add(comment);
    when(remotePr.getComments()).thenReturn(ghIssueComments);

    GitHubPRCause cause = new GitHubPRCommentEvent("test ([A-Za-z0-9 ,!]+) tags please.")
            .check(newGitHubPRDecisionContext()
                    .withPrTrigger(trigger)
                    .withLocalPR(localPR)
                    .withRemotePR(remotePr)
                    .withListener(listener)
                    .build()
            );

    assertThat(cause.getCommentBody(), is(body));
    assertThat(cause.getCommentBodyMatch(), is("foo, bar"));
    assertNotNull(cause);
}
 
Example #10
Source File: GitHubPRCommentEventTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Test
public void firstCommentMatchSecondDont() throws IOException {
    commonExpectations(emptySet());
    causeCreationExpectations();

    when(issue.getCreatedAt()).thenReturn(new Date());

    final String body = "test foo, bar tags please.";
    when(comment.getBody()).thenReturn(body);
    when(comment.getCreatedAt()).thenReturn(new Date());

    final String body2 = "no matching in second comment";
    when(comment2.getBody()).thenReturn(body2);
    when(comment2.getCreatedAt()).thenReturn(new Date());


    final ArrayList<GHIssueComment> ghIssueComments = new ArrayList<>();
    ghIssueComments.add(comment);
    ghIssueComments.add(comment2);
    when(remotePr.getComments()).thenReturn(ghIssueComments);

    GitHubPRCause cause = new GitHubPRCommentEvent("test ([A-Za-z0-9 ,!]+) tags please.")
            .check(newGitHubPRDecisionContext()
                    .withPrTrigger(trigger)
                    .withLocalPR(localPR)
                    .withRemotePR(remotePr)
                    .withListener(listener)
                    .build()
            );
    assertThat(cause, notNullValue());
    assertThat(cause.getCommentBody(), is(body));
    assertThat(cause.getCommentBodyMatch(), is("foo, bar"));
}
 
Example #11
Source File: GithubRepository.java    From cloud-search-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Build the ApiOperation to index a pull request.
 *
 * @param pullRequest  Pull request to index
 * @param previousItem Previous item state in the index
 * @return ApiOperation (RepositoryDoc if indexing,  PushItem if not modified)
 * @throws IOException if unable to create operation
 */
private ApiOperation indexItem(GHPullRequest pullRequest, Item previousItem)
    throws IOException {
  String metadataHash = pullRequest.getUpdatedAt().toString();

  // If previously indexed and unchanged, just requeue as unmodified
  if (canSkipIndexing(previousItem, metadataHash)) {
    return notModified(previousItem.getName());
  }

  String resourceName = pullRequest.getHtmlUrl().getPath();
  FieldOrValue<String> title = FieldOrValue.withValue(pullRequest.getTitle());
  FieldOrValue<String> url = FieldOrValue.withValue(
      pullRequest.getHtmlUrl().toExternalForm());
  FieldOrValue<DateTime> createTime = FieldOrValue.withValue(
      new DateTime(pullRequest.getCreatedAt().getTime()));
  FieldOrValue<DateTime> updateTime = FieldOrValue.withValue(
      new DateTime(pullRequest.getUpdatedAt().getTime()));
  String containerName = pullRequest.getRepository().getHtmlUrl().getPath();

  // Structured data based on the schema
  Multimap<String, Object> structuredData = ArrayListMultimap.create();
  structuredData.put("organization", pullRequest.getRepository().getOwnerName());
  structuredData.put("repository", pullRequest.getRepository().getName());
  structuredData.put("status", pullRequest.getState().name().toLowerCase());
  structuredData.put("openedBy", pullRequest.getUser() != null ?
      pullRequest.getUser().getLogin() : null);
  structuredData.put("assignee", pullRequest.getAssignee() != null ?
      pullRequest.getAssignee().getLogin() : null);
  for (GHLabel label : pullRequest.getLabels()) {
    structuredData.put("labels", label.getName());
  }

  // Index comments as sub objects in the metadata. This makes the comments
  // searchable but still tied to the issue itself.
  for (GHIssueComment comment : pullRequest.getComments()) {
    Multimap<String, Object> commentData = ArrayListMultimap.create();
    commentData.put("comment", comment.getBody());
    commentData.put("user", comment.getUser() != null ?
        comment.getUser().getLogin() : null);
    structuredData.put("comments", commentData);
  }
  structuredData.put("createdAt", pullRequest.getCreatedAt());
  structuredData.put("updatedAt", pullRequest.getUpdatedAt());

  Item item = IndexingItemBuilder.fromConfiguration(resourceName)
      .setTitle(title)
      .setContainerName(containerName)
      .setSourceRepositoryUrl(url)
      .setItemType(IndexingItemBuilder.ItemType.CONTAINER_ITEM)
      .setObjectType("pullRequest")
      .setValues(structuredData)
      .setVersion(Longs.toByteArray(pullRequest.getUpdatedAt().getTime()))
      .setCreateTime(createTime)
      .setUpdateTime(updateTime)
      .setHash(metadataHash)
      .build();

  // TODO - Index the actual patch/diff?
  // TODO - Render markdown to HTML
  AbstractInputStreamContent content = new ByteArrayContent(
      "text/plain",
      pullRequest.getBody().getBytes(StandardCharsets.UTF_8));
  return new RepositoryDoc.Builder()
      .setItem(item)
      .setContent(content, IndexingService.ContentFormat.TEXT)
      .setRequestMode(IndexingService.RequestMode.SYNCHRONOUS)
      .build();
}
 
Example #12
Source File: GithubRepository.java    From cloud-search-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Build the ApiOperation to index an issue.
 *
 * @param issue        Pull request to index
 * @param previousItem Previous item state in the index
 * @return ApiOperation (RepositoryDoc if indexing,  PushItem if not modified)
 * @throws IOException if unable to create operation
 */
private ApiOperation indexItem(GHIssue issue, Item previousItem)
    throws IOException {
  String metadataHash = issue.getUpdatedAt().toString();

  // If previously indexed and unchanged, just requeue as unmodified
  if (canSkipIndexing(previousItem, metadataHash)) {
    return notModified(previousItem.getName());
  }

  String resourceName = issue.getHtmlUrl().getPath();
  FieldOrValue<String> title = FieldOrValue.withValue(issue.getTitle());
  FieldOrValue<String> url = FieldOrValue.withValue(
      issue.getHtmlUrl().toExternalForm());
  FieldOrValue<DateTime> createTime = FieldOrValue.withValue(
      new DateTime(issue.getCreatedAt().getTime()));
  FieldOrValue<DateTime> updateTime = FieldOrValue.withValue(
      new DateTime(issue.getUpdatedAt().getTime()));
  String containerName = issue.getRepository().getHtmlUrl().getPath();

  // Structured data based on the schema
  Multimap<String, Object> structuredData = ArrayListMultimap.create();
  structuredData.put("organization", issue.getRepository().getOwnerName());
  structuredData.put("repository", issue.getRepository().getName());
  structuredData.put("status", issue.getState().name().toLowerCase());
  structuredData.put("reportedBy", issue.getUser() != null ?
      issue.getUser().getLogin() : null);
  structuredData.put("assignee", issue.getAssignee() != null ?
      issue.getAssignee().getLogin() : null);
  for (GHLabel label : issue.getLabels()) {
    structuredData.put("labels", label.getName());
  }

  // Index comments as sub objects in the metadata. This makes the comments
  // searchable but still tied to the issue itself.
  for (GHIssueComment comment : issue.getComments()) {
    Multimap<String, Object> commentData = ArrayListMultimap.create();
    commentData.put("comment", comment.getBody());
    commentData.put("user", comment.getUser() != null ?
        comment.getUser().getLogin() : null);
    structuredData.put("comments", commentData);
  }
  structuredData.put("createdAt", issue.getCreatedAt());
  structuredData.put("updatedAt", issue.getUpdatedAt());

  Item item = IndexingItemBuilder.fromConfiguration(resourceName)
      .setTitle(title)
      .setContainerName(containerName)
      .setSourceRepositoryUrl(url)
      .setItemType(IndexingItemBuilder.ItemType.CONTAINER_ITEM)
      .setObjectType("issue")
      .setValues(structuredData)
      .setVersion(Longs.toByteArray(issue.getUpdatedAt().getTime()))
      .setCreateTime(createTime)
      .setUpdateTime(updateTime)
      .setHash(metadataHash)
      .build();

  // TODO - Render markdown to HTML
  AbstractInputStreamContent content = new ByteArrayContent(
      "text/plain",
      issue.getBody().getBytes(StandardCharsets.UTF_8));
  return new RepositoryDoc.Builder()
      .setItem(item)
      .setContent(content, IndexingService.ContentFormat.TEXT)
      .setRequestMode(IndexingService.RequestMode.SYNCHRONOUS)
      .build();
}