org.kohsuke.github.GHRepository Java Examples

The following examples show how to use org.kohsuke.github.GHRepository. 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: GithubRepository.java    From cloud-search-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch IDs to  push in to the queue for all items in the repository.
 * Currently captures issues & content in the master branch.
 *
 * @param name Name of repository to index
 * @return Items to push into the queue for later indexing
 * @throws IOException if error reading issues
 */
private Collection<ApiOperation> collectRepositoryItems(String name)
    throws IOException {
  List<ApiOperation> operations = new ArrayList<>();
  GHRepository repo = github.getRepository(name);

  // Add the repository as an item to be indexed
  String metadataHash = repo.getUpdatedAt().toString();
  String resourceName = repo.getHtmlUrl().getPath();
  PushItem repositoryPushItem = new PushItem()
      .setMetadataHash(metadataHash);
  PushItems items = new PushItems.Builder()
      .addPushItem(resourceName, repositoryPushItem)
      .build();

  operations.add(items);
  // Add issues/pull requests & files
  operations.add(collectIssues(repo));
  operations.add(collectContent(repo));
  return operations;
}
 
Example #2
Source File: GithubRepository.java    From cloud-search-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch all issues for the repository. Includes pull requests.
 *
 * @param repo Repository to get issues for
 * @return Items to push into the queue for later indexing
 * @throws IOException if error reading issues
 */
private PushItems collectIssues(GHRepository repo) throws IOException {
  PushItems.Builder builder = new PushItems.Builder();

  List<GHIssue> issues = repo.listIssues(GHIssueState.ALL)
      .withPageSize(1000)
      .asList();
  for (GHIssue issue : issues) {
    String resourceName = issue.getHtmlUrl().getPath();
    log.info(() -> String.format("Adding issue %s", resourceName));
    PushItem item = new PushItem();
    item.setMetadataHash(Long.toHexString(issue.getUpdatedAt().getTime()));
    builder.addPushItem(resourceName, item);
  }
  return builder.build();
}
 
Example #3
Source File: ForkableRepoValidatorTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testContentHasNoChangesInDefaultBranch() throws InterruptedException, IOException {
    DockerfileGitHubUtil dockerfileGitHubUtil = mock(DockerfileGitHubUtil.class);
    GHRepository repo = mock(GHRepository.class);
    ForkableRepoValidator validator = new ForkableRepoValidator(dockerfileGitHubUtil);
    GHContent content = mock(GHContent.class);
    String searchContentPath = "/Dockerfile";
    when(content.getPath()).thenReturn(searchContentPath);
    String imageName = "someImage";
    GitForkBranch gitForkBranch = new GitForkBranch(imageName, "someTag", null);
    when(dockerfileGitHubUtil.tryRetrievingContent(eq(repo), any(), any())).thenReturn(content);
    InputStream inputStream = new ByteArrayInputStream("nochanges".getBytes());
    when(content.read()).thenReturn(inputStream);

    assertEquals(validator.contentHasChangesInDefaultBranch(repo, content, gitForkBranch),
            shouldNotForkResult(String.format(COULD_NOT_FIND_IMAGE_TO_UPDATE_TEMPLATE, imageName, searchContentPath)));
}
 
Example #4
Source File: GitHubHelpers.java    From updatebot with Apache License 2.0 6 votes vote down vote up
public static Boolean waitForPullRequestToHaveMergable(GHPullRequest pullRequest, long sleepMS, long maximumTimeMS) throws IOException {
    long end = System.currentTimeMillis() + maximumTimeMS;
    while (true) {
        Boolean mergeable = pullRequest.getMergeable();
        if (mergeable == null) {
            GHRepository repository = pullRequest.getRepository();
            int number = pullRequest.getNumber();
            pullRequest = repository.getPullRequest(number);
            mergeable = pullRequest.getMergeable();
        }
        if (mergeable != null) {
            return mergeable;
        }
        if (System.currentTimeMillis() > end) {
            return null;
        }
        try {
            Thread.sleep(sleepMS);
        } catch (InterruptedException e) {
            // ignore
        }
    }
}
 
Example #5
Source File: LinkConfigurationWidget.java    From BowlerStudio with GNU General Public License v3.0 6 votes vote down vote up
private void test(String type) throws IOException {
	try {
		Vitamins.saveDatabase(type);

	} catch (org.eclipse.jgit.api.errors.TransportException e) {
		GitHub github = PasswordManager.getGithub();

		GHRepository repo = github.getUser("madhephaestus").getRepository("Hardware-Dimensions");
		GHRepository forked = repo.fork();
		System.out.println("Vitamins forked to " + forked.getGitTransportUrl());
		Vitamins.setGitRepoDatabase(
				"https://github.com/" + github.getMyself().getLogin() + "/Hardware-Dimensions.git");
		System.out.println("Loading new files");
		//

	} catch (Exception ex) {
		// ex.printStackTrace(MainController.getOut());
	}
}
 
Example #6
Source File: GitHubPluginRepoProvider.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@CheckForNull
@Override
public synchronized GHRepository getGHRepository(GitHubTrigger trigger) {
    if (isTrue(cacheConnection) && nonNull(remoteRepository)) {
        return remoteRepository;
    }

    final GitHubRepositoryName name = trigger.getRepoFullName();
    try {
        remoteRepository = getGitHub(trigger).getRepository(name.getUserName() + "/" + name.getRepositoryName());
    } catch (IOException ex) {
        LOG.error("Shouldn't fail because getGitHub() expected to provide working repo.", ex);
    }

    return remoteRepository;
}
 
Example #7
Source File: ForkableRepoValidator.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Check to see if the default branch of the parentRepo has the path we found in searchResultContent and
 * whether that content has a qualifying base image update
 * @param parentRepo parentRepo which we'd fork off of
 * @param searchResultContent search result with path to check in parent repo's default branch (where we'd PR)
 * @param gitForkBranch information about the imageName we'd like to update with the new tag
 */
protected ShouldForkResult contentHasChangesInDefaultBranch(GHRepository parentRepo,
                                                            GHContent searchResultContent,
                                                            GitForkBranch gitForkBranch) {
    try {
        String searchContentPath = searchResultContent.getPath();
        GHContent content =
                dockerfileGitHubUtil.tryRetrievingContent(parentRepo,
                        searchContentPath, parentRepo.getDefaultBranch());
        if (content == null) {
            return shouldNotForkResult(
                    String.format(CONTENT_PATH_NOT_IN_DEFAULT_BRANCH_TEMPLATE, searchContentPath));
        } else {
            if (hasNoChanges(content, gitForkBranch)) {
                return shouldNotForkResult(
                        String.format(COULD_NOT_FIND_IMAGE_TO_UPDATE_TEMPLATE,
                                gitForkBranch.getImageName(), searchContentPath));
            }
        }
    } catch (InterruptedException e) {
        log.warn("Couldn't get parent content to check for some reason for {}. Trying to proceed... exception: {}",
                parentRepo.getFullName(), e.getMessage());
    }
    return shouldForkResult();
}
 
Example #8
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
private static void ensureDetailedGHPullRequest(GHPullRequest pr, TaskListener listener, GitHub github, GHRepository ghRepository) throws IOException, InterruptedException {
    final long sleep = 1000;
    int retryCountdown = 4;

    Connector.checkApiRateLimit(listener, github);
    while (pr.getMergeable() == null && retryCountdown > 1) {
        listener.getLogger().format(
            "Waiting for GitHub to create a merge commit for pull request %d.  Retrying %d more times...%n",
            pr.getNumber(),
            retryCountdown);
        retryCountdown -= 1;
        Thread.sleep(sleep);
        Connector.checkApiRateLimit(listener, github);
    }


}
 
Example #9
Source File: LocalRepoUpdaterTest.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    localRepo = new GitHubPRRepository(remoteRepo);

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

    when(commit.getRepository()).thenReturn(headRepo);


    when(remotePR.getUser()).thenReturn(new GHUser());
    when(remotePR.getHead()).thenReturn(commit);
    when(remotePR.getBase()).thenReturn(commit);
    when(remotePR.getRepository()).thenReturn(remoteRepo);
    when(remoteRepo.getIssue(Matchers.any(Integer.class))).thenReturn(new GHIssue());

    when(commit.getSha()).thenReturn(SHA_REMOTE);
}
 
Example #10
Source File: ChildTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider = "inputMap")
public void checkPullRequestMade(Map<String, Object> inputMap) throws Exception {
    Child child = new Child();
    Namespace ns = new Namespace(inputMap);
    DockerfileGitHubUtil dockerfileGitHubUtil = mock(DockerfileGitHubUtil.class);
    Mockito.when(dockerfileGitHubUtil.getRepo(Mockito.any())).thenReturn(new GHRepository());
    Mockito.when(dockerfileGitHubUtil.getOrCreateFork(Mockito.any())).thenReturn(new GHRepository());
    doNothing().when(dockerfileGitHubUtil).modifyAllOnGithub(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
    GitHubJsonStore gitHubJsonStore = mock(GitHubJsonStore.class);
    when(dockerfileGitHubUtil.getGitHubJsonStore(anyString())).thenReturn(gitHubJsonStore);
    doNothing().when(dockerfileGitHubUtil).createPullReq(Mockito.any(), anyString(), Mockito.any(), anyString());

    child.execute(ns, dockerfileGitHubUtil);

    Mockito.verify(dockerfileGitHubUtil, atLeastOnce())
            .createPullReq(Mockito.any(), anyString(), Mockito.any(), anyString());
}
 
Example #11
Source File: ForkableRepoValidatorTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider = "shouldForkData")
public void testShouldFork(ShouldForkResult isForkResult,
                           ShouldForkResult isArchivedResult,
                           ShouldForkResult userIsNotOwnerResult,
                           ShouldForkResult contentHasChangesResult,
                           ShouldForkResult expectedResult) {
    ForkableRepoValidator validator = mock(ForkableRepoValidator.class);

    when(validator.parentIsFork(any())).thenReturn(isForkResult);
    when(validator.parentIsArchived(any())).thenReturn(isArchivedResult);
    when(validator.thisUserIsNotOwner(any())).thenReturn(userIsNotOwnerResult);
    when(validator.contentHasChangesInDefaultBranch(any(), any(), any())).thenReturn(contentHasChangesResult);
    when(validator.shouldFork(any(), any(), any())).thenCallRealMethod();

    assertEquals(validator.shouldFork(mock(GHRepository.class), mock(GHContent.class), mock(GitForkBranch.class)),
            expectedResult);
}
 
Example #12
Source File: GithubSCMSourceTagsTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Test
public void testThrownErrorSingleTagOtherException() throws IOException {
    // Scenario: A single tag but getting back another Error when calling getRef
    SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class);
    Error expectedError = new Error("Bad Tag Request", new RuntimeException());
    Mockito.when(mockSCMHeadObserver.getIncludes()).thenReturn(Collections
            .singleton(new GitHubTagSCMHead("existent-tag", System.currentTimeMillis())));
    GHRepository repoSpy = Mockito.spy(repo);
    GitHubSCMSourceContext context = new GitHubSCMSourceContext(null, mockSCMHeadObserver);
    context.wantTags(true);
    GitHubSCMSourceRequest request = context.newRequest(new GitHubSCMSource("cloudbeers", "yolo", null, false), null);
    Mockito.doThrow(expectedError).when(repoSpy).getRef("tags/existent-tag");

    //Expected: When getting the tag, an error is thrown so we have to catch it
    try{
        Iterator<GHRef> tags = new GitHubSCMSource.LazyTags(request, repoSpy).iterator();
        fail("This should throw an exception");
    }
    catch(Error e){
        //Error is expected here so this is "success"
        assertEquals("Bad Tag Request", e.getMessage());
    }

}
 
Example #13
Source File: GitHubPRHandler.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private static Stream<GHPullRequest> fetchRemotePRs(GitHubPRRepository localRepo, GHRepository remoteRepo) throws IOException {
    // fetch open prs
    Map<Integer, GHPullRequest> remotePulls = execute(() -> remoteRepo.getPullRequests(GHIssueState.OPEN)).stream()
            .collect(Collectors.toMap(GHPullRequest::getNumber, Function.identity()));

    // collect closed pull requests we knew of previously
    Stream<GHPullRequest> closed = new HashSet<>(localRepo.getPulls().keySet()).stream()
            .filter(pr -> !remotePulls.containsKey(pr))
            .map(iof(remoteRepo::getPullRequest));

    return Stream.concat(remotePulls.values().stream(), closed);
}
 
Example #14
Source File: ForkableRepoValidatorTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testParentIsArchivedDoNotForkIt() {
    DockerfileGitHubUtil dockerfileGitHubUtil = mock(DockerfileGitHubUtil.class);
    GHRepository repo = mock(GHRepository.class);
    ForkableRepoValidator validator = new ForkableRepoValidator(dockerfileGitHubUtil);

    when(repo.isArchived()).thenReturn(true);
    ShouldForkResult shouldForkResult = validator.parentIsArchived(repo);
    assertFalse(shouldForkResult.isForkable());
    assertEquals(shouldForkResult.getReason(), REPO_IS_ARCHIVED);
}
 
Example #15
Source File: ForkJoinReleaseTest.java    From updatebot with Apache License 2.0 5 votes vote down vote up
public void assertOpenIssueAndPullRequestCount(String repoName, int expectedIssueCount, int exepectedPullRequestCount, boolean verbose) throws IOException {
    LocalRepository repository = assertLocalRepository(repoName);

    GHRepository gitHubRepository = GitHubHelpers.getGitHubRepository(repository);
    assertThat(gitHubRepository).describedAs("Not a GitHub repository " + repository).isNotNull();

    String label = configuration.getGithubPullRequestLabel();

    List<GHIssue> issues;
    List<GHPullRequest> prs;

    boolean doAssert = true;
    if (doAssert) {
        issues = GithubAssertions.assertOpenIssueCount(gitHubRepository, label, expectedIssueCount);
        prs = GithubAssertions.assertOpenPullRequestCount(gitHubRepository, label, exepectedPullRequestCount);
    } else {
        issues = Issues.getOpenIssues(gitHubRepository, configuration);
        prs = PullRequests.getOpenPullRequests(gitHubRepository, configuration);
    }

    if (verbose) {
        LOG.warn("===> " + gitHubRepository.getName() + " Issue count: " + issues.size() + " PR count: " + prs.size());

        Issues.logOpen(issues);
        PullRequests.logOpen(prs);
    }
}
 
Example #16
Source File: ForkableRepoValidatorTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testParentIsNotArchivedSoForkIt() {
    DockerfileGitHubUtil dockerfileGitHubUtil = mock(DockerfileGitHubUtil.class);
    GHRepository repo = mock(GHRepository.class);
    ForkableRepoValidator validator = new ForkableRepoValidator(dockerfileGitHubUtil);

    when(repo.isArchived()).thenReturn(false);
    ShouldForkResult shouldForkResult = validator.parentIsArchived(repo);
    assertTrue(shouldForkResult.isForkable());
}
 
Example #17
Source File: ForkableRepoValidatorTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testCantForkCouldNotTellIfThisUserIsOwner() throws IOException {
    DockerfileGitHubUtil dockerfileGitHubUtil = mock(DockerfileGitHubUtil.class);
    GHRepository repo = mock(GHRepository.class);
    ForkableRepoValidator validator = new ForkableRepoValidator(dockerfileGitHubUtil);

    when(dockerfileGitHubUtil.thisUserIsOwner(repo)).thenThrow(new IOException("sad times"));
    ShouldForkResult shouldForkResult = validator.thisUserIsNotOwner(repo);
    assertFalse(shouldForkResult.isForkable());
    assertEquals(shouldForkResult.getReason(), COULD_NOT_CHECK_THIS_USER);
}
 
Example #18
Source File: Issues.java    From updatebot with Apache License 2.0 5 votes vote down vote up
public static List<GHIssue> getOpenIssues(GHRepository ghRepository, String label) throws IOException {
    List<GHIssue> issues = retryGithub(() -> ghRepository.getIssues(GHIssueState.OPEN));
    List<GHIssue> answer = new ArrayList<>();
    for (GHIssue issue : issues) {
        if (GitHubHelpers.hasLabel(getLabels(issue), label) && !issue.isPullRequest()) {
            answer.add(issue);
        }
    }
    return answer;
}
 
Example #19
Source File: TestCommon.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Exception checkAndDelete(GHRepository repo) {
    log.info("deleting {}", repo.getFullName());
    try {
        repo.delete();
    } catch (Exception e) {
        return e;
    }
    return null;
}
 
Example #20
Source File: ProjectConfigInfo.java    From DotCi with MIT License 5 votes vote down vote up
public ProjectConfigInfo(String ghRepoName, GHRepository ghRepository) {
    this(
        ghRepoName,
        ghRepository,
        SetupConfig.get().getDynamicProjectRepository(),
        SetupConfig.get().getGithubAccessTokenRepository(),
        new GithubRepositoryService(ghRepository)
    );
}
 
Example #21
Source File: GitHubTagAction.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private static String buildUrl(GHRepository remoteRepository, String tag) {
    String repoUrl = remoteRepository.getHtmlUrl().toExternalForm();
    if (remoteRepository.getDefaultBranch().equals(tag)) {
        return repoUrl;
    }
    return repoUrl + "/releases/tag/" + tag;
}
 
Example #22
Source File: ForkableRepoValidatorTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testCanForkThisUserIsNotOwner() throws IOException {
    DockerfileGitHubUtil dockerfileGitHubUtil = mock(DockerfileGitHubUtil.class);
    GHRepository repo = mock(GHRepository.class);
    ForkableRepoValidator validator = new ForkableRepoValidator(dockerfileGitHubUtil);

    when(dockerfileGitHubUtil.thisUserIsOwner(repo)).thenReturn(false);
    ShouldForkResult shouldForkResult = validator.thisUserIsNotOwner(repo);
    assertTrue(shouldForkResult.isForkable());
}
 
Example #23
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 #24
Source File: GitHubPullRequestSenderTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetForkFromExistingRecordToProcess() {
    String reponame = "reponame";
    DockerfileGitHubUtil dockerfileGitHubUtil = mock(DockerfileGitHubUtil.class);
    GitHubPullRequestSender gitHubPullRequestSender = new GitHubPullRequestSender(dockerfileGitHubUtil, mock(ForkableRepoValidator.class));
    GHRepository fork = mock(GHRepository.class);
    GHRepository parent = mock(GHRepository.class);
    Multimap<String, GitHubContentToProcess> processMultimap = HashMultimap.create();
    processMultimap.put(reponame, new GitHubContentToProcess(fork, parent, "path"));
    assertEquals(gitHubPullRequestSender.getForkFromExistingRecordToProcess(processMultimap, reponame), fork);
}
 
Example #25
Source File: GitHubPullRequestSenderTest.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testDoNotForkReposWhichDoNotQualify() throws Exception {
    DockerfileGitHubUtil dockerfileGitHubUtil = mock(DockerfileGitHubUtil.class);

    GHRepository contentRepo1 = mock(GHRepository.class);
    when(contentRepo1.getFullName()).thenReturn("1");

    GHContent content1 = mock(GHContent.class);
    when(content1.getOwner()).thenReturn(contentRepo1);
    when(contentRepo1.isFork()).thenReturn(true);

    PagedSearchIterable<GHContent> contentsWithImage = mock(PagedSearchIterable.class);

    PagedIterator<GHContent> contentsWithImageIterator = mock(PagedIterator.class);
    when(contentsWithImageIterator.hasNext()).thenReturn(true, false);
    when(contentsWithImageIterator.next()).thenReturn(content1, null);
    when(contentsWithImage.iterator()).thenReturn(contentsWithImageIterator);

    when(dockerfileGitHubUtil.getRepo(any())).thenReturn(contentRepo1);

    ForkableRepoValidator forkableRepoValidator = mock(ForkableRepoValidator.class);
    when(forkableRepoValidator.shouldFork(any(), any(), any())).thenReturn(ShouldForkResult.shouldNotForkResult(""));

    GitHubPullRequestSender pullRequestSender = new GitHubPullRequestSender(dockerfileGitHubUtil, forkableRepoValidator);
    Multimap<String, GitHubContentToProcess> repoMap =
            pullRequestSender.forkRepositoriesFoundAndGetPathToDockerfiles(contentsWithImage, null);

    verify(dockerfileGitHubUtil, never()).getOrCreateFork(any());
    assertEquals(repoMap.size(), 0);
}
 
Example #26
Source File: ForkableRepoValidator.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Check various conditions required for a repo to qualify for updates
 *
 * @param parentRepo parent repo we're checking
 * @param searchResultContent search result content we'll check against
 * @return should we fork the parentRepo?
 */
public ShouldForkResult shouldFork(GHRepository parentRepo,
                                   GHContent searchResultContent,
                                   GitForkBranch gitForkBranch) {
    return parentIsFork(parentRepo)
            .and(parentIsArchived(parentRepo)
                    .and(thisUserIsNotOwner(parentRepo)
                            .and(contentHasChangesInDefaultBranch(parentRepo, searchResultContent, gitForkBranch))));
}
 
Example #27
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutCommitMustFail() 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);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(null);

    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',  " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_COMMIT, b1);
}
 
Example #28
Source File: GHRepoDeleted.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public Boolean call() throws Exception {
    GHRepository repository;
    try {
        repository = gitHub.getRepository(repoName);
    } catch (FileNotFoundException ignore) {
        LOG.debug("[WAIT] GitHub repository '{}' doesn't found", repoName);
        return true;
    }

    LOG.debug("[WAIT] GitHub repository '{}' {}", repoName, isNull(repository) ? "doesn't found" : "exists");
    return isNull(repository);
}
 
Example #29
Source File: GithubSCMSourceTagsTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Test
public void testExistingMultipleTagsIteratorGHExceptionOnHasNextButThrowsFileNotFoundOnGetRefs() throws IOException {
    // Scenario: multiple tags but catches a GH exception on hasNext and then
    // FilenotFound on getRefs
    SCMHeadObserver mockSCMHeadObserver = Mockito.mock(SCMHeadObserver.class);
    Exception expectedError = new GHException("Bad Tag Request");
    Exception expectedGetRefError = new FileNotFoundException("Bad Tag Ref Request");
    Mockito.when(mockSCMHeadObserver.getIncludes()).thenReturn(
            new HashSet<>(Arrays.asList(
                    new GitHubTagSCMHead("existent-multiple-tags1", System.currentTimeMillis()),
                    new GitHubTagSCMHead("existent-multiple-tags2", System.currentTimeMillis()))));
    GitHubSCMSourceContext context = new GitHubSCMSourceContext(null, mockSCMHeadObserver);
    context.wantTags(true);
    GitHubSCMSourceRequest request = context.newRequest(new GitHubSCMSource("cloudbeers", "yolo", null, false), null);
    GHRepository repoSpy = Mockito.spy(repo);
    PagedIterable<GHRef> iterableSpy = (PagedIterable<GHRef>)Mockito.mock(PagedIterable.class);
    Mockito.when(repoSpy.listRefs("tags")).thenReturn(iterableSpy);

    PagedIterator<GHRef> iteratorSpy = (PagedIterator<GHRef>)Mockito.mock(PagedIterator.class);
    Mockito.when(iterableSpy.iterator()).thenReturn(iteratorSpy);
    Iterator<GHRef> tags = new GitHubSCMSource.LazyTags(request, repoSpy).iterator();
    Mockito.when(iteratorSpy.hasNext()).thenThrow(expectedError);
    Mockito.when(repoSpy.getRefs("tags")).thenThrow(expectedGetRefError);

    //Expected: First call to hasNext throws a GHException and then returns a FileNotFound on getRefs so it returns an empty list
    assertFalse(tags.hasNext());
}
 
Example #30
Source File: Child.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void execute(final Namespace ns, final DockerfileGitHubUtil dockerfileGitHubUtil)
        throws IOException, InterruptedException {
    String branch = ns.get(Constants.GIT_BRANCH);
    String img = ns.get(Constants.IMG);
    String forceTag = ns.get(Constants.FORCE_TAG);

    /* Updates store if a store is specified. */
    dockerfileGitHubUtil.getGitHubJsonStore(ns.get(Constants.STORE)).updateStore(img, forceTag);

    log.info("Retrieving repository and creating fork...");
    GHRepository repo = dockerfileGitHubUtil.getRepo(ns.get(Constants.GIT_REPO));
    GHRepository fork = dockerfileGitHubUtil.getOrCreateFork(repo);
    if (fork == null) {
        log.info("Unable to fork {}. Please make sure that the repo is forkable.",
                repo.getFullName());
        return;
    }

    GitForkBranch gitForkBranch = new GitForkBranch(img, forceTag, branch);

    dockerfileGitHubUtil.createOrUpdateForkBranchToParentDefault(repo, fork, gitForkBranch);

    log.info("Modifying on Github...");
    dockerfileGitHubUtil.modifyAllOnGithub(fork, gitForkBranch.getBranchName(), img, forceTag);
    dockerfileGitHubUtil.createPullReq(repo, gitForkBranch.getBranchName(), fork, ns.get(Constants.GIT_PR_TITLE));
}