Search in sources :

Example 1 with PullRequest

use of com.google.copybara.git.github.api.PullRequest in project copybara by google.

the class GithubPrDestination method newWriter.

@Override
public Writer<GitRevision> newWriter(Glob destinationFiles, boolean dryRun, @Nullable String groupId, @Nullable Writer<GitRevision> oldWriter) throws ValidationException {
    WriterImpl gitOldWriter = (WriterImpl) oldWriter;
    boolean effectiveSkipPush = GithubPrDestination.this.effectiveSkipPush || dryRun;
    GithubWriterState state;
    String pushBranchName = branchFromGroupId(groupId);
    if (oldWriter != null && gitOldWriter.skipPush == effectiveSkipPush) {
        state = (GithubWriterState) ((WriterImpl) oldWriter).state;
    } else {
        state = new GithubWriterState(localRepo, destinationOptions.localRepoPath != null ? pushBranchName : "copybara/push-" + UUID.randomUUID() + (dryRun ? "-dryrun" : ""));
    }
    return new WriterImpl<GithubWriterState>(destinationFiles, effectiveSkipPush, url, destinationRef, pushBranchName, generalOptions, commitGenerator, processPushOutput, state, /*nonFastForwardPush=*/
    true, integrates, destinationOptions.lastRevFirstParent, destinationOptions.ignoreIntegrationErrors, destinationOptions.localRepoPath, destinationOptions.committerName, destinationOptions.committerEmail, destinationOptions.rebaseWhenBaseline(), gitOptions.visitChangePageSize) {

        @Override
        public ImmutableList<DestinationEffect> write(TransformResult transformResult, Console console) throws ValidationException, RepoException, IOException {
            ImmutableList.Builder<DestinationEffect> result = ImmutableList.<DestinationEffect>builder().addAll(super.write(transformResult, console));
            if (effectiveSkipPush || state.pullRequestNumber != null) {
                return result.build();
            }
            if (!githubDestinationOptions.createPullRequest) {
                console.infoFmt("Please create a PR manually following this link: %s/compare/%s...%s" + " (Only needed once)", asHttpsUrl(), destinationRef, pushBranchName);
                state.pullRequestNumber = -1L;
                return result.build();
            }
            GithubApi api = githubOptions.getApi(GithubUtil.getProjectNameFromUrl(url));
            for (PullRequest pr : api.getPullRequests(getProjectName())) {
                if (pr.isOpen() && pr.getHead().getRef().equals(pushBranchName)) {
                    console.infoFmt("Pull request for branch %s already exists as %s/pull/%s", pushBranchName, asHttpsUrl(), pr.getNumber());
                    if (!pr.getBase().getRef().equals(destinationRef)) {
                        // TODO(malcon): Update PR or create a new one?
                        console.warnFmt("Current base branch '%s' is different from the PR base branch '%s'", destinationRef, pr.getBase().getRef());
                    }
                    result.add(new DestinationEffect(DestinationEffect.Type.UPDATED, String.format("Pull Request %s updated", pr.getHtmlUrl()), transformResult.getChanges().getCurrent(), new DestinationEffect.DestinationRef(Long.toString(pr.getNumber()), "pull_request", pr.getHtmlUrl()), ImmutableList.of()));
                    return result.build();
                }
            }
            ChangeMessage msg = ChangeMessage.parseMessage(transformResult.getSummary());
            PullRequest pr = api.createPullRequest(getProjectName(), new CreatePullRequest(title == null ? msg.firstLine() : title, body == null ? msg.getText() : body, pushBranchName, destinationRef));
            console.infoFmt("Pull Request %s/pull/%s created using branch '%s'.", asHttpsUrl(), pr.getNumber(), pushBranchName);
            state.pullRequestNumber = pr.getNumber();
            result.add(new DestinationEffect(DestinationEffect.Type.CREATED, String.format("Pull Request %s created", pr.getHtmlUrl()), transformResult.getChanges().getCurrent(), new DestinationEffect.DestinationRef(Long.toString(pr.getNumber()), "pull_request", pr.getHtmlUrl()), ImmutableList.of()));
            return result.build();
        }
    };
}
Also used : TransformResult(com.google.copybara.TransformResult) ImmutableList(com.google.common.collect.ImmutableList) CreatePullRequest(com.google.copybara.git.github.api.CreatePullRequest) PullRequest(com.google.copybara.git.github.api.PullRequest) GithubApi(com.google.copybara.git.github.api.GithubApi) CreatePullRequest(com.google.copybara.git.github.api.CreatePullRequest) WriterImpl(com.google.copybara.git.GitDestination.WriterImpl) DestinationEffect(com.google.copybara.DestinationEffect) Console(com.google.copybara.util.console.Console) ChangeMessage(com.google.copybara.ChangeMessage)

Example 2 with PullRequest

use of com.google.copybara.git.github.api.PullRequest in project copybara by google.

the class AbstractGithubApiTest method testCreatePullRequest.

@Test
public void testCreatePullRequest() throws Exception {
    trainMockPost("/repos/example/project/pulls", createValidator(TestCreatePullRequest.class, (cpr) -> cpr.getTitle().equals("title") && cpr.getBase().equals("aabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb") && cpr.getBody().equals("[TEST] example pull request one") && cpr.getHead().equals("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")), getResource("pulls_12345_testdata.json"));
    // The test does not actually use the data in the CreatePullRequest
    PullRequest pullRequest = api.createPullRequest("example/project", new CreatePullRequest("title", "[TEST] example pull request one", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "aabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
    assertThat(pullRequest.getNumber()).isEqualTo(12345);
    assertThat(pullRequest.getState()).isEqualTo("open");
    assertThat(pullRequest.getTitle()).isEqualTo("[TEST] example pull request one");
}
Also used : GsonFactory(com.google.api.client.json.gson.GsonFactory) GithubApi(com.google.copybara.git.github.api.GithubApi) CombinedStatus(com.google.copybara.git.github.api.CombinedStatus) Review(com.google.copybara.git.github.api.Review) Lists(com.google.common.collect.Lists) State(com.google.copybara.git.github.api.Status.State) ImmutableList(com.google.common.collect.ImmutableList) Assert.fail(org.junit.Assert.fail) GitHubApiTransport(com.google.copybara.git.github.api.GitHubApiTransport) Issue(com.google.copybara.git.github.api.Issue) Profiler(com.google.copybara.profiler.Profiler) Before(org.junit.Before) Label(com.google.copybara.git.github.api.Issue.Label) GitHubApiException(com.google.copybara.git.github.api.GitHubApiException) Files(java.nio.file.Files) Predicate(java.util.function.Predicate) ResponseCode(com.google.copybara.git.github.api.GitHubApiException.ResponseCode) IOException(java.io.IOException) Test(org.junit.Test) Truth.assertThat(com.google.common.truth.Truth.assertThat) Ticker(com.google.common.base.Ticker) CreatePullRequest(com.google.copybara.git.github.api.CreatePullRequest) List(java.util.List) PullRequest(com.google.copybara.git.github.api.PullRequest) Ref(com.google.copybara.git.github.api.Ref) Paths(java.nio.file.Paths) LogProfilerListener(com.google.copybara.profiler.LogProfilerListener) Status(com.google.copybara.git.github.api.Status) CreateStatusRequest(com.google.copybara.git.github.api.CreateStatusRequest) CreatePullRequest(com.google.copybara.git.github.api.CreatePullRequest) PullRequest(com.google.copybara.git.github.api.PullRequest) CreatePullRequest(com.google.copybara.git.github.api.CreatePullRequest) Test(org.junit.Test)

Example 3 with PullRequest

use of com.google.copybara.git.github.api.PullRequest in project copybara by google.

the class AbstractGithubApiTest method testGetPull.

@Test
public void testGetPull() throws Exception {
    trainMockGet("/repos/example/project/pulls/12345", getResource("pulls_12345_testdata.json"));
    PullRequest pullRequest = api.getPullRequest("example/project", 12345);
    assertThat(pullRequest.getNumber()).isEqualTo(12345);
    assertThat(pullRequest.getState()).isEqualTo("open");
    assertThat(pullRequest.getTitle()).isEqualTo("[TEST] example pull request one");
    assertThat(pullRequest.getBody()).isEqualTo("Example body.\r\n");
    assertThat(pullRequest.getHead().getLabel()).isEqualTo("googletestuser:example-branch");
    assertThat(pullRequest.getHead().getRef()).isEqualTo("example-branch");
    assertThat(pullRequest.getHead().getSha()).isEqualTo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
}
Also used : CreatePullRequest(com.google.copybara.git.github.api.CreatePullRequest) PullRequest(com.google.copybara.git.github.api.PullRequest) Test(org.junit.Test)

Example 4 with PullRequest

use of com.google.copybara.git.github.api.PullRequest in project copybara by google.

the class GithubPROrigin method getRevisionForPR.

private GitRevision getRevisionForPR(String project, int prNumber) throws RepoException, ValidationException {
    if (!requiredLabels.isEmpty()) {
        int retryCount = 0;
        Set<String> requiredButNotPresent;
        do {
            Issue issue;
            try (ProfilerTask ignore = generalOptions.profiler().start("github_api_get_issue")) {
                issue = githubOptions.getApi(project).getIssue(project, prNumber);
            }
            requiredButNotPresent = Sets.newHashSet(requiredLabels);
            requiredButNotPresent.removeAll(Collections2.transform(issue.getLabels(), Label::getName));
            // If we got all the labels we want or none of the ones we didn't get are retryable, return.
            if (requiredButNotPresent.isEmpty() || Collections.disjoint(requiredButNotPresent, retryableLabels)) {
                break;
            }
            Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS);
            retryCount++;
        } while (retryCount < RETRY_COUNT);
        if (!requiredButNotPresent.isEmpty()) {
            throw new EmptyChangeException(String.format("Cannot migrate http://github.com/%s/pull/%d because it is missing the following" + " labels: %s", project, prNumber, requiredButNotPresent));
        }
    }
    PullRequest prData;
    try (ProfilerTask ignore = generalOptions.profiler().start("github_api_get_pr")) {
        prData = githubOptions.getApi(project).getPullRequest(project, prNumber);
    }
    if (requiredState == StateFilter.OPEN && !prData.isOpen()) {
        throw new EmptyChangeException(String.format("Pull Request %d is not open", prNumber));
    }
    if (requiredState == StateFilter.CLOSED && prData.isOpen()) {
        throw new EmptyChangeException(String.format("Pull Request %d is open", prNumber));
    }
    String stableRef = useMerge ? GithubUtil.asMergeRef(prNumber) : GithubUtil.asHeadRef(prNumber);
    // Fetch also the baseline branch. It is almost free and doing a roundtrip later would hurt
    // latency.
    console.progressFmt("Fetching Pull Request %d and branch '%s'", prNumber, prData.getBase().getRef());
    try {
        getRepository().fetch(asGithubUrl(project), /*prune=*/
        false, /*force=*/
        true, ImmutableList.of(stableRef + ":refs/PR_HEAD", // GitRepository need the whole reference name.
        "refs/heads/" + prData.getBase().getRef() + ":refs/PR_BASE_BRANCH"));
    } catch (CannotResolveRevisionException e) {
        if (useMerge) {
            throw new CannotResolveRevisionException(String.format("Cannot find a merge reference for Pull Request %d." + " It might have a conflict with head.", prNumber), e);
        } else {
            throw new CannotResolveRevisionException(String.format("Cannot find Pull Request %d.", prNumber), e);
        }
    }
    GitRevision gitRevision = getRepository().resolveReference("PR_HEAD");
    String integrateLabel = new GithubPRIntegrateLabel(getRepository(), generalOptions, project, prNumber, prData.getHead().getLabel(), gitRevision.getSha1()).toString();
    ImmutableMap.Builder<String, String> labels = ImmutableMap.builder();
    labels.put(GITHUB_PR_NUMBER_LABEL, Integer.toString(prNumber));
    labels.put(GitModule.DEFAULT_INTEGRATE_LABEL, integrateLabel);
    labels.put(GITHUB_BASE_BRANCH, prData.getBase().getRef());
    String mergeBase = getRepository().mergeBase("refs/PR_HEAD", "refs/PR_BASE_BRANCH");
    labels.put(GITHUB_BASE_BRANCH_SHA1, mergeBase);
    labels.put(GITHUB_PR_TITLE, prData.getTitle());
    labels.put(GITHUB_PR_BODY, prData.getBody());
    return new GitRevision(getRepository(), gitRevision.getSha1(), /*reviewReference=*/
    null, stableRef, labels.build(), url);
}
Also used : Issue(com.google.copybara.git.github.api.Issue) ProfilerTask(com.google.copybara.profiler.Profiler.ProfilerTask) PullRequest(com.google.copybara.git.github.api.PullRequest) CannotResolveRevisionException(com.google.copybara.exception.CannotResolveRevisionException) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) Endpoint(com.google.copybara.Endpoint) ImmutableMap(com.google.common.collect.ImmutableMap)

Aggregations

PullRequest (com.google.copybara.git.github.api.PullRequest)4 CreatePullRequest (com.google.copybara.git.github.api.CreatePullRequest)3 ImmutableList (com.google.common.collect.ImmutableList)2 GithubApi (com.google.copybara.git.github.api.GithubApi)2 Issue (com.google.copybara.git.github.api.Issue)2 Test (org.junit.Test)2 GsonFactory (com.google.api.client.json.gson.GsonFactory)1 Ticker (com.google.common.base.Ticker)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 Lists (com.google.common.collect.Lists)1 Truth.assertThat (com.google.common.truth.Truth.assertThat)1 ChangeMessage (com.google.copybara.ChangeMessage)1 DestinationEffect (com.google.copybara.DestinationEffect)1 Endpoint (com.google.copybara.Endpoint)1 TransformResult (com.google.copybara.TransformResult)1 CannotResolveRevisionException (com.google.copybara.exception.CannotResolveRevisionException)1 EmptyChangeException (com.google.copybara.exception.EmptyChangeException)1 WriterImpl (com.google.copybara.git.GitDestination.WriterImpl)1 CombinedStatus (com.google.copybara.git.github.api.CombinedStatus)1 CreateStatusRequest (com.google.copybara.git.github.api.CreateStatusRequest)1