Search in sources :

Example 1 with User

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

the class GitHubPrOrigin method getRevisionForPR.

private GitRevision getRevisionForPR(String project, PullRequest prData) throws RepoException, ValidationException {
    GitHubApi api = gitHubOptions.newGitHubApi(project);
    int prNumber = (int) prData.getNumber();
    boolean actuallyUseMerge = this.useMerge;
    ImmutableListMultimap.Builder<String, String> labels = ImmutableListMultimap.builder();
    checkPrState(prData);
    checkPrBranch(project, prData);
    checkRequiredLabels(api, project, prData);
    checkRequiredStatusContextNames(api, project, prData);
    checkRequiredCheckRuns(api, project, prData);
    checkReviewApprovers(api, project, prData, labels);
    // 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());
    ImmutableList.Builder<String> refSpecBuilder = ImmutableList.<String>builder().add(String.format("%s:%s", asHeadRef(prNumber), LOCAL_PR_HEAD_REF)).add(String.format("refs/heads/%s:" + LOCAL_PR_BASE_BRANCH, prData.getBase().getRef()));
    if (actuallyUseMerge) {
        if (!Boolean.FALSE.equals(prData.isMergeable())) {
            refSpecBuilder.add(String.format("%s:%s", asMergeRef(prNumber), LOCAL_PR_MERGE_REF));
        } else if (forceImport()) {
            console.warnFmt("PR %d is not mergeable, but continuing with PR Head instead because of %s", prNumber, GeneralOptions.FORCE);
            actuallyUseMerge = false;
        } else {
            throw new CannotResolveRevisionException(String.format("Cannot find a merge reference for Pull Request %d." + " It might have a conflict with head.", prNumber));
        }
    }
    ImmutableList<String> refspec = refSpecBuilder.build();
    try (ProfilerTask ignore = generalOptions.profiler().start("fetch")) {
        getRepository().fetch(ghHost.projectAsUrl(project), /*prune=*/
        false, /*force=*/
        true, refspec, partialFetch);
    } catch (CannotResolveRevisionException e) {
        if (actuallyUseMerge && prData.isMergeable() == null && forceImport()) {
            // We can perhaps recover by fetching without the merge ref
            actuallyUseMerge = false;
            refspec = refspec.subList(0, refspec.size() - 1);
            try (ProfilerTask ignore = generalOptions.profiler().start("fetch")) {
                getRepository().fetch(ghHost.projectAsUrl(project), /*prune=*/
                false, /*force=*/
                true, refspec, partialFetch);
                e = null;
            } catch (CannotResolveRevisionException e2) {
                // Report the error from the second fetch instead of the original fetch
                e = e2;
            }
        }
        if (e != null) {
            if (actuallyUseMerge) {
                String msg = String.format("Cannot find a merge reference for Pull Request %d.", prNumber);
                if (Boolean.TRUE.equals(prData.isMergeable())) {
                    msg += " GitHub reported that this merge reference should exist.";
                }
                throw new CannotResolveRevisionException(msg, e);
            } else {
                throw new CannotResolveRevisionException(String.format("Cannot find Pull Request %d.", prNumber), e);
            }
        }
    }
    String refForMigration = actuallyUseMerge ? LOCAL_PR_MERGE_REF : LOCAL_PR_HEAD_REF;
    GitRevision gitRevision = getRepository().resolveReference(refForMigration);
    String headPrSha1 = getRepository().resolveReference(LOCAL_PR_HEAD_REF).getSha1();
    String integrateLabel = new GitHubPrIntegrateLabel(getRepository(), generalOptions, project, prNumber, prData.getHead().getLabel(), // The integrate SHA has to be HEAD of the PR not the merge ref, even if use_merge = True
    headPrSha1).toString();
    labels.putAll(GITHUB_PR_REQUESTED_REVIEWER, prData.getRequestedReviewers().stream().map(User::getLogin).collect(toImmutableList()));
    labels.put(GITHUB_PR_NUMBER_LABEL, Integer.toString(prNumber));
    labels.put(GitModule.DEFAULT_INTEGRATE_LABEL, integrateLabel);
    labels.put(GITHUB_BASE_BRANCH, prData.getBase().getRef());
    labels.put(GITHUB_PR_HEAD_SHA, headPrSha1);
    labels.put(GITHUB_PR_USE_MERGE, Boolean.toString(actuallyUseMerge));
    String mergeBase = getRepository().mergeBase(refForMigration, LOCAL_PR_BASE_BRANCH);
    labels.put(GITHUB_BASE_BRANCH_SHA1, mergeBase);
    labels.put(GITHUB_PR_TITLE, prData.getTitle());
    labels.put(GITHUB_PR_BODY, prData.getBody());
    labels.put(GITHUB_PR_URL, prData.getHtmlUrl());
    labels.put(GITHUB_PR_USER, prData.getUser().getLogin());
    labels.putAll(GITHUB_PR_ASSIGNEE, prData.getAssignees().stream().map(User::getLogin).collect(Collectors.toList()));
    GitRevision result = new GitRevision(getRepository(), gitRevision.getSha1(), /*reviewReference=*/
    null, actuallyUseMerge ? asMergeRef(prNumber) : asHeadRef(prNumber), labels.build(), url);
    return describeVersion ? getRepository().addDescribeVersion(result) : result;
}
Also used : User(com.google.copybara.git.github.api.User) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ImmutableList(com.google.common.collect.ImmutableList) Endpoint(com.google.copybara.Endpoint) GitHubApi(com.google.copybara.git.github.api.GitHubApi) ProfilerTask(com.google.copybara.profiler.Profiler.ProfilerTask) ImmutableListMultimap.toImmutableListMultimap(com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) CannotResolveRevisionException(com.google.copybara.exception.CannotResolveRevisionException)

Example 2 with User

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

the class GitHubPrOrigin method checkReviewApprovers.

/**
 * Check that the PR has been approved by sufficient reviewers of the correct types, in accordance
 * with the values provided in the `review_state` and `review_approvers` params
 */
private void checkReviewApprovers(GitHubApi api, String project, PullRequest prData, ImmutableListMultimap.Builder<String, String> labelsBuilder) throws ValidationException, RepoException {
    if (reviewState == null) {
        return;
    }
    ImmutableList<Review> reviews = api.getReviews(project, prData.getNumber());
    ApproverState approverState = reviewState.shouldMigrate(reviews, reviewApprovers, prData.getHead().getSha());
    if (!forceImport() && !approverState.shouldMigrate()) {
        String rejected = "";
        if (!approverState.rejectedReviews().isEmpty()) {
            rejected = String.format("\nThe following reviews were ignored because they don't meet " + "the association requirement of %s:\n%s", Joiner.on(", ").join(reviewApprovers), approverState.rejectedReviews().entries().stream().map(e -> String.format("User %s - Association: %s", e.getKey(), e.getValue())).collect(joining("\n")));
        }
        throw new EmptyChangeException(String.format("Cannot migrate http://github.com/%s/pull/%d because it is missing the required" + " approvals (origin is configured as %s).%s", project, prData.getNumber(), reviewState, rejected));
    }
    Set<String> approvers = new HashSet<>();
    Set<String> others = new HashSet<>();
    for (Review review : reviews) {
        if (reviewApprovers.contains(review.getAuthorAssociation())) {
            approvers.add(review.getUser().getLogin());
        } else {
            others.add(review.getUser().getLogin());
        }
    }
    labelsBuilder.putAll(GITHUB_PR_REVIEWER_APPROVER, approvers);
    labelsBuilder.putAll(GITHUB_PR_REVIEWER_OTHER, others);
}
Also used : GitHubUtil.asHeadRef(com.google.copybara.git.github.util.GitHubUtil.asHeadRef) Origin(com.google.copybara.Origin) CombinedStatus(com.google.copybara.git.github.api.CombinedStatus) Collections2(com.google.common.collect.Collections2) Review(com.google.copybara.git.github.api.Review) ImmutableListMultimap.toImmutableListMultimap(com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap) Matcher(java.util.regex.Matcher) Change(com.google.copybara.Change) BaselinesWithoutLabelVisitor(com.google.copybara.BaselinesWithoutLabelVisitor) CannotResolveRevisionException(com.google.copybara.exception.CannotResolveRevisionException) Endpoint(com.google.copybara.Endpoint) Splitter(com.google.common.base.Splitter) GeneralOptions(com.google.copybara.GeneralOptions) Path(java.nio.file.Path) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) User(com.google.copybara.git.github.api.User) ProfilerTask(com.google.copybara.profiler.Profiler.ProfilerTask) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) Collectors(java.util.stream.Collectors) Collectors.joining(java.util.stream.Collectors.joining) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) List(java.util.List) GitHubApi(com.google.copybara.git.github.api.GitHubApi) PullRequest(com.google.copybara.git.github.api.PullRequest) GitHubUtil.asMergeRef(com.google.copybara.git.github.util.GitHubUtil.asMergeRef) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) AutoValue(com.google.auto.value.AutoValue) Optional(java.util.Optional) Joiner(com.google.common.base.Joiner) AuthorAssociation(com.google.copybara.git.github.api.AuthorAssociation) Iterables(com.google.common.collect.Iterables) CheckRuns(com.google.copybara.git.github.api.CheckRuns) ValidationException.checkCondition(com.google.copybara.exception.ValidationException.checkCondition) RepoException(com.google.copybara.exception.RepoException) SubmoduleStrategy(com.google.copybara.git.GitOrigin.SubmoduleStrategy) HashSet(java.util.HashSet) GitHubUtil(com.google.copybara.git.github.util.GitHubUtil) Label(com.google.copybara.git.github.api.Label) State(com.google.copybara.git.github.api.Status.State) ImmutableList(com.google.common.collect.ImmutableList) Issue(com.google.copybara.git.github.api.Issue) Nullable(javax.annotation.Nullable) GitLogEntry(com.google.copybara.git.GitRepository.GitLogEntry) Uninterruptibles(com.google.common.util.concurrent.Uninterruptibles) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) CharMatcher(com.google.common.base.CharMatcher) ValidationException(com.google.copybara.exception.ValidationException) ReaderImpl(com.google.copybara.git.GitOrigin.ReaderImpl) PatchTransformation(com.google.copybara.transform.patch.PatchTransformation) Console(com.google.copybara.util.console.Console) TimeUnit(java.util.concurrent.TimeUnit) Authoring(com.google.copybara.authoring.Authoring) Checker(com.google.copybara.checks.Checker) Glob(com.google.copybara.util.Glob) CheckRun(com.google.copybara.git.github.api.CheckRun) Preconditions(com.google.common.base.Preconditions) Status(com.google.copybara.git.github.api.Status) GitHubHost(com.google.copybara.git.github.util.GitHubHost) GitHubPrUrl(com.google.copybara.git.github.util.GitHubHost.GitHubPrUrl) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) Review(com.google.copybara.git.github.api.Review) HashSet(java.util.HashSet)

Example 3 with User

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

the class AbstractGitHubApiTest method testAuthenticatedUser.

@Test
public void testAuthenticatedUser() throws Exception {
    trainMockGet("/user", getResource("get_authenticated_user_response_testdata.json"));
    User user = api.getAuthenticatedUser();
    assertThat(user.getLogin()).isEqualTo("googletestuser");
}
Also used : User(com.google.copybara.git.github.api.User) Test(org.junit.Test)

Aggregations

User (com.google.copybara.git.github.api.User)3 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)2 ImmutableListMultimap (com.google.common.collect.ImmutableListMultimap)2 ImmutableListMultimap.toImmutableListMultimap (com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap)2 Endpoint (com.google.copybara.Endpoint)2 CannotResolveRevisionException (com.google.copybara.exception.CannotResolveRevisionException)2 GitHubApi (com.google.copybara.git.github.api.GitHubApi)2 ProfilerTask (com.google.copybara.profiler.Profiler.ProfilerTask)2 AutoValue (com.google.auto.value.AutoValue)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 CharMatcher (com.google.common.base.CharMatcher)1 Joiner (com.google.common.base.Joiner)1 Preconditions (com.google.common.base.Preconditions)1 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)1 Splitter (com.google.common.base.Splitter)1 Collections2 (com.google.common.collect.Collections2)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 ImmutableSetMultimap (com.google.common.collect.ImmutableSetMultimap)1 Iterables (com.google.common.collect.Iterables)1