use of com.google.copybara.git.github.api.GitHubApiException in project copybara by google.
the class GitHubEndPoint method getPullRequests.
@StarlarkMethod(name = "get_pull_requests", doc = "Get Pull Requests for a repo", parameters = { @Param(name = "head_prefix", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "Only return PRs wher the branch name has head_prefix", defaultValue = "None"), @Param(name = "base_prefix", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "Only return PRs where the destination branch name has base_prefix", defaultValue = "None"), @Param(name = "state", doc = "State of the Pull Request. Can be `\"OPEN\"`, `\"CLOSED\"` or `\"ALL\"`", defaultValue = "\"OPEN\"", named = true), @Param(name = "sort", doc = "Sort filter for retrieving the Pull Requests. Can be `\"CREATED\"`," + " `\"UPDATED\"` or `\"POPULARITY\"`", named = true, defaultValue = "\"CREATED\""), @Param(name = "direction", doc = "Direction of the filter. Can be `\"ASC\"` or `\"DESC\"`", defaultValue = "\"ASC\"", named = true) }, allowReturnNones = true)
@Nullable
public ImmutableList<PullRequest> getPullRequests(Object headPrefixParam, Object basePrefixParam, String state, String sort, String direction) throws EvalException, RepoException {
try {
String project = ghHost.getProjectNameFromUrl(url);
PullRequestListParams request = PullRequestListParams.DEFAULT;
String headPrefix = convertFromNoneable(headPrefixParam, null);
String basePrefix = convertFromNoneable(basePrefixParam, null);
if (!Strings.isNullOrEmpty(headPrefix)) {
checkCondition(SAFE_BRANCH_NAME_PREFIX.matches(headPrefix), "'%s' is not a valid head_prefix (%s is used for validation)", headPrefix, SAFE_BRANCH_NAME_PREFIX.pattern());
request = request.withHead(headPrefix);
}
if (!Strings.isNullOrEmpty(basePrefix)) {
checkCondition(SAFE_BRANCH_NAME_PREFIX.matches(basePrefix), "'%s' is not a valid base_prefix (%s is used for validation)", basePrefix, SAFE_BRANCH_NAME_PREFIX.pattern());
request = request.withHead(basePrefix);
}
return apiSupplier.load(console).getPullRequests(project, request.withState(stringToEnum("state", state, StateFilter.class)).withDirection(stringToEnum("direction", direction, DirectionFilter.class)).withSort(stringToEnum("sort", sort, SortFilter.class)));
} catch (GitHubApiException e) {
return returnNullOnNotFound(e);
} catch (ValidationException | RuntimeException e) {
throw Starlark.errorf("Error calling get_pull_requests: %s", e.getMessage());
}
}
use of com.google.copybara.git.github.api.GitHubApiException in project copybara by google.
the class GitHubPrWriteHook method beforePush.
@Override
public void beforePush(GitRepository scratchClone, MessageInfo messageInfo, boolean skipPush, List<? extends Change<?>> originChanges) throws ValidationException, RepoException {
if (skipPush || generalOptions.allowEmptyDiff(allowEmptyDiff)) {
return;
}
for (Change<?> originalChange : originChanges) {
String configProjectName = ghHost.getProjectNameFromUrl(repoUrl);
GitHubApi api = gitHubOptions.newGitHubApi(configProjectName);
try {
ImmutableList<PullRequest> pullRequests = api.getPullRequests(configProjectName, PullRequestListParams.DEFAULT.withHead(String.format("%s:%s", ghHost.getUserNameFromUrl(repoUrl), this.prBranchToUpdate)));
// We don't want to throw EmptyChangeException for some of the prs with the empty diff.
if (pullRequests.size() != 1) {
return;
}
SameGitTree sameGitTree = new SameGitTree(scratchClone, repoUrl, generalOptions, partialFetch);
PullRequest pullRequest = pullRequests.get(0);
if (sameGitTree.hasSameTree(pullRequest.getHead().getSha())) {
throw new RedundantChangeException(String.format("Skipping push to the existing pr %s/pull/%s as the change %s is empty.", repoUrl, pullRequest.getNumber(), originalChange.getRef()), pullRequest.getHead().getSha());
}
} catch (GitHubApiException e) {
if (e.getResponseCode() == ResponseCode.NOT_FOUND || e.getResponseCode() == ResponseCode.UNPROCESSABLE_ENTITY) {
console.verboseFmt("Branch %s does not exist", this.prBranchToUpdate);
}
throw e;
}
}
}
use of com.google.copybara.git.github.api.GitHubApiException in project copybara by google.
the class GitHubWriteHook method afterPush.
@Override
public ImmutableList<DestinationEffect> afterPush(String serverResponse, MessageInfo messageInfo, GitRevision pushedRevision, List<? extends Change<?>> originChanges) throws ValidationException, RepoException {
ImmutableList.Builder<DestinationEffect> baseEffects = ImmutableList.<DestinationEffect>builder().addAll(super.afterPush(serverResponse, messageInfo, pushedRevision, originChanges));
if (prBranchToUpdate == null || !deletePrBranch) {
return baseEffects.build();
}
String projectId = ghHost.getProjectNameFromUrl(repoUrl);
GitHubApi api = gitHubOptions.newGitHubApi(projectId);
for (Change<?> change : originChanges) {
Dict<String, String> labelDict = change.getLabelsForSkylark();
String updatedPrBranchName = getUpdatedPrBranch(labelDict);
checkCondition(!Objects.equals(updatedPrBranchName, "master"), "Cannot delete 'master' branch from GitHub");
String completeRef = String.format("refs/heads/%s", updatedPrBranchName);
try {
api.deleteReference(projectId, completeRef);
baseEffects.add(new DestinationEffect(Type.UPDATED, String.format("Reference '%s' deleted", completeRef), ImmutableList.of(change), new DestinationRef(completeRef, "ref_deleted", "https://github.com/" + projectId + "/tree/" + updatedPrBranchName)));
} catch (GitHubApiException e) {
if (e.getResponseCode() == ResponseCode.NOT_FOUND || e.getResponseCode() == ResponseCode.UNPROCESSABLE_ENTITY) {
console.infoFmt("Branch %s does not exist", updatedPrBranchName);
logger.atInfo().log("Branch %s does not exist", updatedPrBranchName);
continue;
}
throw e;
}
}
return baseEffects.build();
}
use of com.google.copybara.git.github.api.GitHubApiException in project copybara by google.
the class GitHubEndPoint method createStatus.
@StarlarkMethod(name = "create_status", doc = "Create or update a status for a commit. Returns the status created.", parameters = { @Param(name = "sha", named = true, doc = "The SHA-1 for which we want to create or update the status"), @Param(name = "state", named = true, doc = "The state of the commit status: 'success', 'error', 'pending' or 'failure'"), @Param(name = "context", doc = "The context for the commit status. Use a value like 'copybara/import_successful'" + " or similar", named = true), @Param(name = "description", named = true, doc = "Description about what happened"), @Param(name = "target_url", allowedTypes = { @ParamType(type = String.class), @ParamType(type = NoneType.class) }, named = true, doc = "Url with expanded information about the event", defaultValue = "None") })
public Status createStatus(String sha, String state, String context, String description, Object targetUrl) throws EvalException, RepoException, ValidationException {
try {
checkCondition(State.VALID_VALUES.contains(state), "Invalid value for state. Valid values: %s", State.VALID_VALUES);
checkCondition(GitRevision.COMPLETE_SHA1_PATTERN.matcher(sha).matches(), "Not a valid complete SHA-1: %s", sha);
checkCondition(!Strings.isNullOrEmpty(description), "description cannot be empty");
checkCondition(!Strings.isNullOrEmpty(context), "context cannot be empty");
String project = ghHost.getProjectNameFromUrl(url);
return apiSupplier.load(console).createStatus(project, sha, new CreateStatusRequest(State.valueOf(state.toUpperCase()), convertFromNoneable(targetUrl, null), description, context));
} catch (GitHubApiException gae) {
if (gae.getResponseCode() == ResponseCode.UNPROCESSABLE_ENTITY) {
throw new ValidationException("GitHub was unable to process the request " + gae.getError(), gae);
}
throw gae;
} catch (ValidationException | RuntimeException e) {
throw Starlark.errorf("Error calling create_status: %s", e.getMessage());
}
}
use of com.google.copybara.git.github.api.GitHubApiException in project copybara by google.
the class GitHubWriteHook method beforePush.
@Override
public void beforePush(GitRepository scratchClone, MessageInfo messageInfo, boolean skipPush, List<? extends Change<?>> originChanges) throws ValidationException, RepoException {
if (skipPush || prBranchToUpdate == null) {
return;
}
String configProjectName = ghHost.getProjectNameFromUrl(repoUrl);
GitHubApi api = gitHubOptions.newGitHubApi(configProjectName);
for (Change<?> change : originChanges) {
Dict<String, String> labelDict = change.getLabelsForSkylark();
String updatedPrBranchName = getUpdatedPrBranch(labelDict);
String completeRef = String.format("refs/heads/%s", updatedPrBranchName);
try {
// fails with NOT_FOUND if doesn't exist
api.getReference(configProjectName, completeRef);
generalOptions.repoTask("push current commit to the head of pr_branch_to_update", () -> scratchClone.push().withRefspecs(repoUrl, ImmutableList.of(scratchClone.createRefSpec("+HEAD:" + completeRef))).run());
} catch (GitHubApiException e) {
if (e.getResponseCode() == ResponseCode.NOT_FOUND || e.getResponseCode() == ResponseCode.UNPROCESSABLE_ENTITY) {
console.verboseFmt("Branch %s does not exist", updatedPrBranchName);
logger.atInfo().log("Branch %s does not exist", updatedPrBranchName);
continue;
}
throw e;
}
}
}
Aggregations