org.kohsuke.github.GHLabel Java Examples

The following examples show how to use org.kohsuke.github.GHLabel. 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: GitHubPRLabelAddedEventTest.java    From github-integration-plugin with MIT License 6 votes vote down vote up
/**
 * Case when there is three checked labels and no one of them was removed.
 */
@Test
public void noLabelsWasRemoved() throws IOException {
    Set<String> localLabels = new HashSet<>(asList(MERGE, REVIEWED, LOCALLY_TESTED));
    List<GHLabel> remoteLabels = asList(testLabel, reviewedLabel, mergeLabel);

    commonExpectations(localLabels);

    when(issue.getLabels()).thenReturn(remoteLabels);
    when(testLabel.getName()).thenReturn(LOCALLY_TESTED);
    when(reviewedLabel.getName()).thenReturn(REVIEWED);
    when(mergeLabel.getName()).thenReturn(MERGE);

    GitHubPRCause cause = new GitHubPRLabelAddedEvent(labels)
            .check(newGitHubPRDecisionContext()
                    .withPrTrigger(trigger)
                    .withRemotePR(remotePr)
                    .withListener(listener)
                    .withLocalPR(localPR)
                    .build()
            );
    ;
    assertNull(cause);
}
 
Example #2
Source File: GitHubPRLabelAddedEventTest.java    From github-integration-plugin with MIT License 6 votes vote down vote up
/**
 * Case when there is three checked labels and all of them was already added.
 */
@Test
public void allLabelsAlreadyExist() throws IOException {
    Set<String> localLabels = new HashSet<>(asList(LOCALLY_TESTED, MERGE, REVIEWED));
    List<GHLabel> remoteLabels = asList(testLabel, reviewedLabel, mergeLabel);

    commonExpectations(localLabels);

    when(issue.getLabels()).thenReturn(remoteLabels);
    when(testLabel.getName()).thenReturn(LOCALLY_TESTED);
    when(reviewedLabel.getName()).thenReturn(REVIEWED);
    when(mergeLabel.getName()).thenReturn(MERGE);

    GitHubPRLabelAddedEvent instance = new GitHubPRLabelAddedEvent(labels);
    GitHubPRCause cause = instance.check(newGitHubPRDecisionContext()
            .withPrTrigger(trigger)
            .withRemotePR(remotePr)
            .withListener(listener)
            .withLocalPR(localPR)
            .build()
    );
    ;
    assertNull(cause);
}
 
Example #3
Source File: GitHubPRLabelAddPublisher.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
                    @Nonnull TaskListener listener) throws InterruptedException, IOException {
    if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) {
        return;
    }
    try {
        HashSet<String> remoteLabels = new HashSet<>();
        final GHIssue ghIssue = getGhIssue(run);
        //remote labels List -> Set
        ghIssue.getLabels().stream()
                .map(GHLabel::getName)
                .collect(Collectors.toList())
                .forEach(remoteLabels::add);

        remoteLabels.addAll(getLabelProperty().getLabelsSet());
        ghIssue.setLabels(remoteLabels.toArray(new String[remoteLabels.size()]));
    } catch (IOException ex) {
        final int number = getPRNumberFromPRCause(run);
        listener.getLogger().println("Couldn't add label for PR #" + number + ex.getMessage());
        LOGGER.error("Couldn't add label for PR #{}", number, ex);
        handlePublisherError(run);
    }
}
 
Example #4
Source File: GitHubPRLabelRemovePublisher.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath workspace, @Nonnull Launcher launcher,
                    @Nonnull TaskListener listener) throws InterruptedException, IOException {
    if (getStatusVerifier() != null && !getStatusVerifier().isRunAllowed(run)) {
        return;
    }

    final int number = getPRNumberFromPRCause(run);
    try {
        HashSet<String> remoteLabels = getGhIssue(run).getLabels().stream()
                .map(GHLabel::getName)
                .collect(Collectors.toCollection(HashSet::new));

        //remote labels List -> Set
        remoteLabels.removeAll(getLabelProperty().getLabelsSet());
        // TODO print only really removing
        listener.getLogger().println("Removing labels: " + getLabelProperty().getLabelsSet());
        getGhIssue(run).setLabels(remoteLabels.toArray(new String[remoteLabels.size()]));
    } catch (IOException ex) {
        listener.getLogger().println("Couldn't remove label for PR #" + number + ex);
        LOGGER.error("Couldn't remove label for PR #{}", number, ex);
        handlePublisherError(run);
    }
}
 
Example #5
Source File: GitHubPRLabelAddedEventTest.java    From github-integration-plugin with MIT License 6 votes vote down vote up
/**
 * Case when there is three checked labels and there is one that was added and one that already exists.
 */
@Test
public void secondOfThreeLabelsWasAdded() throws IOException {
    Set<String> localLabels = new HashSet<>(Collections.singleton(LOCALLY_TESTED));

    List<GHLabel> remoteLabels = asList(testLabel, reviewedLabel);

    commonExpectations(localLabels);

    when(issue.getLabels()).thenReturn(remoteLabels);
    when(testLabel.getName()).thenReturn(LOCALLY_TESTED);
    when(reviewedLabel.getName()).thenReturn(REVIEWED);

    GitHubPRCause cause = new GitHubPRLabelAddedEvent(labels)
            .check(newGitHubPRDecisionContext()
                    .withPrTrigger(trigger)
                    .withRemotePR(remotePr)
                    .withListener(listener)
                    .withLocalPR(localPR)
                    .build()
            );
    assertNull(cause);
}
 
Example #6
Source File: GitHubPRLabelExistsEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();

    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        return null; // already closed, skip check?
    }

    GitHubPRCause cause = null;

    Collection<GHLabel> remoteLabels = remotePR.getRepository().getIssue(remotePR.getNumber()).getLabels();
    Set<String> existingLabels = new HashSet<>();

    for (GHLabel ghLabel : remoteLabels) {
        existingLabels.add(ghLabel.getName());
    }

    if (existingLabels.containsAll(label.getLabelsSet())) {
        final PrintStream logger = listener.getLogger();
        logger.println(DISPLAY_NAME + ": " + label.getLabelsSet() + " found");
        cause = prDecisionContext.newCause(label.getLabelsSet() + " labels exist", isSkip());
    }

    return cause;
}
 
Example #7
Source File: GitHubPRLabelPatternExistsEvent.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();
    final PrintStream logger = listener.getLogger();

    for (GHLabel ghLabel : remotePR.getRepository().getIssue(remotePR.getNumber()).getLabels()) {
        for (String labelPatternStr : label.getLabelsSet()) {
            Pattern labelPattern = Pattern.compile(labelPatternStr);
            if (labelPattern.matcher(ghLabel.getName()).matches()) {
                logger.println(DISPLAY_NAME + ": Pull request has label: " + labelPatternStr);
                LOGGER.info("Pull request has '{}' label.", labelPatternStr);
                return prDecisionContext.newCause("PR has label: " + labelPatternStr, isSkip());
            }
        }
    }

    return null;
}
 
Example #8
Source File: GitHubPRNonMergeableEventTest.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Before
public void before() throws IOException {
    when(remotePr.getUser()).thenReturn(ghUser);

    GHRepository headRepo = mock(GHRepository.class);
    when(headRepo.getOwnerName()).thenReturn("owner");

    when(remotePr.getHead()).thenReturn(ghCommitPointer);
    when(remotePr.getBase()).thenReturn(ghCommitPointer);

    when(ghCommitPointer.getSha()).thenReturn("1r134rsha324");
    when(ghCommitPointer.getRef()).thenReturn("some/branch");
    when(ghCommitPointer.getRepository()).thenReturn(headRepo);

    when(remotePr.getRepository()).thenReturn(ghRepository);
    when(ghRepository.getIssue(0)).thenReturn(ghIssue);
    when(ghIssue.getLabels()).thenReturn(Collections.<GHLabel>emptySet());
    when(remotePr.getState()).thenReturn(GHIssueState.OPEN);
}
 
Example #9
Source File: GitHubPRLabelRemovedEventTest.java    From github-integration-plugin with MIT License 6 votes vote down vote up
/**
 * Case when there is three checked labels and there is one that wasn't removed yet.
 */
@Test
public void twoOfThreeLabelsWasRemoved() throws IOException {
    Set<String> localLabels = new HashSet<>();
    localLabels.add(TESTS_FAILURE);

    List<GHLabel> remoteLabels = new ArrayList<>();
    remoteLabels.add(label);

    commonExpectations(localLabels);
    when(issue.getLabels()).thenReturn(remoteLabels);
    when(label.getName()).thenReturn(TESTS_FAILURE);

    GitHubPRLabelRemovedEvent instance = new GitHubPRLabelRemovedEvent(labels);
    GitHubPRCause cause = instance.check(newGitHubPRDecisionContext()
            .withPrTrigger(trigger)
            .withLocalPR(localPR)
            .withRemotePR(remotePr)
            .withListener(listener)
            .build()
    );
    Assert.assertNull(cause);
}
 
Example #10
Source File: GitHubPRLabelNotExistsEvent.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();

    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        return null; // already closed, skip check?
    }

    GitHubPRCause cause = null;

    Collection<GHLabel> remoteLabels = remotePR.getRepository().getIssue(remotePR.getNumber()).getLabels();
    Set<String> existingLabels = new HashSet<>();

    for (GHLabel ghLabel : remoteLabels) {
        existingLabels.add(ghLabel.getName());
    }

    existingLabels.retainAll(label.getLabelsSet());

    if (existingLabels.isEmpty()) {
        final PrintStream logger = listener.getLogger();
        LOG.debug("{}:{} not found", DISPLAY_NAME, label.getLabelsSet());
        logger.println(DISPLAY_NAME + ": " + label.getLabelsSet() + " not found");
        cause = prDecisionContext.newCause(label.getLabelsSet() + " labels not exist", isSkip());
    }

    return cause;
}
 
Example #11
Source File: NotesBuilder.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns issue label for release notes.
 *
 * @param issue issue.
 * @return issue label for release notes
 * @throws IOException if an I/o error occurs.
 */
private static String getIssueLabelFrom(GHIssue issue) throws IOException {
    final Collection<GHLabel> issueLabels = issue.getLabels();
    final Optional<GHLabel> label = issueLabels.stream()
        .filter(input -> Arrays.binarySearch(Constants.ISSUE_LABELS, input.getName()) >= 0)
        .findFirst();
    return label.map(GHLabel::getName).orElse("");
}
 
Example #12
Source File: GitHubPRLabelAddedEventTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
/**
 * Case when there is three checked labels and all of them was already added.
 */
@Test
@Ignore
public void thirdOfThreeLabelsWasAdded() throws IOException {
    Set<String> localLabels = new HashSet<>(asList(LOCALLY_TESTED, MERGE));

    List<GHLabel> remoteLabels = asList(testLabel, reviewedLabel, mergeLabel);

    commonExpectations(localLabels);

    when(issue.getLabels()).thenReturn(remoteLabels);
    when(testLabel.getName()).thenReturn(LOCALLY_TESTED);
    when(reviewedLabel.getName()).thenReturn(REVIEWED);
    when(mergeLabel.getName()).thenReturn(MERGE);

    causeCreationExpectations();

    GitHubPRCause cause = new GitHubPRLabelAddedEvent(labels)
            .check(newGitHubPRDecisionContext()
                    .withPrTrigger(trigger)
                    .withRemotePR(remotePr)
                    .withListener(listener)
                    .withLocalPR(localPR)
                    .build()
            );
    assertThat(cause.getLabels(), equalTo(localLabels));
}
 
Example #13
Source File: GitHubPRLabelRemovedEventTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
/**
 * Case when there is three checked labels and no one of them was removed.
 */
@Test
public void noLabelsWasRemoved() throws IOException {
    Set<String> localLabels = new HashSet<>();
    localLabels.add(NOT_READY_FOR_MERGE);
    localLabels.add(NOT_REVIEWED);
    localLabels.add(TESTS_FAILURE);

    List<GHLabel> remoteLabels = new ArrayList<>();
    for (int i = 0; i < localLabels.size(); i++) {
        remoteLabels.add(label);
    }

    commonExpectations(localLabels);
    when(issue.getLabels()).thenReturn(remoteLabels);
    when(label.getName()).thenReturn(TESTS_FAILURE);
    when(label.getName()).thenReturn(NOT_READY_FOR_MERGE);
    when(label.getName()).thenReturn(NOT_REVIEWED);

    GitHubPRLabelRemovedEvent instance = new GitHubPRLabelRemovedEvent(labels);
    GitHubPRCause cause = instance.check(newGitHubPRDecisionContext()
            .withPrTrigger(trigger)
            .withLocalPR(localPR)
            .withRemotePR(remotePr)
            .withListener(listener)
            .build()
    );
    Assert.assertNull(cause);
}
 
Example #14
Source File: GitHubPRLabelAddedEvent.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public GitHubPRCause check(@Nonnull GitHubPRDecisionContext prDecisionContext) throws IOException {
    TaskListener listener = prDecisionContext.getListener();
    GitHubPRPullRequest localPR = prDecisionContext.getLocalPR();
    GHPullRequest remotePR = prDecisionContext.getRemotePR();

    if (remotePR.getState().equals(GHIssueState.CLOSED)) {
        return null; // already closed, skip check?
    }

    if (isNull(label)) {
        LOG.error("Label is null. Bad configured event: {}", getDescriptor().getDisplayName());
        throw new IllegalStateException("Label is null. Bad configured event: " + getDescriptor().getDisplayName());
    }

    //localPR exists before, checking for changes
    if (localPR != null && localPR.getLabels().containsAll(label.getLabelsSet())) {
        return null; // label existed before exiting
    }

    GitHubPRCause cause = null;

    Collection<GHLabel> labels = remotePR.getRepository().getIssue(remotePR.getNumber()).getLabels();
    Set<String> existingLabels = new HashSet<String>();

    for (GHLabel curLabel : labels) {
        existingLabels.add(curLabel.getName());
    }

    if (existingLabels.containsAll(label.getLabelsSet())) {
        final PrintStream logger = listener.getLogger();
        logger.println(DISPLAY_NAME + ": state has changed (" + label.getLabelsSet() + " labels were added");
        cause = prDecisionContext.newCause(label.getLabelsSet() + " labels were added", false);
    }

    return cause;
}
 
Example #15
Source File: GitHubHelpers.java    From updatebot with Apache License 2.0 5 votes vote down vote up
public static boolean hasLabel(Collection<GHLabel> labels, String label) {
    if (labels != null) {
        for (GHLabel ghLabel : labels) {
            if (Objects.equal(label, ghLabel.getName())) {
                return true;
            }
        }
    }
    return false;
}
 
Example #16
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 #17
Source File: GitHubPRPullRequest.java    From github-integration-plugin with MIT License 4 votes vote down vote up
private void updateLabels(Collection<GHLabel> labels) {
    this.labels = new HashSet<>();
    for (GHLabel label : labels) {
        this.labels.add(label.getName());
    }
}
 
Example #18
Source File: Issues.java    From updatebot with Apache License 2.0 4 votes vote down vote up
/**
 * Lets return the labels on an issue with retries
 */
public static Collection<GHLabel> getLabels(GHIssue issue) throws IOException {
    return retryGithub(() -> issue.getLabels());
}
 
Example #19
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();
}