Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -3584,7 +3584,7 @@ Name | Type | Description

Creates changes in a new pull request in the destination.

<code><a href="#destination">destination</a></code> <code>git.github_pr_destination(<a href=#git.github_pr_destination.url>url</a>, <a href=#git.github_pr_destination.destination_ref>destination_ref</a>='master', <a href=#git.github_pr_destination.pr_branch>pr_branch</a>=None, <a href=#git.github_pr_destination.partial_fetch>partial_fetch</a>=False, <a href=#git.github_pr_destination.allow_empty_diff>allow_empty_diff</a>=True, <a href=#git.github_pr_destination.allow_empty_diff_merge_statuses>allow_empty_diff_merge_statuses</a>=[], <a href=#git.github_pr_destination.allow_empty_diff_check_suites_to_conclusion>allow_empty_diff_check_suites_to_conclusion</a>={}, <a href=#git.github_pr_destination.title>title</a>=None, <a href=#git.github_pr_destination.body>body</a>=None, <a href=#git.github_pr_destination.assignees>assignees</a>=[], <a href=#git.github_pr_destination.integrates>integrates</a>=None, <a href=#git.github_pr_destination.api_checker>api_checker</a>=None, <a href=#git.github_pr_destination.update_description>update_description</a>=False, <a href=#git.github_pr_destination.primary_branch_migration>primary_branch_migration</a>=False, <a href=#git.github_pr_destination.checker>checker</a>=None, <a href=#git.github_pr_destination.draft>draft</a>=False, <a href=#git.github_pr_destination.credentials>credentials</a>=None, <a href=#git.github_pr_destination.github_host_name>github_host_name</a>='github.com')</code>
<code><a href="#destination">destination</a></code> <code>git.github_pr_destination(<a href=#git.github_pr_destination.url>url</a>, <a href=#git.github_pr_destination.destination_ref>destination_ref</a>='master', <a href=#git.github_pr_destination.pr_branch>pr_branch</a>=None, <a href=#git.github_pr_destination.partial_fetch>partial_fetch</a>=False, <a href=#git.github_pr_destination.allow_empty_diff>allow_empty_diff</a>=True, <a href=#git.github_pr_destination.allow_empty_diff_merge_statuses>allow_empty_diff_merge_statuses</a>=[], <a href=#git.github_pr_destination.allow_empty_diff_check_suites_to_conclusion>allow_empty_diff_check_suites_to_conclusion</a>={}, <a href=#git.github_pr_destination.title>title</a>=None, <a href=#git.github_pr_destination.body>body</a>=None, <a href=#git.github_pr_destination.assignees>assignees</a>=[], <a href=#git.github_pr_destination.labels>labels</a>=[], <a href=#git.github_pr_destination.integrates>integrates</a>=None, <a href=#git.github_pr_destination.api_checker>api_checker</a>=None, <a href=#git.github_pr_destination.update_description>update_description</a>=False, <a href=#git.github_pr_destination.primary_branch_migration>primary_branch_migration</a>=False, <a href=#git.github_pr_destination.checker>checker</a>=None, <a href=#git.github_pr_destination.draft>draft</a>=False, <a href=#git.github_pr_destination.credentials>credentials</a>=None, <a href=#git.github_pr_destination.github_host_name>github_host_name</a>='github.com')</code>


<h4 id="parameters.git.github_pr_destination">Parameters:</h4>
Expand All @@ -3601,6 +3601,7 @@ Parameter | Description
<span id=git.github_pr_destination.title href=#git.github_pr_destination.title>title</span> | <code><a href="#string">string</a></code> or <code>NoneType</code><br><p>When creating (or updating if `update_description` is set) a pull request, use this title. By default it uses the change first line. This field accepts a template with labels. For example: `"Change ${CONTEXT_REFERENCE}"`</p>
<span id=git.github_pr_destination.body href=#git.github_pr_destination.body>body</span> | <code><a href="#string">string</a></code> or <code>NoneType</code><br><p>When creating (or updating if `update_description` is set) a pull request, use this body. By default it uses the change summary. This field accepts a template with labels. For example: `"Change ${CONTEXT_REFERENCE}"`</p>
<span id=git.github_pr_destination.assignees href=#git.github_pr_destination.assignees>assignees</span> | <code>sequence of <a href="#string">string</a></code><br><p>The assignees to set when creating a new pull request. The maximum number of assignees is 10 and the assignees must be GitHub usernames or a label that can be resolved to a GitHub username. For example: `assignees = ["github-repo-owner1", "${YOUR_LABEL}"]`</p>
<span id=git.github_pr_destination.labels href=#git.github_pr_destination.labels>labels</span> | <code>sequence of <a href="#string">string</a></code><br><p>The GitHub labels to add to the pull request, both when creating it and when updating an existing one (labels are only ever added, never removed). Each entry is a label name or a template that can be resolved from the change's labels. For example: `labels = ["autogenerated", "${YOUR_LABEL}"]`. Labels are applied in a separate call; failure to apply them is logged as a warning.</p>
<span id=git.github_pr_destination.integrates href=#git.github_pr_destination.integrates>integrates</span> | <code>sequence of git_integrate</code> or <code>NoneType</code><br><p>Integrate changes from a url present in the migrated change label. Defaults to a semi-fake merge if COPYBARA_INTEGRATE_REVIEW label is present in the message</p>
<span id=git.github_pr_destination.api_checker href=#git.github_pr_destination.api_checker>api_checker</span> | <code><a href="#checker">checker</a></code> or <code>NoneType</code><br><p>A checker for the GitHub API endpoint provided for after_migration hooks. This field is not required if the workflow hooks don't use the origin/destination endpoints.</p>
<span id=git.github_pr_destination.update_description href=#git.github_pr_destination.update_description>update_description</span> | <code><a href="#bool">bool</a></code><br><p>By default, Copybara only set the title and body of the PR when creating the PR. If this field is set to true, it will update those fields for every update.</p>
Expand Down
28 changes: 28 additions & 0 deletions java/com/google/copybara/git/GitHubPrDestination.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public class GitHubPrDestination implements Destination<GitRevision> {
private final LazyResourceLoader<GitRepository> localRepo;
private final ConfigFile mainConfigFile;
private final List<String> assignees;
private final List<String> labels;
@Nullable private final Checker endpointChecker;

@Nullable private String resolvedDestinationRef;
Expand All @@ -110,6 +111,7 @@ public class GitHubPrDestination implements Destination<GitRevision> {
@Nullable String title,
@Nullable String body,
List<String> assignees,
List<String> labels,
ConfigFile mainConfigFile,
@Nullable String workflowName,
@Nullable Checker endpointChecker,
Expand All @@ -133,6 +135,7 @@ public class GitHubPrDestination implements Destination<GitRevision> {
this.integrates = Preconditions.checkNotNull(integrates);
this.title = title;
this.assignees = assignees;
this.labels = labels;
this.body = body;
this.updateDescription = updateDescription;
this.ghHost = Preconditions.checkNotNull(ghHost);
Expand Down Expand Up @@ -270,6 +273,9 @@ public ImmutableList<DestinationEffect> write(
ImmutableList<String> assignees =
LabelFinder.mapLabels(
transformResult.getLabelFinder(), GitHubPrDestination.this.assignees);
ImmutableList<String> prLabels =
LabelFinder.mapLabels(
transformResult.getLabelFinder(), GitHubPrDestination.this.labels);
for (PullRequest pr : pullRequests) {
if (pr.getHead().getRef().equals(prBranch)) {
if (!pr.isOpen()) {
Expand Down Expand Up @@ -300,6 +306,7 @@ public ImmutableList<DestinationEffect> write(
pr.getNumber(),
new UpdatePullRequest(title, prBody, /* state= */ null));
}
addLabelsToPullRequest(api, console, pr, prLabels);
result.add(
new DestinationEffect(
DestinationEffect.Type.UPDATED,
Expand Down Expand Up @@ -334,6 +341,8 @@ public ImmutableList<DestinationEffect> write(
}
}

addLabelsToPullRequest(api, console, pr, prLabels);

state.pullRequestNumber = pr.getNumber();
result.add(
new DestinationEffect(
Expand All @@ -358,6 +367,25 @@ public Endpoint getFeedbackEndPoint(Console console) throws ValidationException
};
}

/**
* Adds labels to a pull request. GitHub's create-PR endpoint does not accept labels, so this is
* a separate call. Adding is idempotent and never removes existing labels. Failure is non-fatal.
*/
private void addLabelsToPullRequest(
GitHubApi api, Console console, PullRequest pr, ImmutableList<String> prLabels)
throws ValidationException {
if (prLabels.isEmpty()) {
return;
}
try {
api.addLabels(getProjectName(), pr.getNumber(), prLabels);
} catch (RepoException e) {
console.warnFmt(
"Could not add all labels (%s) to %s/pull/%s with error '%s'",
prLabels, asHttpsUrl(), pr.getNumber(), e.getMessage());
}
}

@VisibleForTesting
String asHttpsUrl() throws ValidationException {
return ghHost.projectAsUrl(getProjectName());
Expand Down
17 changes: 17 additions & 0 deletions java/com/google/copybara/git/GitModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -2303,6 +2303,21 @@ public GitDestination gitHubDestination(
+ " assignees is 10 and the assignees must be GitHub usernames or a label that"
+ " can be resolved to a GitHub username. For example: `assignees ="
+ " [\"github-repo-owner1\", \"${YOUR_LABEL}\"]`"),
@Param(
name = "labels",
allowedTypes = {
@ParamType(type = Sequence.class, generic1 = String.class),
},
defaultValue = "[]",
named = true,
positional = false,
doc =
"The GitHub labels to add to the pull request, both when creating it and when"
+ " updating an existing one (labels are only ever added, never removed). Each"
+ " entry is a label"
+ " name or a template that can be resolved from the change's labels. For"
+ " example: `labels = [\"autogenerated\", \"${YOUR_LABEL}\"]`. Labels are"
+ " applied in a separate call; failure to apply them is logged as a warning."),
@Param(
name = "integrates",
allowedTypes = {
Expand Down Expand Up @@ -2424,6 +2439,7 @@ public GitHubPrDestination githubPrDestination(
Object title,
Object body,
Sequence<? extends String> assignees,
Sequence<? extends String> labels,
Object integrates,
Object apiChecker,
Boolean updateDescription,
Expand Down Expand Up @@ -2487,6 +2503,7 @@ public GitHubPrDestination githubPrDestination(
convertFromNoneable(title, null),
convertFromNoneable(body, null),
ImmutableList.copyOf(assignees),
ImmutableList.copyOf(labels),
mainConfigFile,
workflowName,
apiCheckerObj != null ? apiCheckerObj : checkerObj,
Expand Down
108 changes: 108 additions & 0 deletions javatests/com/google/copybara/git/GitHubPrDestinationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.matches;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
Expand Down Expand Up @@ -203,6 +204,113 @@ public void testCustomTitleAndBodyAndAssignees()
.buildRequest("POST", "https://api.github.com/repos/foo/issues/12345/assignees");
}

@Test
public void testLabelsAddedAfterCreation() throws Exception {
options.githubDestination.destinationPrBranch = "feature";

mockNoPullRequestsGet("feature");

gitUtil.mockApi(
"POST",
"https://api.github.com/repos/foo/pulls",
mockResponse("{\"id\": 1, \"number\": 12345, \"state\": \"open\"}"));
gitUtil.mockApi(
"POST",
"https://api.github.com/repos/foo/issues/12345/labels",
mockResponseAndValidateRequest(
"[{\"name\": \"autogenerated\"}, {\"name\": \"area-x\"}]",
MockRequestAssertion.equals("{\"labels\":[\"autogenerated\",\"area-x\"]}")));

GitHubPrDestination d =
skylark.eval(
"r",
"""
r = git.github_pr_destination(
url = 'https://github.com/foo',
destination_ref = 'main',
labels = ['autogenerated', '${AREA}']
)
""");
WriterContext writerContext =
new WriterContext(
"piper_to_github",
"TEST",
false,
new DummyRevision("feature", "feature"),
Glob.ALL_FILES.roots());
Writer<GitRevision> writer = d.newWriter(writerContext);
GitRepository remote = gitUtil.mockRemoteRepo("github.com/foo");
addFiles(
remote,
null,
"first change",
ImmutableMap.<String, String>builder().put("foo.txt", "").buildOrThrow());

writeFile(this.workdir, "test.txt", "some content");
writer.write(
TransformResults.of(this.workdir, new DummyRevision("one"))
.withLabelFinder(Functions.forMap(ImmutableMap.of("AREA", ImmutableList.of("area-x")))),
Glob.ALL_FILES,
console);

verify(gitUtil.httpTransport(), times(1))
.buildRequest("POST", "https://api.github.com/repos/foo/pulls");
verify(gitUtil.httpTransport(), times(1))
.buildRequest("POST", "https://api.github.com/repos/foo/issues/12345/labels");
}

@Test
public void testLabelsAddedToExistingPullRequest() throws Exception {
options.githubDestination.destinationPrBranch = "feature";

gitUtil.mockApi(
"GET",
getPullRequestsUrl("feature"),
mockResponse(
"[{\"id\": 1, \"number\": 12345, \"state\": \"open\","
+ " \"head\": {\"ref\": \"feature\"}, \"base\": {\"ref\": \"main\"}}]"));
gitUtil.mockApi(
"POST",
"https://api.github.com/repos/foo/issues/12345/labels",
mockResponseAndValidateRequest(
"[{\"name\": \"autogenerated\"}]",
MockRequestAssertion.equals("{\"labels\":[\"autogenerated\"]}")));

GitHubPrDestination d =
skylark.eval(
"r",
"""
r = git.github_pr_destination(
url = 'https://github.com/foo',
destination_ref = 'main',
labels = ['autogenerated']
)
""");
WriterContext writerContext =
new WriterContext(
"piper_to_github",
"TEST",
false,
new DummyRevision("feature", "feature"),
Glob.ALL_FILES.roots());
Writer<GitRevision> writer = d.newWriter(writerContext);
GitRepository remote = gitUtil.mockRemoteRepo("github.com/foo");
addFiles(
remote,
null,
"first change",
ImmutableMap.<String, String>builder().put("foo.txt", "").buildOrThrow());

writeFile(this.workdir, "test.txt", "some content");
writer.write(
TransformResults.of(this.workdir, new DummyRevision("one")), Glob.ALL_FILES, console);

verify(gitUtil.httpTransport(), never())
.buildRequest("POST", "https://api.github.com/repos/foo/pulls");
verify(gitUtil.httpTransport(), times(1))
.buildRequest("POST", "https://api.github.com/repos/foo/issues/12345/labels");
}

@Test
public void testCustomTitleAndBody_withUpdate()
throws ValidationException, IOException, RepoException {
Expand Down