Skip to content

The Unified and Autonomous Development Platform

chore: Refactoring for CI/CD MCP support

Robin Shen5df04de72184
diff --git a/server-core/src/main/java/io/onedev/server/ai/McpHelperResource.java b/server-core/src/main/java/io/onedev/server/ai/McpHelperResource.java
index b483eee766..379ad309c0 100644
--- a/server-core/src/main/java/io/onedev/server/ai/McpHelperResource.java
+++ b/server-core/src/main/java/io/onedev/server/ai/McpHelperResource.java
@@ -1,6 +1,7 @@
package io.onedev.server.ai;
import java.io.Serializable;
+import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -58,8 +59,10 @@ import io.onedev.server.entitymanager.SettingManager;
import io.onedev.server.entitymanager.UserManager;
import io.onedev.server.entityreference.IssueReference;
import io.onedev.server.entityreference.PullRequestReference;
-import io.onedev.server.exception.LinkValidationException;
-import io.onedev.server.exception.ReviewRejectException;
+import io.onedev.server.exception.InvalidIssueFieldsException;
+import io.onedev.server.exception.InvalidReferenceException;
+import io.onedev.server.exception.IssueLinkValidationException;
+import io.onedev.server.exception.PullRequestReviewRejectedException;
import io.onedev.server.git.service.GitService;
import io.onedev.server.model.Issue;
import io.onedev.server.model.IssueComment;
@@ -75,7 +78,6 @@ import io.onedev.server.model.PullRequestComment;
import io.onedev.server.model.PullRequestReview;
import io.onedev.server.model.PullRequestUpdate;
import io.onedev.server.model.User;
-import io.onedev.server.model.support.issue.field.EmptyFieldsException;
import io.onedev.server.model.support.issue.field.FieldUtils;
import io.onedev.server.model.support.issue.field.spec.BooleanField;
import io.onedev.server.model.support.issue.field.spec.DateField;
@@ -91,7 +93,6 @@ import io.onedev.server.model.support.pullrequest.AutoMerge;
import io.onedev.server.model.support.pullrequest.MergeStrategy;
import io.onedev.server.model.support.pullrequest.changedata.PullRequestApproveData;
import io.onedev.server.model.support.pullrequest.changedata.PullRequestRequestedForChangesData;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.resource.support.RestConstants;
import io.onedev.server.search.entity.EntityQuery;
@@ -392,6 +393,18 @@ public class McpHelperResource {
return project;
}
+ private ProjectInfo getProjectInfo(String projectPath, String currentProjectPath) {
+ projectPath = StringUtils.trimToNull(projectPath);
+ if (projectPath == null)
+ projectPath = currentProjectPath;
+
+ var projectInfo = new ProjectInfo();
+ projectInfo.project = getProject(projectPath);
+ projectInfo.currentProject = getProject(currentProjectPath);
+
+ return projectInfo;
+ }
+
private Map<String, Object> getFieldProperties(FieldSpec field) {
String fieldDescription;
if (field.getDescription() != null)
@@ -449,379 +462,298 @@ public class McpHelperResource {
@Path("/get-tool-input-schemas")
@GET
- public Map<String, Object> getToolInputSchemas(@QueryParam("currentProject") @NotNull String currentProjectPath) {
+ public Map<String, Object> getToolInputSchemas() {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
- var currentProject = getProject(currentProjectPath);
-
- Project.push(currentProject);
- try {
- var inputSchemas = new HashMap<String, Object>();
-
- var queryIssuesInputSchema = new HashMap<String, Object>();
- var queryIssuesProperties = new HashMap<String, Object>();
-
- queryIssuesProperties.put("query", Map.of(
- "type", "string",
- "description", getIssueQueryStringDescription()));
- queryIssuesProperties.put("offset", Map.of(
+ var inputSchemas = new HashMap<String, Object>();
+
+ var queryIssuesInputSchema = new HashMap<String, Object>();
+ var queryIssuesProperties = new HashMap<String, Object>();
+
+ queryIssuesProperties.put("project", Map.of(
+ "type", "string",
+ "description", "Project to query issues in. Leave empty to query in current project"));
+ queryIssuesProperties.put("query", Map.of(
+ "type", "string",
+ "description", getIssueQueryStringDescription()));
+ queryIssuesProperties.put("offset", Map.of(
+ "type", "integer",
+ "description", "start position for the query (optional, defaults to 0)"));
+ queryIssuesProperties.put("count", Map.of(
+ "type", "integer",
+ "description", "number of issues to return (optional, defaults to 25, max 100)"));
+
+ queryIssuesInputSchema.put("Type", "object");
+ queryIssuesInputSchema.put("Properties", queryIssuesProperties);
+ queryIssuesInputSchema.put("Required", new ArrayList<>());
+
+ inputSchemas.put("queryIssues", queryIssuesInputSchema);
+
+ var createIssueInputSchema = new HashMap<String, Object>();
+ var createIssueProperties = new HashMap<String, Object>();
+ createIssueProperties.put("project", Map.of(
+ "type", "string",
+ "description", "Project to create issue in. Leave empty to create issue in current project"));
+ createIssueProperties.put("title", Map.of(
+ "type", "string",
+ "description", "title of the issue"));
+ createIssueProperties.put("description", Map.of(
+ "type", "string",
+ "description", "description of the issue"));
+ createIssueProperties.put("confidential", Map.of(
+ "type", "boolean",
+ "description", "whether the issue is confidential"));
+
+ createIssueProperties.put("iterations", getArrayProperties("iteration names"));
+
+ if (subscriptionManager.isSubscriptionActive()) {
+ createIssueProperties.put("ownEstimatedTime", Map.of(
"type", "integer",
- "description", "start position for the query (optional, defaults to 0)"));
- queryIssuesProperties.put("count", Map.of(
- "type", "integer",
- "description", "number of issues to return (optional, defaults to 25, max 100)"));
-
- queryIssuesInputSchema.put("Type", "object");
- queryIssuesInputSchema.put("Properties", queryIssuesProperties);
- queryIssuesInputSchema.put("Required", new ArrayList<>());
-
- inputSchemas.put("queryIssues", queryIssuesInputSchema);
+ "description", "Estimated time in hours for this issue only (not including linked issues)"));
+ }
- var createIssueInputSchema = new HashMap<String, Object>();
- var createIssueProperties = new HashMap<String, Object>();
- createIssueProperties.put("title", Map.of(
- "type", "string",
+ for (var field: settingManager.getIssueSetting().getFieldSpecs()) {
+ var paramName = getToolParamName(field.getName());
+ var fieldProperties = getFieldProperties(field);
+ createIssueProperties.put(paramName, fieldProperties);
+ }
+
+ createIssueInputSchema.put("Type", "object");
+ createIssueInputSchema.put("Properties", createIssueProperties);
+ createIssueInputSchema.put("Required", List.of("title"));
+
+ inputSchemas.put("createIssue", createIssueInputSchema);
+
+ var editIssueInputSchema = new HashMap<String, Object>();
+ var editIssueProperties = new HashMap<String, Object>();
+ editIssueProperties.put("issueReference", Map.of(
+ "type", "string",
+ "description", "reference of the issue to update"));
+ editIssueProperties.put("title", Map.of(
+ "type", "string",
"description", "title of the issue"));
- createIssueProperties.put("description", Map.of(
- "type", "string",
+ editIssueProperties.put("description", Map.of(
+ "type", "string",
"description", "description of the issue"));
- createIssueProperties.put("confidential", Map.of(
- "type", "boolean",
+ editIssueProperties.put("confidential", Map.of(
+ "type", "boolean",
"description", "whether the issue is confidential"));
- if (SecurityUtils.canScheduleIssues(currentProject)) {
- createIssueProperties.put("iterations", getArrayProperties("iteration names"));
+ editIssueProperties.put("iterations", getArrayProperties("iterations to schedule the issue in"));
- if (subscriptionManager.isSubscriptionActive() && currentProject.isTimeTracking()) {
- createIssueProperties.put("ownEstimatedTime", Map.of(
- "type", "integer",
- "description", "Estimated time in hours for this issue only (not including linked issues)"));
- }
- }
+ if (subscriptionManager.isSubscriptionActive()) {
+ editIssueProperties.put("ownEstimatedTime", Map.of(
+ "type", "integer",
+ "description", "Estimated time in hours for this issue only (not including linked issues)"));
+ }
+
+ for (var field : settingManager.getIssueSetting().getFieldSpecs()) {
+ var paramName = getToolParamName(field.getName());
+
+ var fieldProperties = getFieldProperties(field);
+ editIssueProperties.put(paramName, fieldProperties);
+ }
- var createIssueRequiredProperties = new ArrayList<String>();
- createIssueRequiredProperties.add("title");
+ editIssueInputSchema.put("Type", "object");
+ editIssueInputSchema.put("Properties", editIssueProperties);
+ editIssueInputSchema.put("Required", List.of("issueReference"));
- for (var field: settingManager.getIssueSetting().getFieldSpecs()) {
- if (field.isApplicable(currentProject)
- && field.isPromptUponIssueOpen()
- && SecurityUtils.canEditIssueField(currentProject, field.getName())) {
- var paramName = getToolParamName(field.getName());
- var fieldProperties = getFieldProperties(field);
- createIssueProperties.put(paramName, fieldProperties);
+ inputSchemas.put("editIssue", editIssueInputSchema);
- if (!field.isAllowEmpty() && field.getShowCondition() == null) {
- createIssueRequiredProperties.add(paramName);
- }
+ var toStates = new HashSet<String>();
+ for (var transition: settingManager.getIssueSetting().getTransitionSpecs()) {
+ if (transition instanceof ManualSpec) {
+ if (transition.getToStates().isEmpty()) {
+ toStates.addAll(settingManager.getIssueSetting().getStateSpecMap().keySet());
+ break;
+ } else {
+ toStates.addAll(transition.getToStates());
}
}
-
- createIssueInputSchema.put("Type", "object");
- createIssueInputSchema.put("Properties", createIssueProperties);
- createIssueInputSchema.put("Required", createIssueRequiredProperties);
-
- inputSchemas.put("createIssue", createIssueInputSchema);
+ }
+ if (toStates.size() > 0) {
+ var transitionInputSchema = new HashMap<String, Object>();
+ transitionInputSchema.put("Type", "object");
- var editIssueInputSchema = new HashMap<String, Object>();
- var editIssueProperties = new HashMap<String, Object>();
- editIssueProperties.put("issueReference", Map.of(
+ var transitIssueProperties = new HashMap<String, Object>();
+ transitIssueProperties.put("issueReference", Map.of(
"type", "string",
- "description", "reference of the issue to update"));
- editIssueProperties.put("title", Map.of(
+ "description", "reference of the issue to transit state"));
+ transitIssueProperties.put("state", Map.of(
"type", "string",
- "description", "title of the issue"));
- editIssueProperties.put("description", Map.of(
+ "description", "new state of the issue after transition. Must be one of: " + String.join(", ", toStates)));
+ transitIssueProperties.put("comment", Map.of(
"type", "string",
- "description", "description of the issue"));
- editIssueProperties.put("confidential", Map.of(
- "type", "boolean",
- "description", "whether the issue is confidential"));
-
- if (SecurityUtils.canScheduleIssues(currentProject)) {
- editIssueProperties.put("iterations", getArrayProperties("iterations to schedule the issue in"));
-
- if (subscriptionManager.isSubscriptionActive() && currentProject.isTimeTracking()) {
- editIssueProperties.put("ownEstimatedTime", Map.of(
- "type", "integer",
- "description", "Estimated time in hours for this issue only (not including linked issues)"));
- }
- }
+ "description", "comment of the transition"));
for (var field : settingManager.getIssueSetting().getFieldSpecs()) {
- if (SecurityUtils.canEditIssueField(currentProject, field.getName())) {
- var paramName = getToolParamName(field.getName());
-
- var fieldProperties = getFieldProperties(field);
- editIssueProperties.put(paramName, fieldProperties);
- }
- }
-
- editIssueInputSchema.put("Type", "object");
- editIssueInputSchema.put("Properties", editIssueProperties);
- editIssueInputSchema.put("Required", List.of("issueReference"));
-
- inputSchemas.put("editIssue", editIssueInputSchema);
-
- var toStates = new HashSet<String>();
- for (var transition: settingManager.getIssueSetting().getTransitionSpecs()) {
- if (transition instanceof ManualSpec) {
- if (transition.getToStates().isEmpty()) {
- toStates.addAll(settingManager.getIssueSetting().getStateSpecMap().keySet());
- break;
- } else {
- toStates.addAll(transition.getToStates());
- }
- }
- }
- if (toStates.size() > 0) {
- var transitionInputSchema = new HashMap<String, Object>();
- transitionInputSchema.put("Type", "object");
-
- var transitIssueProperties = new HashMap<String, Object>();
- transitIssueProperties.put("issueReference", Map.of(
- "type", "string",
- "description", "reference of the issue to transit state"));
- transitIssueProperties.put("state", Map.of(
- "type", "string",
- "description", "new state of the issue after transition. Must be one of: " + String.join(", ", toStates)));
- transitIssueProperties.put("comment", Map.of(
- "type", "string",
- "description", "comment of the transition"));
-
- for (var field : settingManager.getIssueSetting().getFieldSpecs()) {
- if (SecurityUtils.canEditIssueField(currentProject, field.getName())) {
- var paramName = getToolParamName(field.getName());
-
- var fieldProperties = getFieldProperties(field);
- transitIssueProperties.put(paramName, fieldProperties);
- }
- }
-
- transitionInputSchema.put("Properties", transitIssueProperties);
- transitionInputSchema.put("Required", List.of("issueReference", "state"));
+ var paramName = getToolParamName(field.getName());
- inputSchemas.put("transitIssue", transitionInputSchema);
- }
-
- var linkSpecs = linkSpecManager.query();
- if (!linkSpecs.isEmpty()) {
- var linkInputSchema = new HashMap<String, Object>();
- linkInputSchema.put("Type", "object");
-
- var linkProperties = new HashMap<String, Object>();
- linkProperties.put("sourceIssueReference", Map.of(
- "type", "string",
- "description", "Issue reference as source of the link"));
- linkProperties.put("targetIssueReference", Map.of(
- "type", "string",
- "description", "Issue reference as target of the link"
- ));
- var linkNames = new ArrayList<String>();
- for (var linkSpec: linkSpecs) {
- linkNames.add(linkSpec.getName());
- if (linkSpec.getOpposite() != null)
- linkNames.add(linkSpec.getOpposite().getName());
- }
- linkProperties.put("linkName", Map.of(
- "type", "string",
- "description", "Name of the link. Must be one of: " + String.join(", ", linkNames)));
- linkInputSchema.put("Properties", linkProperties);
- linkInputSchema.put("Required", List.of("sourceIssueReference", "targetIssueReference", "linkName"));
+ var fieldProperties = getFieldProperties(field);
+ transitIssueProperties.put(paramName, fieldProperties);
+ }
- inputSchemas.put("linkIssues", linkInputSchema);
- }
+ transitionInputSchema.put("Properties", transitIssueProperties);
+ transitionInputSchema.put("Required", List.of("issueReference", "state"));
- var queryPullRequestsInputSchema = new HashMap<String, Object>();
- var queryPullRequestsProperties = new HashMap<String, Object>();
-
- queryPullRequestsProperties.put("query", Map.of(
- "type", "string",
- "description", getPullRequestQueryStringDescription()));
- queryPullRequestsProperties.put("offset", Map.of(
- "type", "integer",
- "description", "start position for the query (optional, defaults to 0)"));
- queryPullRequestsProperties.put("count", Map.of(
- "type", "integer",
- "description", "number of pull requests to return (optional, defaults to 25, max 100)"));
-
- queryPullRequestsInputSchema.put("Type", "object");
- queryPullRequestsInputSchema.put("Properties", queryPullRequestsProperties);
- queryPullRequestsInputSchema.put("Required", new ArrayList<>());
+ inputSchemas.put("transitIssue", transitionInputSchema);
+ }
- inputSchemas.put("queryPullRequests", queryPullRequestsInputSchema);
+ var linkSpecs = linkSpecManager.query();
+ if (!linkSpecs.isEmpty()) {
+ var linkInputSchema = new HashMap<String, Object>();
+ linkInputSchema.put("Type", "object");
- var createPullRequestInputSchema = new HashMap<String, Object>();
- var createPullRequestProperties = new HashMap<String, Object>();
- createPullRequestProperties.put("title", Map.of(
- "type", "string",
- "description", "Title of the pull request"));
- createPullRequestProperties.put("description", Map.of(
- "type", "string",
- "description", "Description of the pull request"));
- createPullRequestProperties.put("targetBranch", Map.of(
- "type", "string",
- "description", "A branch in current project to be used as target branch of the pull request"));
- createPullRequestProperties.put("sourceBranch", Map.of(
- "type", "string",
- "description", "A branch in current project to be used as source branch of the pull request"));
- createPullRequestProperties.put("mergeStrategy", Map.of(
- "type", "string",
- "description", "Merge strategy of the pull request. Must be one of: " +
- Arrays.stream(MergeStrategy.values()).map(Enum::name).collect(Collectors.joining(", "))));
- createPullRequestProperties.put("reviewers", Map.of(
- "type", "array",
- "items", Map.of("type", "string"),
- "uniqueItems", true,
- "description", "Reviewers of the pull request. Expects user login names"));
- createPullRequestProperties.put("assignees", Map.of(
- "type", "array",
- "items", Map.of("type", "string"),
- "uniqueItems", true,
- "description", "Assignees of the pull request. Expects user login names"));
-
- var labelSpecs = labelSpecManager.query();
- if (!labelSpecs.isEmpty()) {
- createPullRequestProperties.put("labels", Map.of(
- "type", "array",
- "items", Map.of("type", "string"),
- "uniqueItems", true,
- "description", "Labels of the pull request. Must be one or more of: " + String.join(", ",
- labelSpecs.stream().map(LabelSpec::getName).collect(Collectors.toList()))));
+ var linkProperties = new HashMap<String, Object>();
+ linkProperties.put("sourceIssueReference", Map.of(
+ "type", "string",
+ "description", "Issue reference as source of the link"));
+ linkProperties.put("targetIssueReference", Map.of(
+ "type", "string",
+ "description", "Issue reference as target of the link"
+ ));
+ var linkNames = new ArrayList<String>();
+ for (var linkSpec: linkSpecs) {
+ linkNames.add(linkSpec.getName());
+ if (linkSpec.getOpposite() != null)
+ linkNames.add(linkSpec.getOpposite().getName());
}
+ linkProperties.put("linkName", Map.of(
+ "type", "string",
+ "description", "Name of the link. Must be one of: " + String.join(", ", linkNames)));
+ linkInputSchema.put("Properties", linkProperties);
+ linkInputSchema.put("Required", List.of("sourceIssueReference", "targetIssueReference", "linkName"));
- createPullRequestInputSchema.put("Type", "object");
- createPullRequestInputSchema.put("Properties", createPullRequestProperties);
- createPullRequestInputSchema.put("Required", List.of("title", "targetBranch", "sourceBranch"));
-
- inputSchemas.put("createPullRequest", createPullRequestInputSchema);
+ inputSchemas.put("linkIssues", linkInputSchema);
+ }
- var editPullRequestInputSchema = new HashMap<String, Object>();
- var editPullRequestProperties = new HashMap<String, Object>();
- editPullRequestProperties.put("pullRequestReference", Map.of(
- "type", "string",
- "description", "Reference of the pull request to edit"));
- editPullRequestProperties.put("title", Map.of(
- "type", "string",
- "description", "Title of the pull request"));
- editPullRequestProperties.put("description", Map.of(
- "type", "string",
- "description", "Description of the pull request"));
- editPullRequestProperties.put("mergeStrategy", Map.of(
- "type", "string",
- "description", "Merge strategy of the pull request. Must be one of: " +
- Arrays.stream(MergeStrategy.values()).map(Enum::name).collect(Collectors.joining(", "))));
- editPullRequestProperties.put("assignees", Map.of(
- "type", "array",
- "items", Map.of("type", "string"),
- "uniqueItems", true,
- "description", "Assignees of the pull request. Expects user login names"));
+ var queryPullRequestsInputSchema = new HashMap<String, Object>();
+ var queryPullRequestsProperties = new HashMap<String, Object>();
- editPullRequestProperties.put("addReviewers", Map.of(
- "type", "array",
- "items", Map.of("type", "string"),
- "uniqueItems", true,
- "description", "Request review from specified users. Expects user login names"));
- editPullRequestProperties.put("removeReviewers", Map.of(
- "type", "array",
- "items", Map.of("type", "string"),
- "uniqueItems", true,
- "description", "Remove specified reviewers. Expects user login names"));
-
- if (!labelSpecs.isEmpty()) {
- editPullRequestProperties.put("labels", Map.of(
+ queryPullRequestsProperties.put("project", Map.of(
+ "type", "string",
+ "description", "Project to query pull requests in. Leave empty to query in current project"));
+ queryPullRequestsProperties.put("query", Map.of(
+ "type", "string",
+ "description", getPullRequestQueryStringDescription()));
+ queryPullRequestsProperties.put("offset", Map.of(
+ "type", "integer",
+ "description", "start position for the query (optional, defaults to 0)"));
+ queryPullRequestsProperties.put("count", Map.of(
+ "type", "integer",
+ "description", "number of pull requests to return (optional, defaults to 25, max 100)"));
+
+ queryPullRequestsInputSchema.put("Type", "object");
+ queryPullRequestsInputSchema.put("Properties", queryPullRequestsProperties);
+ queryPullRequestsInputSchema.put("Required", new ArrayList<>());
+
+ inputSchemas.put("queryPullRequests", queryPullRequestsInputSchema);
+
+ var createPullRequestInputSchema = new HashMap<String, Object>();
+ var createPullRequestProperties = new HashMap<String, Object>();
+ createPullRequestProperties.put("targetProject", Map.of(
+ "type", "string",
+ "description", "Target project of the pull request. If left empty, it defaults to the original project when the source project is a fork, or to the source project itself otherwise"));
+ createPullRequestProperties.put("sourceProject", Map.of(
+ "type", "string",
+ "description", "Source project of the pull request. Leave empty to use current project"));
+ createPullRequestProperties.put("title", Map.of(
+ "type", "string",
+ "description", "Title of the pull request. Leave empty to use default title"));
+ createPullRequestProperties.put("description", Map.of(
+ "type", "string",
+ "description", "Description of the pull request"));
+ createPullRequestProperties.put("targetBranch", Map.of(
+ "type", "string",
+ "description", "A branch in target project to be used as target branch of the pull request. Leave empty to use default branch"));
+ createPullRequestProperties.put("sourceBranch", Map.of(
+ "type", "string",
+ "description", "A branch in source project to be used as source branch of the pull request"));
+ createPullRequestProperties.put("mergeStrategy", Map.of(
+ "type", "string",
+ "description", "Merge strategy of the pull request. Must be one of: " +
+ Arrays.stream(MergeStrategy.values()).map(Enum::name).collect(Collectors.joining(", "))));
+ createPullRequestProperties.put("reviewers", Map.of(
+ "type", "array",
+ "items", Map.of("type", "string"),
+ "uniqueItems", true,
+ "description", "Reviewers of the pull request. Expects user login names"));
+ createPullRequestProperties.put("assignees", Map.of(
+ "type", "array",
+ "items", Map.of("type", "string"),
+ "uniqueItems", true,
+ "description", "Assignees of the pull request. Expects user login names"));
+
+ var labelSpecs = labelSpecManager.query();
+ if (!labelSpecs.isEmpty()) {
+ createPullRequestProperties.put("labels", Map.of(
"type", "array",
"items", Map.of("type", "string"),
"uniqueItems", true,
- "description", "Labels of the pull request. Must be one or more of: " + String.join(", ", labelSpecs.stream().map(LabelSpec::getName).collect(Collectors.toList()))));
- }
-
- editPullRequestProperties.put("autoMerge", Map.of(
- "type", "boolean",
- "description", "Whether to enable auto merge"));
- editPullRequestProperties.put("autoMergeCommitMessage", Map.of(
- "type", "string",
- "description", "Preset commit message for auto merge"));
+ "description", "Labels of the pull request. Must be one or more of: " + String.join(", ",
+ labelSpecs.stream().map(LabelSpec::getName).collect(Collectors.toList()))));
+ }
- editPullRequestInputSchema.put("Type", "object");
- editPullRequestInputSchema.put("Properties", editPullRequestProperties);
- editPullRequestInputSchema.put("Required", List.of("pullRequestReference"));
+ createPullRequestInputSchema.put("Type", "object");
+ createPullRequestInputSchema.put("Properties", createPullRequestProperties);
+ createPullRequestInputSchema.put("Required", List.of("sourceBranch"));
- inputSchemas.put("editPullRequest", editPullRequestInputSchema);
+ inputSchemas.put("createPullRequest", createPullRequestInputSchema);
- return inputSchemas;
- } finally {
- Project.pop();
+ var editPullRequestInputSchema = new HashMap<String, Object>();
+ var editPullRequestProperties = new HashMap<String, Object>();
+ editPullRequestProperties.put("pullRequestReference", Map.of(
+ "type", "string",
+ "description", "Reference of the pull request to edit"));
+ editPullRequestProperties.put("title", Map.of(
+ "type", "string",
+ "description", "Title of the pull request"));
+ editPullRequestProperties.put("description", Map.of(
+ "type", "string",
+ "description", "Description of the pull request"));
+ editPullRequestProperties.put("mergeStrategy", Map.of(
+ "type", "string",
+ "description", "Merge strategy of the pull request. Must be one of: " +
+ Arrays.stream(MergeStrategy.values()).map(Enum::name).collect(Collectors.joining(", "))));
+ editPullRequestProperties.put("assignees", Map.of(
+ "type", "array",
+ "items", Map.of("type", "string"),
+ "uniqueItems", true,
+ "description", "Assignees of the pull request. Expects user login names"));
+
+ editPullRequestProperties.put("addReviewers", Map.of(
+ "type", "array",
+ "items", Map.of("type", "string"),
+ "uniqueItems", true,
+ "description", "Request review from specified users. Expects user login names"));
+ editPullRequestProperties.put("removeReviewers", Map.of(
+ "type", "array",
+ "items", Map.of("type", "string"),
+ "uniqueItems", true,
+ "description", "Remove specified reviewers. Expects user login names"));
+
+ if (!labelSpecs.isEmpty()) {
+ editPullRequestProperties.put("labels", Map.of(
+ "type", "array",
+ "items", Map.of("type", "string"),
+ "uniqueItems", true,
+ "description", "Labels of the pull request. Must be one or more of: " + String.join(", ", labelSpecs.stream().map(LabelSpec::getName).collect(Collectors.toList()))));
}
- }
-
- @Path("/get-prompt-arguments")
- @GET
- public Map<String, Object> getPromptArguments(@QueryParam("currentProject") @NotNull String currentProjectPath) {
- if (SecurityUtils.getAuthUser() == null)
- throw new UnauthenticatedException();
- var currentProject = getProject(currentProjectPath);
+ editPullRequestProperties.put("autoMerge", Map.of(
+ "type", "boolean",
+ "description", "Whether to enable auto merge"));
+ editPullRequestProperties.put("autoMergeCommitMessage", Map.of(
+ "type", "string",
+ "description", "Preset commit message for auto merge"));
- Project.push(currentProject);
- try {
- var arguments = new LinkedHashMap<String, Object>();
- var createIssueArguments = new ArrayList<Map<String, Object>>();
- createIssueArguments.add(Map.of(
- "name", "title",
- "description", "title of the issue",
- "required", true));
- createIssueArguments.add(Map.of(
- "name", "description",
- "description", "description of the issue",
- "required", false));
- createIssueArguments.add(Map.of(
- "name", "confidential",
- "description", "whether the issue is confidential",
- "required", false));
-
- if (SecurityUtils.canScheduleIssues(currentProject)) {
- createIssueArguments.add(Map.of(
- "name", "iterations",
- "description", "iterations to schedule the issue in",
- "required", false));
-
- if (subscriptionManager.isSubscriptionActive() && currentProject.isTimeTracking()) {
- createIssueArguments.add(Map.of(
- "name", "ownEstimatedTime",
- "description", "estimated time for this issue only in hours (excluding linked issues)",
- "required", false));
- }
- }
+ editPullRequestInputSchema.put("Type", "object");
+ editPullRequestInputSchema.put("Properties", editPullRequestProperties);
+ editPullRequestInputSchema.put("Required", List.of("pullRequestReference"));
- for (var field: settingManager.getIssueSetting().getFieldSpecs()) {
- if (field.isApplicable(currentProject)
- && field.isPromptUponIssueOpen()
- && field.getShowCondition() == null
- && SecurityUtils.canEditIssueField(currentProject, field.getName())) {
- var paramName = getToolParamName(field.getName());
- String description = "";
- if (field.getDescription() != null)
- description = field.getDescription().replace("\n", " ");
- if (field instanceof ChoiceField) {
- var choiceField = (ChoiceField) field;
- if (field.isAllowMultiple())
- description = appendDescription(description, "Expects one or more of: " + String.join(", ", choiceField.getPossibleValues()));
- else
- description = appendDescription(description, "Expects one of: " + String.join(", ", choiceField.getPossibleValues()));
- }
- var argumentMap = new HashMap<String, Object>();
- argumentMap.put("name", paramName);
- argumentMap.put("required", !field.isAllowEmpty());
- argumentMap.put("description", HtmlEscape.escapeHtml5(description));
- createIssueArguments.add(argumentMap);
- }
- }
+ inputSchemas.put("editPullRequest", editPullRequestInputSchema);
- arguments.put("createIssue", createIssueArguments);
- return arguments;
- } finally {
- Project.pop();
- }
+ return inputSchemas;
}
@Path("/get-login-name")
@@ -849,7 +781,7 @@ public class McpHelperResource {
if (matchingUsers.size() == 1) {
user = matchingUsers.get(0);
} else if (matchingUsers.size() > 1) {
- throw new InvalidParamsException("Multiple users found: " + userName);
+ throw new NotAcceptableException("Multiple users found: " + userName);
}
}
if (user == null)
@@ -871,28 +803,33 @@ public class McpHelperResource {
@Path("/query-issues")
@GET
- public List<Map<String, Object>> queryIssues(@QueryParam("currentProject") @NotNull String currentProjectPath,
- @QueryParam("query") String query, @QueryParam("offset") int offset, @QueryParam("count") int count) {
+ public List<Map<String, Object>> queryIssues(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("project") String projectPath,
+ @QueryParam("query") String query,
+ @QueryParam("offset") int offset,
+ @QueryParam("count") int count) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
+ var projectInfo = getProjectInfo(projectPath, currentProjectPath);
+
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
- var currentProject = getProject(currentProjectPath);
EntityQuery<Issue> parsedQuery;
if (query != null) {
var option = new IssueQueryParseOption();
option.withCurrentUserCriteria(true);
- parsedQuery = IssueQuery.parse(currentProject, query, option, true);
+ parsedQuery = IssueQuery.parse(projectInfo.project, query, option, true);
} else {
parsedQuery = new IssueQuery();
}
var issues = new ArrayList<Map<String, Object>>();
- for (var issue : issueManager.query(new ProjectScope(currentProject, true, false), parsedQuery, true, offset, count)) {
- var issueMap = getIssueMap(currentProject, issue);
+ for (var issue : issueManager.query(new ProjectScope(projectInfo.project, true, false), parsedQuery, true, offset, count)) {
+ var issueMap = getIssueMap(projectInfo.currentProject, issue);
for (var entry: issue.getFieldInputs().entrySet()) {
issueMap.put(entry.getKey(), entry.getValue().getValues());
}
@@ -903,7 +840,12 @@ public class McpHelperResource {
}
private Issue getIssue(Project currentProject, String referenceString) {
- var issueReference = IssueReference.of(referenceString, currentProject);
+ IssueReference issueReference;
+ try {
+ issueReference = IssueReference.of(referenceString, currentProject);
+ } catch (InvalidReferenceException e) {
+ throw new NotAcceptableException(e.getMessage());
+ }
var issue = issueManager.find(issueReference.getProject(), issueReference.getNumber());
if (issue != null) {
if (!SecurityUtils.canAccessIssue(issue))
@@ -940,7 +882,8 @@ public class McpHelperResource {
@Path("/get-issue")
@GET
- public Map<String, Object> getIssue(@QueryParam("currentProject") @NotNull String currentProjectPath,
+ public Map<String, Object> getIssue(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
@QueryParam("reference") @NotNull String issueReference) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
@@ -975,12 +918,14 @@ public class McpHelperResource {
@Path("/get-issue-comments")
@GET
- public List<Map<String, Object>> getIssueComments(@QueryParam("currentProject") @NotNull String currentProjectPath,
+ public List<Map<String, Object>> getIssueComments(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
@QueryParam("reference") @NotNull String issueReference) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
var currentProject = getProject(currentProjectPath);
+
var issue = getIssue(currentProject, issueReference);
var comments = new ArrayList<Map<String, Object>>();
@@ -997,8 +942,10 @@ public class McpHelperResource {
@Path("/add-issue-comment")
@Consumes(MediaType.TEXT_PLAIN)
@POST
- public String addIssueComment(@QueryParam("currentProject") String currentProjectPath,
- @QueryParam("reference") @NotNull String issueReference, @NotNull String commentContent) {
+ public String addIssueComment(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("reference") @NotNull String issueReference,
+ @NotNull String commentContent) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
@@ -1011,17 +958,19 @@ public class McpHelperResource {
comment.setDate(new Date());
issueCommentManager.create(comment);
- return "Commented on issue " + issueReference + ": " + urlManager.urlFor(comment, true);
+ return "Commented on issue " + issueReference;
}
@Path("/create-issue")
@POST
- public String createIssue(@QueryParam("currentProject") @NotNull String currentProjectPath,
+ public String createIssue(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("project") String projectPath,
@NotNull @Valid Map<String, Serializable> data) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
- var currentProject = getProject(currentProjectPath);
+ var projectInfo = getProjectInfo(projectPath, currentProjectPath);
normalizeIssueData(data);
@@ -1030,7 +979,7 @@ public class McpHelperResource {
Issue issue = new Issue();
var title = (String) data.remove("title");
if (title == null)
- throw new InvalidParamsException("title is required");
+ throw new NotAcceptableException("title is required");
issue.setTitle(title);
var description = (String) data.remove("description");
issue.setDescription(description);
@@ -1042,9 +991,9 @@ public class McpHelperResource {
if (ownEstimatedTime != null) {
if (!subscriptionManager.isSubscriptionActive())
throw new NotAcceptableException("An active subscription is required for this feature");
- if (!currentProject.isTimeTracking())
+ if (!projectInfo.project.isTimeTracking())
throw new NotAcceptableException("Time tracking needs to be enabled for the project");
- if (!SecurityUtils.canScheduleIssues(currentProject))
+ if (!SecurityUtils.canScheduleIssues(projectInfo.project))
throw new UnauthorizedException("Issue schedule permission required to set own estimated time");
issue.setOwnEstimatedTime(ownEstimatedTime*60);
}
@@ -1052,10 +1001,10 @@ public class McpHelperResource {
@SuppressWarnings("unchecked")
List<String> iterationNames = (List<String>) data.remove("iterations");
if (iterationNames != null) {
- if (!SecurityUtils.canScheduleIssues(currentProject))
+ if (!SecurityUtils.canScheduleIssues(projectInfo.project))
throw new UnauthorizedException("Issue schedule permission required to set iterations");
for (var iterationName : iterationNames) {
- var iteration = iterationManager.findInHierarchy(currentProject, iterationName);
+ var iteration = iterationManager.findInHierarchy(projectInfo.project, iterationName);
if (iteration == null)
throw new NotFoundException("Iteration '" + iterationName + "' not found");
IssueSchedule schedule = new IssueSchedule();
@@ -1065,7 +1014,7 @@ public class McpHelperResource {
}
}
- issue.setProject(currentProject);
+ issue.setProject(projectInfo.project);
issue.setSubmitDate(new Date());
issue.setSubmitter(SecurityUtils.getAuthUser());
issue.setState(issueSetting.getInitialStateSpec().getName());
@@ -1074,17 +1023,19 @@ public class McpHelperResource {
try {
issueManager.open(issue);
- } catch (EmptyFieldsException e) {
- throw new InvalidParamsException("Missing parameters: " + String.join(", ", e.getEmptyFields()));
+ } catch (InvalidIssueFieldsException e) {
+ throw newNotAcceptableException(e);
}
- return "Created issue " + issue.getReference().toString(currentProject) + ": " + urlManager.urlFor(issue, true);
+ return "Created issue " + issue.getReference().toString(projectInfo.currentProject) + ": " + urlManager.urlFor(issue, true);
}
@Path("/edit-issue")
@POST
- public String editIssue(@QueryParam("currentProject") @NotNull String currentProjectPath,
- @QueryParam("reference") @NotNull String issueReference, @NotNull Map<String, Serializable> data) {
+ public String editIssue(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("reference") @NotNull String issueReference,
+ @NotNull Map<String, Serializable> data) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
@@ -1145,18 +1096,20 @@ public class McpHelperResource {
try {
issueChangeManager.changeFields(issue, FieldUtils.getFieldValues(issue.getProject(), data));
- } catch (EmptyFieldsException e) {
- throw new InvalidParamsException("Missing parameters: " + String.join(", ", e.getEmptyFields()));
+ } catch (InvalidIssueFieldsException e) {
+ throw newNotAcceptableException(e);
}
}
- return "Edited issue " + issueReference + ": " + urlManager.urlFor(issue, true);
+ return "Edited issue " + issueReference;
}
@Path("/transit-issue")
@POST
- public String transitIssue(@QueryParam("currentProject") @NotNull String currentProjectPath,
- @QueryParam("reference") @NotNull String issueReference, @NotNull Map<String, Serializable> data) {
+ public String transitIssue(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("reference") @NotNull String issueReference,
+ @NotNull Map<String, Serializable> data) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
@@ -1166,36 +1119,45 @@ public class McpHelperResource {
normalizeIssueData(data);
var state = (String) data.remove("state");
if (state == null)
- throw new InvalidParamsException("state is required");
+ throw new NotAcceptableException("state is required");
var comment = (String) data.remove("comment");
ManualSpec transition = settingManager.getIssueSetting().getManualSpec(issue, state);
+ if (transition == null) {
+ var message = MessageFormat.format(
+ "No applicable manual transition spec found for current user (issue: {0}, from state: {1}, to state: {2})",
+ issue.getReference().toString(), issue.getState(), state);
+ throw new NotAcceptableException(message);
+ }
var fieldValues = FieldUtils.getFieldValues(issue.getProject(), data);
try {
issueChangeManager.changeState(issue, state, fieldValues, transition.getPromptFields(),
transition.getRemoveFields(), comment);
- } catch (EmptyFieldsException e) {
- throw new InvalidParamsException("Missing parameters: " + String.join(", ", e.getEmptyFields()));
+ } catch (InvalidIssueFieldsException e) {
+ throw newNotAcceptableException(e);
}
- var feedback = "Issue " + issueReference + " transited to state \"" + state + "\": " + urlManager.urlFor(issue, true);
+ var feedback = "Issue " + issueReference + " transited to state \"" + state + "\"";
var stateDescription = settingManager.getIssueSetting().getStateSpec(state).getDescription();
if (stateDescription != null)
- feedback += "\n\n" + stateDescription;
+ feedback += ":\n\n" + stateDescription;
return feedback;
}
@Path("/link-issues")
@GET
- public String linkIssues(@QueryParam("currentProject") @NotNull String currentProjectPath,
- @QueryParam("sourceReference") @NotNull String sourceReference,
- @QueryParam("linkName") @Nullable String linkName,
- @QueryParam("targetReference") @NotNull String targetReference) {
+ public String linkIssues(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("sourceReference") @NotNull String sourceReference,
+ @QueryParam("linkName") @Nullable String linkName,
+ @QueryParam("targetReference") @NotNull String targetReference) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
var currentProject = getProject(currentProjectPath);
+
var sourceIssue = getIssue(currentProject, sourceReference);
var targetIssue = getIssue(currentProject, targetReference);
+
var linkSpec = linkSpecManager.find(linkName);
if (linkSpec == null)
throw new NotFoundException("Link spec not found: " + linkName);
@@ -1215,23 +1177,26 @@ public class McpHelperResource {
}
try {
link.validate();
- } catch (LinkValidationException e) {
+ } catch (IssueLinkValidationException e) {
throw new NotAcceptableException(e.getMessage());
}
issueLinkManager.create(link);
- return "Issue " + targetReference + " added as \"" + linkName + "\" of " + sourceReference + ": " + urlManager.urlFor(sourceIssue, true);
+ return "Issue " + targetReference + " added as \"" + linkName + "\" of " + sourceReference;
}
@Path("/log-work")
@Consumes(MediaType.TEXT_PLAIN)
@POST
- public String logWork(@QueryParam("currentProject") @NotNull String currentProjectPath,
- @QueryParam("reference") @NotNull String issueReference,
- @QueryParam("spentHours") int spentHours, String comment) {
+ public String logWork(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("reference") @NotNull String issueReference,
+ @QueryParam("spentHours") int spentHours, String comment) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
+
var currentProject = getProject(currentProjectPath);
+
var issue = getIssue(currentProject, issueReference);
if (!subscriptionManager.isSubscriptionActive())
@@ -1247,7 +1212,7 @@ public class McpHelperResource {
work.setMinutes(spentHours * 60);
work.setNote(StringUtils.trimToNull(comment));
issueWorkManager.createOrUpdate(work);
- return "Work logged for issue " + issueReference + ": " + urlManager.urlFor(issue, true);
+ return "Work logged for issue " + issueReference;
}
private void normalizeIssueData(Map<String, Serializable> data) {
@@ -1264,10 +1229,18 @@ public class McpHelperResource {
}
}
- private Map<String, Object> getPullRequestMap(Project currentProject, PullRequest pullRequest) {
+ private Map<String, Object> getPullRequestMap(Project currentProject,
+ PullRequest pullRequest, boolean checkMergeConditionIfOpen) {
var typeReference = new TypeReference<LinkedHashMap<String, Object>>() {};
var pullRequestMap = objectMapper.convertValue(pullRequest, typeReference);
pullRequestMap.remove("id");
+ if (pullRequest.isOpen() && checkMergeConditionIfOpen) {
+ var errorMessage = pullRequest.checkMergeCondition();
+ if (errorMessage != null)
+ pullRequestMap.put("status", PullRequest.Status.OPEN.name() + " (" + errorMessage + ")");
+ else
+ pullRequestMap.put("status", PullRequest.Status.OPEN.name() + " (ready to merge)");
+ }
pullRequestMap.remove("uuid");
pullRequestMap.remove("baseCommitHash");
pullRequestMap.remove("buildCommitHash");
@@ -1295,29 +1268,33 @@ public class McpHelperResource {
@Path("/query-pull-requests")
@GET
- public List<Map<String, Object>> queryPullRequests(@QueryParam("currentProject") @NotNull String currentProjectPath,
- @QueryParam("query") String query, @QueryParam("offset") int offset, @QueryParam("count") int count) {
+ public List<Map<String, Object>> queryPullRequests(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("project") String projectPath,
+ @QueryParam("query") String query,
+ @QueryParam("offset") int offset,
+ @QueryParam("count") int count) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
- if (!SecurityUtils.canReadCode(getProject(currentProjectPath)))
+ var projectInfo = getProjectInfo(projectPath, currentProjectPath);
+
+ if (!SecurityUtils.canReadCode(projectInfo.project))
throw new UnauthorizedException("Code read permission required to query pull requests");
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
-
- var currentProject = getProject(currentProjectPath);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
EntityQuery<PullRequest> parsedQuery;
if (query != null) {
- parsedQuery = PullRequestQuery.parse(currentProject, query, true);
+ parsedQuery = PullRequestQuery.parse(projectInfo.project, query, true);
} else {
parsedQuery = new PullRequestQuery();
}
var pullRequests = new ArrayList<Map<String, Object>>();
- for (var pullRequest : pullRequestManager.query(currentProject, parsedQuery, false, offset, count)) {
- var pullRequestMap = getPullRequestMap(currentProject, pullRequest);
+ for (var pullRequest : pullRequestManager.query(projectInfo.project, parsedQuery, false, offset, count)) {
+ var pullRequestMap = getPullRequestMap(projectInfo.currentProject, pullRequest, false);
pullRequestMap.put("link", urlManager.urlFor(pullRequest, true));
pullRequests.add(pullRequestMap);
}
@@ -1326,15 +1303,18 @@ public class McpHelperResource {
@Path("/get-pull-request")
@GET
- public Map<String, Object> getPullRequest(@QueryParam("currentProject") @NotNull String currentProjectPath,
+ public Map<String, Object> getPullRequest(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
@QueryParam("reference") @NotNull String pullRequestReference) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
var currentProject = getProject(currentProjectPath);
+
var pullRequest = getPullRequest(currentProject, pullRequestReference);
- var pullRequestMap = getPullRequestMap(currentProject, pullRequest);
+ var pullRequestMap = getPullRequestMap(currentProject, pullRequest, true);
+ pullRequestMap.put("headCommitHash", pullRequest.getLatestUpdate().getHeadCommitHash());
pullRequestMap.put("assignees", pullRequest.getAssignees().stream().map(it->it.getName()).collect(Collectors.toList()));
var reviews = new ArrayList<Map<String, Object>>();
for (var review : pullRequest.getReviews()) {
@@ -1344,7 +1324,7 @@ public class McpHelperResource {
reviewMap.put("reviewer", review.getUser().getName());
reviewMap.put("status", review.getStatus());
reviews.add(reviewMap);
- }
+ }
pullRequestMap.put("reviews", reviews);
pullRequestMap.put("labels", pullRequest.getLabels().stream().map(it->it.getSpec().getName()).collect(Collectors.toList()));
pullRequestMap.put("link", urlManager.urlFor(pullRequest, true));
@@ -1354,7 +1334,8 @@ public class McpHelperResource {
@Path("/get-pull-request-comments")
@GET
- public List<Map<String, Object>> getPullRequestComments(@QueryParam("currentProject") @NotNull String currentProjectPath,
+ public List<Map<String, Object>> getPullRequestComments(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
@QueryParam("reference") @NotNull String pullRequestReference) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
@@ -1375,12 +1356,14 @@ public class McpHelperResource {
@Path("/get-pull-request-code-comments")
@GET
- public List<Map<String, Object>> getPullRequestCodeComments(@QueryParam("currentProject") @NotNull String currentProjectPath,
+ public List<Map<String, Object>> getPullRequestCodeComments(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
@QueryParam("reference") @NotNull String pullRequestReference) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
var currentProject = getProject(currentProjectPath);
+
var pullRequest = getPullRequest(currentProject, pullRequestReference);
var comments = new ArrayList<Map<String, Object>>();
@@ -1398,35 +1381,6 @@ public class McpHelperResource {
return comments;
}
- @Path("/get-pull-request-checkout-instruction")
- @GET
- @Produces(MediaType.TEXT_PLAIN)
- public String getPullRequestCheckoutInstruction(
- @QueryParam("currentProject") @NotNull String currentProjectPath,
- @QueryParam("reference") @NotNull String pullRequestReference) {
- var user = SecurityUtils.getAuthUser();
- if (user == null)
- throw new UnauthenticatedException();
- var currentProject = getProject(currentProjectPath);
- var pullRequest = getPullRequest(currentProject, pullRequestReference);
- String localBranch;
- String remoteBranch;
- if (currentProject.equals(pullRequest.getSourceProject()) && pullRequest.isOpen()) {
- localBranch = pullRequest.getSourceBranch();
- remoteBranch = pullRequest.getSourceBranch();
- } else {
- localBranch = "pr-" + pullRequest.getNumber();
- remoteBranch = null;
- }
-
- var checkoutInstruction = new StringBuilder();
- checkoutInstruction.append("1. Fetch commit " + pullRequest.getLatestUpdate().getHeadCommitHash() + "\n");
- checkoutInstruction.append("2. If local branch " + localBranch + " does not exist, create it off above commit; otherwise fastforward it to above commit\n");
- if (remoteBranch != null)
- checkoutInstruction.append("3. Set up above local branch to track remote branch " + remoteBranch + ". Make sure the remote tracking branch is reset to above commit\n");
- return checkoutInstruction.toString();
- }
-
@Path("/get-pull-request-patch-info")
@GET
public Map<String, String> getPullRequestPatchInfo(
@@ -1436,8 +1390,11 @@ public class McpHelperResource {
var user = SecurityUtils.getAuthUser();
if (user == null)
throw new UnauthenticatedException();
+
var currentProject = getProject(currentProjectPath);
+
var pullRequest = getPullRequest(currentProject, pullRequestReference);
+
var oldCommitHash = pullRequest.getBaseCommitHash();
if (sinceLastReview) {
Date sinceDate = null;
@@ -1466,7 +1423,7 @@ public class McpHelperResource {
pullRequest, ObjectId.fromString(oldCommitHash), ObjectId.fromString(newCommitHash));
var patchInfo = new HashMap<String, String>();
- patchInfo.put("projectId", currentProject.getId().toString());
+ patchInfo.put("projectId", pullRequest.getProject().getId().toString());
patchInfo.put("oldCommitHash", comparisonBase.name());
patchInfo.put("newCommitHash", newCommitHash);
return patchInfo;
@@ -1474,35 +1431,63 @@ public class McpHelperResource {
@Path("/create-pull-request")
@POST
- public String createPullRequest(@QueryParam("currentProject") @NotNull String currentProjectPath,
+ public String createPullRequest(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("targetProject") String targetProjectPath,
+ @QueryParam("sourceProject") String sourceProjectPath,
@NotNull Map<String, Serializable> data) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
- var currentProject = getProject(currentProjectPath);
- if (!SecurityUtils.canReadCode(currentProject))
- throw new UnauthorizedException("No permission to read code of project: " + currentProjectPath);
+
+ sourceProjectPath = StringUtils.trimToNull(sourceProjectPath);
+ targetProjectPath = StringUtils.trimToNull(targetProjectPath);
+
+ if (sourceProjectPath == null)
+ sourceProjectPath = currentProjectPath;
+
+ var sourceProject = getProject(sourceProjectPath);
+ if (!SecurityUtils.canReadCode(sourceProject))
+ throw new UnauthorizedException("No permission to read code of source project: " + sourceProjectPath);
+
+ Project targetProject;
+ if (targetProjectPath != null) {
+ targetProject = getProject(targetProjectPath);
+ } else {
+ targetProject = sourceProject.getForkedFrom();
+ if (targetProject == null)
+ targetProject = sourceProject;
+ }
+ if (!SecurityUtils.canReadCode(targetProject))
+ throw new UnauthorizedException("No permission to read code of target project: " + targetProjectPath);
+
+ var currentProject = getProject(currentProjectPath);
normalizePullRequestData(data);
var targetBranch = (String) data.remove("targetBranch");
+ if (targetBranch == null)
+ targetBranch = targetProject.getDefaultBranch();
+ if (targetBranch == null)
+ throw new NotAcceptableException("No code in target project: " + targetProject.getPath());
+
var sourceBranch = (String) data.remove("sourceBranch");
- var target = new ProjectAndBranch(currentProject, targetBranch);
- var source = new ProjectAndBranch(currentProject, sourceBranch);
+ var target = new ProjectAndBranch(targetProject, targetBranch);
+ var source = new ProjectAndBranch(sourceProject, sourceBranch);
if (target.equals(source))
- throw new InvalidParamsException("Target and source branches are the same");
+ throw new NotAcceptableException("Target and source branches are the same");
PullRequest request = pullRequestManager.findOpen(target, source);
if (request != null)
- throw new InvalidParamsException("Another pull request already opened for this change");
+ throw new NotAcceptableException("Another pull request already opened for this change");
request = pullRequestManager.findEffective(target, source);
if (request != null) {
if (request.isOpen())
- throw new InvalidParamsException("Another pull request already opened for this change");
+ throw new NotAcceptableException("Another pull request already opened for this change");
else
- throw new InvalidParamsException("Change already merged");
+ throw new NotAcceptableException("Change already merged");
}
request = new PullRequest();
@@ -1511,14 +1496,14 @@ public class McpHelperResource {
source.getProject(), source.getObjectId());
if (baseCommitId == null)
- throw new InvalidParamsException("No common base for source and target branches");
+ throw new NotAcceptableException("No common base for source and target branches");
request.setTitle((String) data.remove("title"));
+ request.setDescription((String) data.remove("description"));
request.setTarget(target);
request.setSource(source);
request.setSubmitter(SecurityUtils.getAuthUser());
request.setBaseCommitHash(baseCommitId.name());
- request.setDescription((String) data.remove("description"));
var mergeStrategyName = (String) data.remove("mergeStrategy");
if (mergeStrategyName != null)
@@ -1527,7 +1512,7 @@ public class McpHelperResource {
request.setMergeStrategy(request.getProject().findDefaultPullRequestMergeStrategy());
if (request.getBaseCommitHash().equals(source.getObjectName()))
- throw new InvalidParamsException("Change already merged");
+ throw new NotAcceptableException("Change already merged");
PullRequestUpdate update = new PullRequestUpdate();
@@ -1537,6 +1522,8 @@ public class McpHelperResource {
update.setTargetHeadCommitHash(request.getTarget().getObjectName());
request.getUpdates().add(update);
+ request.generateTitleAndDescriptionIfEmpty();
+
pullRequestManager.checkReviews(request, false);
@SuppressWarnings("unchecked")
@@ -1547,7 +1534,7 @@ public class McpHelperResource {
if (reviewer == null)
throw new NotFoundException("Reviewer not found: " + reviewerName);
if (reviewer.equals(request.getSubmitter()))
- throw new InvalidParamsException("Pull request submitter can not be reviewer");
+ throw new NotAcceptableException("Pull request submitter can not be reviewer");
if (request.getReview(reviewer) == null) {
PullRequestReview review = new PullRequestReview();
@@ -1585,7 +1572,12 @@ public class McpHelperResource {
}
private PullRequest getPullRequest(Project currentProject, String referenceString) {
- var requestReference = PullRequestReference.of(referenceString, currentProject);
+ PullRequestReference requestReference;
+ try {
+ requestReference = PullRequestReference.of(referenceString, currentProject);
+ } catch (InvalidReferenceException e) {
+ throw new NotAcceptableException(e.getMessage());
+ }
var request = pullRequestManager.find(requestReference.getProject(), requestReference.getNumber());
if (request != null) {
if (!SecurityUtils.canReadCode(request.getProject()))
@@ -1599,16 +1591,19 @@ public class McpHelperResource {
@SuppressWarnings("unchecked")
@Path("/edit-pull-request")
@POST
- public String editPullRequest(@QueryParam("currentProject") @NotNull String currentProjectPath,
- @QueryParam("reference") @NotNull String requestReference, @NotNull Map<String, Serializable> data) {
+ public String editPullRequest(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("reference") @NotNull String pullRequestReference, @NotNull Map<String, Serializable> data) {
var user = SecurityUtils.getAuthUser();
if (user == null)
throw new UnauthenticatedException();
+
var currentProject = getProject(currentProjectPath);
- var request = getPullRequest(currentProject, requestReference);
+
+ var request = getPullRequest(currentProject, pullRequestReference);
if (!SecurityUtils.canModifyPullRequest(request))
- throw new UnauthorizedException("No permission to edit pull request: " + requestReference);
+ throw new UnauthorizedException("No permission to edit pull request: " + pullRequestReference);
normalizePullRequestData(data);
@@ -1712,57 +1707,126 @@ public class McpHelperResource {
if (!request.isOpen())
throw new NotAcceptableException("Pull request is closed");
- if (autoMergeEnabled && request.checkMerge() == null)
+ if (autoMergeEnabled && request.checkMergeCondition() == null)
throw new NotAcceptableException("This pull request is not eligible for auto-merge, as it can be merged directly now");
var autoMerge = new AutoMerge();
autoMerge.setEnabled(autoMergeEnabled);
autoMerge.setCommitMessage(StringUtils.trimToNull((String) data.remove("autoMergeCommitMessage")));
autoMerge.setUser(user);
- var errorMessage = request.checkMergeCommitMessage(user, request, autoMerge.getCommitMessage());
+ var errorMessage = request.checkMergeCommitMessage(user, autoMerge.getCommitMessage());
if (errorMessage != null)
throw new NotAcceptableException("Error validating param auto merge commit message: " + errorMessage);
pullRequestChangeManager.changeAutoMerge(request, autoMerge);
}
- return "Edited pull request " + request.getReference().toString(currentProject) + ": " + urlManager.urlFor(request, true);
+ return "Edited pull request " + pullRequestReference;
}
- @Path("/review-pull-request")
+ @Path("/process-pull-request")
@Consumes(MediaType.TEXT_PLAIN)
@POST
- public String reviewPullRequest(@QueryParam("currentProject") String currentProjectPath,
- @QueryParam("reference") @NotNull String pullRequestReference,
- @QueryParam("approved") boolean approved, String comment) {
+ public String processPullRequest(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("reference") @NotNull String pullRequestReference,
+ @QueryParam("operation") String operation,
+ String comment) {
var user = SecurityUtils.getAuthUser();
if (user == null)
throw new UnauthenticatedException();
var currentProject = getProject(currentProjectPath);
+
var pullRequest = getPullRequest(currentProject, pullRequestReference);
- try {
- pullRequestReviewManager.review(pullRequest, approved, comment);
- } catch (ReviewRejectException e) {
- throw new NotAcceptableException(e.getMessage());
- }
+ comment = StringUtils.trimToNull(comment);
+
+ switch (operation) {
+ case "approve":
+ try {
+ pullRequestReviewManager.review(pullRequest, true, comment);
+ } catch (PullRequestReviewRejectedException e) {
+ throw new NotAcceptableException(e.getMessage());
+ }
+ return "Approved pull request " + pullRequestReference;
+ case "requestChanges":
+ try {
+ pullRequestReviewManager.review(pullRequest, false, comment);
+ } catch (PullRequestReviewRejectedException e) {
+ throw new NotAcceptableException(e.getMessage());
+ }
+ return "Requested changes on pull request " + pullRequestReference;
+ case "merge":
+ if (!SecurityUtils.canWriteCode(user.asSubject(), pullRequest.getProject()))
+ throw new UnauthorizedException();
+ String errorMessage = pullRequest.checkMergeCondition();
+ if (errorMessage != null)
+ throw new NotAcceptableException(errorMessage);
+ errorMessage = pullRequest.checkMergeCommitMessage(user, comment);
+ if (errorMessage != null)
+ throw new NotAcceptableException("Error validating merge commit message: " + errorMessage);
+
+ pullRequestManager.merge(user, pullRequest, comment);
+
+ return "Merged pull request " + pullRequestReference;
+ case "discard":
+ if (!SecurityUtils.canModifyPullRequest(pullRequest))
+ throw new UnauthorizedException();
+ if (!pullRequest.isOpen())
+ throw new NotAcceptableException("Pull request already closed");
+ pullRequestManager.discard(pullRequest, comment);
+ return "Discarded pull request " + pullRequestReference;
+ case "reopen":
+ if (!SecurityUtils.canModifyPullRequest(pullRequest))
+ throw new UnauthorizedException();
+ errorMessage = pullRequest.checkReopenCondition();
+ if (errorMessage != null)
+ throw new NotAcceptableException(errorMessage);
+ pullRequestManager.reopen(pullRequest, comment);
+ return "Reopened pull request " + pullRequestReference;
+ case "deleteSourceBranch":
+ if (!SecurityUtils.canModifyPullRequest(pullRequest)
+ || !SecurityUtils.canDeleteBranch(pullRequest.getSourceProject(), pullRequest.getSourceBranch())) {
+ throw new UnauthorizedException();
+ }
+
+ errorMessage = pullRequest.checkDeleteSourceBranchCondition();
+ if (errorMessage != null)
+ throw new NotAcceptableException(errorMessage);
+
+ pullRequestManager.deleteSourceBranch(pullRequest, comment);
- if (approved) {
- return "Approved pull request " + pullRequestReference + ": " + urlManager.urlFor(pullRequest, true);
- } else {
- return "Requested changes on pull request " + pullRequestReference + ": " + urlManager.urlFor(pullRequest, true);
+ return "Deleted source branch of pull request " + pullRequestReference;
+ case "restoreSourceBranch":
+ if (!SecurityUtils.canModifyPullRequest(pullRequest) ||
+ !SecurityUtils.canWriteCode(pullRequest.getSourceProject())) {
+ throw new UnauthorizedException();
+ }
+
+ errorMessage = pullRequest.checkRestoreSourceBranchCondition();
+ if (errorMessage != null)
+ throw new NotAcceptableException(errorMessage);
+
+ pullRequestManager.restoreSourceBranch(pullRequest, comment);
+
+ return "Restored source branch of pull request " + pullRequestReference;
+ default:
+ throw new NotAcceptableException("Invalid operation: " + operation);
}
}
@Path("/add-pull-request-comment")
@Consumes(MediaType.TEXT_PLAIN)
@POST
- public String addPullRequestComment(@QueryParam("currentProject") String currentProjectPath,
- @QueryParam("reference") @NotNull String pullRequestReference, @NotNull String commentContent) {
+ public String addPullRequestComment(
+ @QueryParam("currentProject") @NotNull String currentProjectPath,
+ @QueryParam("reference") @NotNull String pullRequestReference,
+ @NotNull String commentContent) {
if (SecurityUtils.getAuthUser() == null)
throw new UnauthenticatedException();
var currentProject = getProject(currentProjectPath);
+
var pullRequest = getPullRequest(currentProject, pullRequestReference);
var comment = new PullRequestComment();
comment.setRequest(pullRequest);
@@ -1771,7 +1835,7 @@ public class McpHelperResource {
comment.setDate(new Date());
pullRequestCommentManager.create(comment);
- return "Commented on pull request " + pullRequestReference + ": " + urlManager.urlFor(comment, true);
+ return "Commented on pull request " + pullRequestReference;
}
private void normalizePullRequestData(Map<String, Serializable> data) {
@@ -1781,4 +1845,19 @@ public class McpHelperResource {
}
}
-}
\ No newline at end of file
+ private NotAcceptableException newNotAcceptableException(InvalidIssueFieldsException e) {
+ var invaliParams = new ArrayList<String>();
+ for (var entry: e.getInvalidFields().entrySet()) {
+ invaliParams.add(getToolParamName(entry.getKey()) + ": " + entry.getValue());
+ }
+ return new NotAcceptableException("Invalid tool parameters:\n\n" + String.join("\n", invaliParams));
+ }
+
+ private static class ProjectInfo {
+
+ Project project;
+
+ Project currentProject;
+ }
+
+ }
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueChangeManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueChangeManager.java
index cd48f00eac..bfde4a727a 100644
--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueChangeManager.java
+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueChangeManager.java
@@ -59,6 +59,7 @@ import io.onedev.server.event.project.issue.IssueChanged;
import io.onedev.server.event.project.pullrequest.PullRequestChanged;
import io.onedev.server.event.system.SystemStarted;
import io.onedev.server.event.system.SystemStopping;
+import io.onedev.server.exception.InvalidIssueFieldsException;
import io.onedev.server.git.GitUtils;
import io.onedev.server.model.Build;
import io.onedev.server.model.Issue;
@@ -86,7 +87,6 @@ import io.onedev.server.model.support.issue.changedata.IssueStateChangeData;
import io.onedev.server.model.support.issue.changedata.IssueTitleChangeData;
import io.onedev.server.model.support.issue.changedata.IssueTotalEstimatedTimeChangeData;
import io.onedev.server.model.support.issue.changedata.IssueTotalSpentTimeChangeData;
-import io.onedev.server.model.support.issue.field.EmptyFieldsException;
import io.onedev.server.model.support.issue.transitionspec.BranchUpdatedSpec;
import io.onedev.server.model.support.issue.transitionspec.BuildSuccessfulSpec;
import io.onedev.server.model.support.issue.transitionspec.IssueStateTransitedSpec;
@@ -384,7 +384,7 @@ public class DefaultIssueChangeManager extends BaseEntityManager<IssueChange>
public void changeFields(Issue issue, Map<String, Object> fieldValues) {
Map<String, Input> prevFields = issue.getFieldInputs();
issue.setFieldValues(fieldValues);
- issue.checkEmptyFields();
+ issue.validateFields();
if (!prevFields.equals(issue.getFieldInputs())) {
issueFieldManager.saveFields(issue);
@@ -407,7 +407,7 @@ public class DefaultIssueChangeManager extends BaseEntityManager<IssueChange>
issue.removeFields(removeFields);
issue.setFieldValues(fieldValues);
issue.addMissingFields(promptFields);
- issue.checkEmptyFields();
+ issue.validateFields();
issueFieldManager.saveFields(issue);
@@ -441,10 +441,9 @@ public class DefaultIssueChangeManager extends BaseEntityManager<IssueChange>
issue.setFieldValues(fieldValues);
try {
- issue.checkEmptyFields();
- } catch (EmptyFieldsException e) {
- Collection<String> emptyFields = e.getEmptyFields();
- throw new EmptyFieldsException("The following fields must be set for issue " + issue.getReference().toString(issue.getProject()) + ": " + String.join(", ", emptyFields), emptyFields);
+ issue.validateFields();
+ } catch (InvalidIssueFieldsException e) {
+ throw new InvalidIssueFieldsException("Error validating fields for issue " + issue.getReference().toString(issue.getProject()) + ": " + InvalidIssueFieldsException.buildMessage(e.getInvalidFields()), e.getInvalidFields());
}
issueFieldManager.saveFields(issue);
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java
index caeaf47c28..76020128ce 100644
--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java
+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java
@@ -243,7 +243,7 @@ public class DefaultIssueManager extends BaseEntityManager<Issue> implements Iss
issue.setLastActivity(lastActivity);
issue.addMissingFields(settingManager.getIssueSetting().getPromptFieldsUponIssueOpen(issue.getProject()));
- issue.checkEmptyFields();
+ issue.validateFields();
dao.persist(issue);
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestManager.java
index 622eb1faad..22315548d4 100644
--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestManager.java
+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestManager.java
@@ -373,7 +373,7 @@ public class DefaultPullRequestManager extends BaseEntityManager<PullRequest>
ObjectId.fromString(mergePreview.getTargetHeadCommitHash()));
if (project.findDeleteBranchAfterPullRequestMerge()
- && request.checkDeleteSourceBranch() == null
+ && request.checkDeleteSourceBranchCondition() == null
&& SecurityUtils.canDeleteBranch(user.asSubject(), request.getSourceProject(), request.getSourceBranch())) {
gitService.deleteBranch(request.getSourceProject(), request.getSourceBranch());
}
@@ -501,7 +501,7 @@ public class DefaultPullRequestManager extends BaseEntityManager<PullRequest>
public void checkAutoMerge(PullRequest request) {
if (request.isOpen()) {
var autoMerge = request.getAutoMerge();
- if (autoMerge.isEnabled() && request.checkMerge() == null) {
+ if (autoMerge.isEnabled() && request.checkMergeCondition() == null) {
if (autoMerge.getUser() != null)
merge(autoMerge.getUser(), request, autoMerge.getCommitMessage());
else
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestReviewManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestReviewManager.java
index 2e39fc822c..f1b4e3ab41 100644
--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestReviewManager.java
+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultPullRequestReviewManager.java
@@ -15,7 +15,7 @@ import io.onedev.server.entitymanager.PullRequestReviewManager;
import io.onedev.server.event.ListenerRegistry;
import io.onedev.server.event.project.pullrequest.PullRequestReviewRequested;
import io.onedev.server.event.project.pullrequest.PullRequestReviewerRemoved;
-import io.onedev.server.exception.ReviewRejectException;
+import io.onedev.server.exception.PullRequestReviewRejectedException;
import io.onedev.server.model.PullRequest;
import io.onedev.server.model.PullRequestChange;
import io.onedev.server.model.PullRequestReview;
@@ -86,7 +86,7 @@ public class DefaultPullRequestReviewManager extends BaseEntityManager<PullReque
User user = SecurityUtils.getAuthUser();
PullRequestReview review = request.getReview(user);
if (review == null || review.getStatus() == PullRequestReview.Status.EXCLUDED)
- throw new ReviewRejectException("You are not reviewer of this pull request");
+ throw new PullRequestReviewRejectedException("You are not reviewer of this pull request");
if (approved)
review.setStatus(PullRequestReview.Status.APPROVED);
else
diff --git a/server-core/src/main/java/io/onedev/server/entityreference/EntityReference.java b/server-core/src/main/java/io/onedev/server/entityreference/EntityReference.java
index e53da5b68f..d7686bd73d 100644
--- a/server-core/src/main/java/io/onedev/server/entityreference/EntityReference.java
+++ b/server-core/src/main/java/io/onedev/server/entityreference/EntityReference.java
@@ -1,14 +1,16 @@
package io.onedev.server.entityreference;
-import io.onedev.commons.utils.ExplicitException;
-import io.onedev.server.OneDev;
-import io.onedev.server.entitymanager.ProjectManager;
-import io.onedev.server.model.Project;
+import java.io.Serializable;
+
+import javax.annotation.Nullable;
+
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
-import javax.annotation.Nullable;
-import java.io.Serializable;
+import io.onedev.server.OneDev;
+import io.onedev.server.entitymanager.ProjectManager;
+import io.onedev.server.exception.InvalidReferenceException;
+import io.onedev.server.model.Project;
public abstract class EntityReference implements Serializable {
@@ -52,7 +54,7 @@ public abstract class EntityReference implements Serializable {
try {
return Long.valueOf(numberString);
} catch (NumberFormatException e) {
- throw new ExplicitException("Invalid reference number: " + numberString);
+ throw new InvalidReferenceException("Invalid reference number: " + numberString);
}
}
@@ -66,13 +68,13 @@ public abstract class EntityReference implements Serializable {
if (currentProject != null)
return EntityReference.of(type, currentProject, number);
else
- throw new ExplicitException("Reference project not specified: " + referenceString);
+ throw new InvalidReferenceException("Reference project not specified: " + referenceString);
} else {
var project = projectManager.findByPath(projectPath);
if (project != null)
return EntityReference.of(type, project, number);
else
- throw new ExplicitException("Reference project not found: " + projectPath);
+ throw new InvalidReferenceException("Reference project not found: " + projectPath);
}
}
index = referenceString.indexOf('-');
@@ -83,9 +85,9 @@ public abstract class EntityReference implements Serializable {
if (project != null)
return EntityReference.of(type, project, number);
else
- throw new ExplicitException("Reference project not found with key: " + projectKey);
+ throw new InvalidReferenceException("Reference project not found with key: " + projectKey);
}
- throw new ExplicitException("Invalid entity reference: " + referenceString);
+ throw new InvalidReferenceException("Invalid entity reference: " + referenceString);
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/exception/InvalidIssueFieldsException.java b/server-core/src/main/java/io/onedev/server/exception/InvalidIssueFieldsException.java
new file mode 100644
index 0000000000..fd76fc36b4
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/exception/InvalidIssueFieldsException.java
@@ -0,0 +1,33 @@
+package io.onedev.server.exception;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import io.onedev.commons.utils.ExplicitException;
+
+public class InvalidIssueFieldsException extends ExplicitException {
+
+ private final Map<String, String> invalidFields;
+
+ public InvalidIssueFieldsException(Map<String, String> invalidFields) {
+ this(buildMessage(invalidFields), invalidFields);
+ }
+
+ public static String buildMessage(Map<String, String> invalidFields) {
+ var fieldErrors = new ArrayList<String>();
+ for (var entry: invalidFields.entrySet()) {
+ fieldErrors.add(entry.getKey() + " (" + entry.getValue() + ")");
+ }
+ return "Invalid fields: " + String.join(", ", fieldErrors);
+ }
+
+ public InvalidIssueFieldsException(String message, Map<String, String> invalidFields) {
+ super(message);
+ this.invalidFields = invalidFields;
+ }
+
+ public Map<String, String> getInvalidFields() {
+ return invalidFields;
+ }
+
+}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/exception/ReviewRejectException.java b/server-core/src/main/java/io/onedev/server/exception/InvalidReferenceException.java
similarity index 50%
rename from server-core/src/main/java/io/onedev/server/exception/ReviewRejectException.java
rename to server-core/src/main/java/io/onedev/server/exception/InvalidReferenceException.java
index b17ea3fd81..a0c514a26d 100644
--- a/server-core/src/main/java/io/onedev/server/exception/ReviewRejectException.java
+++ b/server-core/src/main/java/io/onedev/server/exception/InvalidReferenceException.java
@@ -2,9 +2,9 @@ package io.onedev.server.exception;
import io.onedev.commons.utils.ExplicitException;
-public class ReviewRejectException extends ExplicitException {
+public class InvalidReferenceException extends ExplicitException {
- public ReviewRejectException(String message) {
+ public InvalidReferenceException(String message) {
super(message);
}
diff --git a/server-core/src/main/java/io/onedev/server/exception/IssueLinkValidationException.java b/server-core/src/main/java/io/onedev/server/exception/IssueLinkValidationException.java
new file mode 100644
index 0000000000..420d93639c
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/exception/IssueLinkValidationException.java
@@ -0,0 +1,11 @@
+package io.onedev.server.exception;
+
+import io.onedev.commons.utils.ExplicitException;
+
+public class IssueLinkValidationException extends ExplicitException {
+
+ public IssueLinkValidationException(String message) {
+ super(message);
+ }
+
+}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/exception/LinkValidationException.java b/server-core/src/main/java/io/onedev/server/exception/LinkValidationException.java
deleted file mode 100644
index 7681f9ba1c..0000000000
--- a/server-core/src/main/java/io/onedev/server/exception/LinkValidationException.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package io.onedev.server.exception;
-
-import io.onedev.commons.utils.ExplicitException;
-
-public class LinkValidationException extends ExplicitException {
-
- public LinkValidationException(String message) {
- super(message);
- }
-
-}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/exception/PullRequestReviewRejectedException.java b/server-core/src/main/java/io/onedev/server/exception/PullRequestReviewRejectedException.java
new file mode 100644
index 0000000000..68d89b4300
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/exception/PullRequestReviewRejectedException.java
@@ -0,0 +1,11 @@
+package io.onedev.server.exception;
+
+import io.onedev.commons.utils.ExplicitException;
+
+public class PullRequestReviewRejectedException extends ExplicitException {
+
+ public PullRequestReviewRejectedException(String message) {
+ super(message);
+ }
+
+}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/git/service/DefaultGitService.java b/server-core/src/main/java/io/onedev/server/git/service/DefaultGitService.java
index c757f03735..915c22bfe0 100644
--- a/server-core/src/main/java/io/onedev/server/git/service/DefaultGitService.java
+++ b/server-core/src/main/java/io/onedev/server/git/service/DefaultGitService.java
@@ -1422,8 +1422,7 @@ public class DefaultGitService implements GitService, Serializable {
ObjectId oldId, ObjectId newId,
Map<String, String> envs) {
Long projectId = project.getId();
- if (protection.getMaxCommitMessageLineLength() != null
- || protection.isEnforceConventionalCommits()) {
+ if (protection.getMaxCommitMessageLineLength() != null || protection.isEnforceConventionalCommits()) {
return runOnProjectServer(projectId, () -> {
Map<ObjectId, String> commitMessages = new LinkedHashMap<>();
Set<ObjectId> mergeCommits = new HashSet<>();
diff --git a/server-core/src/main/java/io/onedev/server/model/Issue.java b/server-core/src/main/java/io/onedev/server/model/Issue.java
index 234117994b..812887e299 100644
--- a/server-core/src/main/java/io/onedev/server/model/Issue.java
+++ b/server-core/src/main/java/io/onedev/server/model/Issue.java
@@ -78,13 +78,14 @@ import io.onedev.server.entitymanager.SettingManager;
import io.onedev.server.entitymanager.UserManager;
import io.onedev.server.entityreference.EntityReference;
import io.onedev.server.entityreference.IssueReference;
+import io.onedev.server.exception.InvalidIssueFieldsException;
import io.onedev.server.model.support.EntityWatch;
import io.onedev.server.model.support.LastActivity;
import io.onedev.server.model.support.ProjectBelonging;
import io.onedev.server.model.support.administration.GlobalIssueSetting;
import io.onedev.server.model.support.issue.field.FieldUtils;
-import io.onedev.server.model.support.issue.field.EmptyFieldsException;
import io.onedev.server.model.support.issue.field.spec.FieldSpec;
+import io.onedev.server.model.support.issue.field.spec.choicefield.ChoiceField;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.search.entity.EntitySort;
import io.onedev.server.search.entity.IssueSortField;
@@ -1028,6 +1029,7 @@ public class Issue extends ProjectBelonging implements AttachmentStorageSupport
}
public void addMissingFields(Collection<String> fieldNames) {
+ Project.push(getProject());
try {
var fieldBean = FieldUtils.getFieldBeanClass().getConstructor().newInstance();
var existingFieldNames = getFieldNames();
@@ -1039,23 +1041,56 @@ public class Issue extends ProjectBelonging implements AttachmentStorageSupport
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
+ } finally {
+ Project.pop();
}
}
- public void checkEmptyFields() {
- var emptyFields = new ArrayList<String>();
- for (var fieldName: getFieldNames()) {
- var field = getIssueSetting().getFieldSpec(fieldName);
- if (field != null
- && !field.isAllowEmpty()
- && isFieldVisible(fieldName)
- && SecurityUtils.canEditIssueField(getProject(), fieldName)
- && getFieldValue(fieldName) == null) {
- emptyFields.add(field.getName());
+ @SuppressWarnings("unchecked")
+ public void validateFields() {
+ Project.push(getProject());
+ try {
+ var invalidFields = new HashMap<String, String>();
+ for (var fieldName: getFieldNames()) {
+ var field = getIssueSetting().getFieldSpec(fieldName);
+ if (field != null) {
+ var value = getFieldValue(fieldName);
+ if (value != null) {
+ if (field instanceof ChoiceField) {
+ var values = new ArrayList<String>();
+ if (value instanceof Collection)
+ values.addAll((Collection<String>) value);
+ else
+ values.add((String) value);
+ var choiceField = (ChoiceField) field;
+ var possibleValues = choiceField.getPossibleValues();
+ if (!possibleValues.containsAll(values)) {
+ if (field.isAllowMultiple())
+ invalidFields.put(fieldName, "value should be one or more of: " + String.join(", ", possibleValues));
+ else
+ invalidFields.put(fieldName, "value should be one of: " + String.join(", ", possibleValues));
+ }
+ }
+ } else if (!field.isAllowEmpty() && isFieldVisible(fieldName)
+ && SecurityUtils.canEditIssueField(getProject(), fieldName)) {
+ if (field instanceof ChoiceField) {
+ var choiceField = (ChoiceField) field;
+ var possibleValues = choiceField.getPossibleValues();
+ if (field.isAllowMultiple())
+ invalidFields.put(fieldName, "value must not be empty, and should take one or more of: " + String.join(", ", possibleValues));
+ else
+ invalidFields.put(fieldName, "value must not be empty, and should take one of: " + String.join(", ", possibleValues));
+ } else {
+ invalidFields.put(fieldName, "value must not be empty");
+ }
+ }
+ }
}
+ if (invalidFields.size() > 0)
+ throw new InvalidIssueFieldsException(invalidFields);
+ } finally {
+ Project.pop();
}
- if (emptyFields.size() > 0)
- throw new EmptyFieldsException(emptyFields);
}
public List<User> getParticipants() {
diff --git a/server-core/src/main/java/io/onedev/server/model/IssueLink.java b/server-core/src/main/java/io/onedev/server/model/IssueLink.java
index 009e492ed3..97893f58d5 100644
--- a/server-core/src/main/java/io/onedev/server/model/IssueLink.java
+++ b/server-core/src/main/java/io/onedev/server/model/IssueLink.java
@@ -8,7 +8,7 @@ import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
-import io.onedev.server.exception.LinkValidationException;
+import io.onedev.server.exception.IssueLinkValidationException;
@Entity
@Table(
@@ -66,35 +66,35 @@ public class IssueLink extends AbstractEntity {
public void validate() {
if (getSource().equals(getTarget()))
- throw new LinkValidationException("Can not link to self");
+ throw new IssueLinkValidationException("Can not link to self");
if (getSpec().getOpposite() != null) {
if (getSource().getTargetLinks().stream()
.anyMatch(it -> it.getSpec().equals(getSpec()) && it.getTarget().equals(getTarget())))
- throw new LinkValidationException("Source issue already linked to target issue via specified link spec");
+ throw new IssueLinkValidationException("Source issue already linked to target issue via specified link spec");
if (!getSpec().isMultiple()
&& getSource().getTargetLinks().stream().anyMatch(it -> it.getSpec().equals(getSpec())))
- throw new LinkValidationException(
+ throw new IssueLinkValidationException(
"Link spec is not multiple and the source issue is already linked to another issue via this link spec");
if (!getSpec().getParsedIssueQuery(getSource().getProject()).matches(getTarget()))
- throw new LinkValidationException("Link spec not allowed to link to the target issue");
+ throw new IssueLinkValidationException("Link spec not allowed to link to the target issue");
if (!getSpec().getOpposite().isMultiple()
&& getTarget().getSourceLinks().stream().anyMatch(it -> it.getSpec().equals(getSpec())))
- throw new LinkValidationException(
+ throw new IssueLinkValidationException(
"Opposite side of link spec is not multiple and the target issue is already linked to another issue via this link spec");
if (!getSpec().getOpposite().getParsedIssueQuery(getSource().getProject())
.matches(getSource()))
- throw new LinkValidationException("Opposite side of link spec not allowed to link to the source issue");
+ throw new IssueLinkValidationException("Opposite side of link spec not allowed to link to the source issue");
} else {
if (getSource().getLinks().stream().anyMatch(it -> it.getSpec().equals(getSpec())
&& it.getLinked(getSource()).equals(getTarget())))
- throw new LinkValidationException("Specified issues already linked via specified link spec");
+ throw new IssueLinkValidationException("Specified issues already linked via specified link spec");
if (!getSpec().isMultiple()
&& getSource().getLinks().stream().anyMatch(it -> it.getSpec().equals(getSpec())))
- throw new LinkValidationException(
+ throw new IssueLinkValidationException(
"Link spec is not multiple and source issue is already linked to another issue via this link spec");
var parsedIssueQuery = getSpec().getParsedIssueQuery(getSource().getProject());
if (!parsedIssueQuery.matches(getSource()) || !parsedIssueQuery.matches(getTarget()))
- throw new LinkValidationException("Link spec not allowed to link specified issues");
+ throw new IssueLinkValidationException("Link spec not allowed to link specified issues");
}
}
}
diff --git a/server-core/src/main/java/io/onedev/server/model/PullRequest.java b/server-core/src/main/java/io/onedev/server/model/PullRequest.java
index 03abeef7d1..931974092b 100644
--- a/server-core/src/main/java/io/onedev/server/model/PullRequest.java
+++ b/server-core/src/main/java/io/onedev/server/model/PullRequest.java
@@ -246,6 +246,9 @@ public class PullRequest extends ProjectBelonging
private static final int MAX_CHECK_ERROR_LEN = 1024;
+ private static final List<String> CONVENTIONAL_COMMIT_TYPES = List.of(
+ "feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore", "revert");
+
public static final List<String> QUERY_FIELDS = Lists.newArrayList(
NAME_NUMBER, NAME_TITLE, NAME_TARGET_PROJECT, NAME_TARGET_BRANCH,
NAME_SOURCE_PROJECT, NAME_SOURCE_BRANCH, NAME_LABEL, NAME_DESCRIPTION,
@@ -1172,7 +1175,7 @@ public class PullRequest extends ProjectBelonging
}
@Nullable
- public String checkMerge() {
+ public String checkMergeCondition() {
if (!isOpen())
return _T("Pull request already closed");
String checkError = getCheckError();
@@ -1211,19 +1214,18 @@ public class PullRequest extends ProjectBelonging
}
@Nullable
- public String checkMergeCommitMessage(User user, PullRequest request, @Nullable String commitMessage) {
- if (request.isMergeCommitMessageRequired()) {
- var branchProtection = request.getProject().getBranchProtection(request.getTargetBranch(), user);
+ public String checkMergeCommitMessage(User user, @Nullable String commitMessage) {
+ if (isMergeCommitMessageRequired()) {
+ var branchProtection = getProject().getBranchProtection(getTargetBranch(), user);
if (commitMessage == null)
- commitMessage = request.getDefaultMergeCommitMessage();
- return branchProtection.checkCommitMessage(commitMessage,
- request.getMergeStrategy() != SQUASH_SOURCE_BRANCH_COMMITS);
+ commitMessage = getDefaultMergeCommitMessage();
+ return branchProtection.checkCommitMessage(commitMessage, getMergeStrategy() != SQUASH_SOURCE_BRANCH_COMMITS);
}
return null;
}
@Nullable
- public String checkReopen() {
+ public String checkReopenCondition() {
if (isOpen())
return _T("Pull request already opened");
if (getTarget().getObjectName(false) == null)
@@ -1250,7 +1252,7 @@ public class PullRequest extends ProjectBelonging
}
@Nullable
- public String checkDeleteSourceBranch() {
+ public String checkDeleteSourceBranchCondition() {
if (!isMerged())
return _T("Pull request not merged");
if (getSourceProject() == null)
@@ -1273,7 +1275,7 @@ public class PullRequest extends ProjectBelonging
}
@Nullable
- public String checkRestoreSourceBranch() {
+ public String checkRestoreSourceBranchCondition() {
if (getSourceProject() == null)
return _T("Source project no longer exists");
if (getSource().getObjectName(false) != null)
@@ -1305,12 +1307,8 @@ public class PullRequest extends ProjectBelonging
error = getProject().checkCommitMessages(getTargetBranch(), getSubmitter(),
getBaseCommit().copy(), getLatestUpdate().getHeadCommit().copy(), new HashMap<>());
}
- if (error == null && autoMerge.isEnabled() && isMergeCommitMessageRequired()) {
- var branchProtection = getProject().getBranchProtection(getTargetBranch(), autoMerge.getUser());
- var commitMessage = autoMerge.getCommitMessage();
- if (commitMessage == null)
- commitMessage = getDefaultMergeCommitMessage();
- var errorMessage = branchProtection.checkCommitMessage(commitMessage, mergeStrategy != SQUASH_SOURCE_BRANCH_COMMITS);
+ if (error == null && autoMerge.isEnabled()) {
+ var errorMessage = checkMergeCommitMessage(autoMerge.getUser(), autoMerge.getCommitMessage());
if (errorMessage != null)
error = new CommitMessageError(null, errorMessage);
}
@@ -1396,4 +1394,43 @@ public class PullRequest extends ProjectBelonging
return lowerTitle.startsWith("wip") || lowerTitle.startsWith("[wip]");
}
+ public void generateTitleAndDescriptionIfEmpty() {
+ if (title == null) {
+ var commits = getLatestUpdate().getCommits();
+ if (commits.size() == 1) {
+ title = commits.get(0).getShortMessage();
+ } else {
+ title = getSource().getBranch().toLowerCase();
+ boolean wip = false;
+ if (title.startsWith("wip-") || title.startsWith("wip_") || title.startsWith("wip/")) {
+ wip = true;
+ title = title.substring(4);
+ }
+ boolean found = false;
+ for (var commitType: CONVENTIONAL_COMMIT_TYPES) {
+ if (title.startsWith(commitType + "-") || title.startsWith(commitType + "_") || title.startsWith(commitType + "/")) {
+ title = commitType + ": " + StringUtils.capitalize(title.substring(commitType.length() + 1).replace('-', ' ').replace('_', ' ').replace('/', ' '));
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ title = StringUtils.capitalize(title.replace('-', ' ').replace('_', ' ').replace('/', ' '));
+ }
+ if (wip)
+ title = "[WIP] " + title;
+ }
+ }
+ if (description == null) {
+ var commits = getLatestUpdate().getCommits();
+ if (commits.size() == 1) {
+ var commit = commits.get(0);
+ var shortMessage = commits.get(0).getShortMessage();
+ description = commit.getFullMessage().substring(shortMessage.length()).trim();
+ if (description.length() == 0)
+ description = null;
+ }
+ }
+ }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/administration/GlobalIssueSetting.java b/server-core/src/main/java/io/onedev/server/model/support/administration/GlobalIssueSetting.java
index 0f68a0301b..ee33df463e 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/administration/GlobalIssueSetting.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/administration/GlobalIssueSetting.java
@@ -1,7 +1,6 @@
package io.onedev.server.model.support.administration;
import java.io.Serializable;
-import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
@@ -40,7 +39,6 @@ import io.onedev.server.model.support.issue.transitionspec.BranchUpdatedSpec;
import io.onedev.server.model.support.issue.transitionspec.IssueStateTransitedSpec;
import io.onedev.server.model.support.issue.transitionspec.ManualSpec;
import io.onedev.server.model.support.issue.transitionspec.TransitionSpec;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.search.entity.issue.IssueQuery;
import io.onedev.server.search.entity.issue.IssueQueryParseOption;
import io.onedev.server.util.usage.Usage;
@@ -754,6 +752,7 @@ public class GlobalIssueSetting implements Serializable {
return getStateSpecs().indexOf(getStateSpec(state));
}
+ @Nullable
public ManualSpec getManualSpec(Issue issue, String state) {
for (var transition: getTransitionSpecs()) {
if (transition instanceof ManualSpec) {
@@ -763,10 +762,7 @@ public class GlobalIssueSetting implements Serializable {
}
}
}
- var message = MessageFormat.format(
- "No applicable manual transition spec found for current user (issue: {0}, from state: {1}, to state: {2})",
- issue.getReference().toString(), issue.getState(), state);
- throw new InvalidParamsException(message);
+ return null;
}
public Collection<String> getPromptFieldsUponIssueOpen(Project project) {
diff --git a/server-core/src/main/java/io/onedev/server/model/support/issue/field/EmptyFieldsException.java b/server-core/src/main/java/io/onedev/server/model/support/issue/field/EmptyFieldsException.java
deleted file mode 100644
index d7730b3572..0000000000
--- a/server-core/src/main/java/io/onedev/server/model/support/issue/field/EmptyFieldsException.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package io.onedev.server.model.support.issue.field;
-
-import java.util.Collection;
-
-import io.onedev.commons.utils.ExplicitException;
-
-public class EmptyFieldsException extends ExplicitException {
-
- private final Collection<String> emptyFields;
-
- public EmptyFieldsException(Collection<String> emptyFields) {
- this("The following fields must be set: " + String.join(", ", emptyFields), emptyFields);
- }
-
- public EmptyFieldsException(String message, Collection<String> emptyFields) {
- super(message);
- this.emptyFields = emptyFields;
- }
-
- public Collection<String> getEmptyFields() {
- return emptyFields;
- }
-
-}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/rest/InvalidParamsException.java b/server-core/src/main/java/io/onedev/server/rest/InvalidParamsException.java
deleted file mode 100644
index 25bf8a2767..0000000000
--- a/server-core/src/main/java/io/onedev/server/rest/InvalidParamsException.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package io.onedev.server.rest;
-
-import javax.ws.rs.BadRequestException;
-
-public class InvalidParamsException extends BadRequestException {
-
- private static final long serialVersionUID = 1L;
-
- public InvalidParamsException(String message) {
- super(message);
- }
-
- public InvalidParamsException(String message, Exception cause) {
- super(message, cause);
- }
-
-}
diff --git a/server-core/src/main/java/io/onedev/server/rest/ParamCheckFilter.java b/server-core/src/main/java/io/onedev/server/rest/ParamCheckFilter.java
index 3f677ebbf8..0e3302756a 100644
--- a/server-core/src/main/java/io/onedev/server/rest/ParamCheckFilter.java
+++ b/server-core/src/main/java/io/onedev/server/rest/ParamCheckFilter.java
@@ -5,8 +5,10 @@ import java.lang.reflect.Parameter;
import java.util.HashSet;
import java.util.Set;
+import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
+import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
@@ -15,8 +17,6 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.Provider;
-import javax.validation.constraints.NotEmpty;
-
import io.onedev.server.rest.resource.TriggerJobResource;
@Provider
@@ -45,12 +45,12 @@ public class ParamCheckFilter implements ContainerRequestFilter {
Set<String> suppliedQueryParams = new HashSet<>(uriInfo.getQueryParameters().keySet());
suppliedQueryParams.removeAll(definedQueryParams);
if (!suppliedQueryParams.isEmpty())
- throw new InvalidParamsException("Unexpected query params: " + suppliedQueryParams);
+ throw new NotAcceptableException("Unexpected query params: " + suppliedQueryParams);
}
requiredQueryParams.removeAll(uriInfo.getQueryParameters().keySet());
if (!requiredQueryParams.isEmpty())
- throw new InvalidParamsException("Missing query params: " + requiredQueryParams);
+ throw new NotAcceptableException("Missing query params: " + requiredQueryParams);
}
public static boolean isRequired(Parameter param) {
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/AgentResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/AgentResource.java
index cddd3cbcd9..ff05fa8ec3 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/AgentResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/AgentResource.java
@@ -7,6 +7,7 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
+import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@@ -23,7 +24,6 @@ import io.onedev.server.entitymanager.AgentAttributeManager;
import io.onedev.server.entitymanager.AgentManager;
import io.onedev.server.entitymanager.AuditManager;
import io.onedev.server.model.Agent;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.search.entity.agent.AgentQuery;
import io.onedev.server.security.SecurityUtils;
@@ -78,7 +78,7 @@ public class AgentResource {
try {
parsedQuery = AgentQuery.parse(query, false);
} catch (Exception e) {
- throw new InvalidParamsException("Error parsing query", e);
+ throw new NotAcceptableException("Error parsing query", e);
}
return agentManager.query(parsedQuery, offset, count);
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/AgentTokenResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/AgentTokenResource.java
index b9f38da3a3..e0a7301d80 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/AgentTokenResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/AgentTokenResource.java
@@ -7,6 +7,7 @@ import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
+import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@@ -24,7 +25,6 @@ import io.onedev.server.entitymanager.AuditManager;
import io.onedev.server.model.Agent;
import io.onedev.server.model.AgentToken;
import io.onedev.server.persistence.dao.EntityCriteria;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.resource.support.RestConstants;
import io.onedev.server.security.SecurityUtils;
@@ -76,7 +76,7 @@ public class AgentTokenResource {
throw new UnauthorizedException();
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
EntityCriteria<AgentToken> criteria = EntityCriteria.of(AgentToken.class);
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/BuildResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/BuildResource.java
index c8fdc354f0..ba2a40503c 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/BuildResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/BuildResource.java
@@ -11,6 +11,7 @@ import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
+import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@@ -31,7 +32,6 @@ import io.onedev.server.model.Build;
import io.onedev.server.model.BuildDependence;
import io.onedev.server.model.BuildLabel;
import io.onedev.server.model.BuildParam;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.resource.support.RestConstants;
import io.onedev.server.search.entity.build.BuildQuery;
@@ -131,13 +131,13 @@ public class BuildResource {
@QueryParam("count") @Api(example="100") int count) {
if (!SecurityUtils.isAdministrator() && count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
BuildQuery parsedQuery;
try {
parsedQuery = BuildQuery.parse(null, query, true, true);
} catch (Exception e) {
- throw new InvalidParamsException("Error parsing query", e);
+ throw new NotAcceptableException("Error parsing query", e);
}
return buildManager.query(null, parsedQuery, false, offset, count);
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/IssueLinkResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/IssueLinkResource.java
index 3b700f28c5..a4ae256c44 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/IssueLinkResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/IssueLinkResource.java
@@ -20,7 +20,7 @@ import javax.ws.rs.core.Response;
import org.apache.shiro.authz.UnauthorizedException;
import io.onedev.server.entitymanager.IssueLinkManager;
-import io.onedev.server.exception.LinkValidationException;
+import io.onedev.server.exception.IssueLinkValidationException;
import io.onedev.server.model.IssueLink;
import io.onedev.server.rest.annotation.Api;
@@ -59,7 +59,7 @@ public class IssueLinkResource {
}
try {
link.validate();
- } catch (LinkValidationException e) {
+ } catch (IssueLinkValidationException e) {
throw new NotAcceptableException(e.getMessage());
}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/IssueResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/IssueResource.java
index 33da7935e2..36892203ca 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/IssueResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/IssueResource.java
@@ -2,6 +2,7 @@ package io.onedev.server.rest.resource;
import java.io.InputStream;
import java.io.Serializable;
+import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
@@ -44,6 +45,7 @@ import io.onedev.server.entitymanager.IssueManager;
import io.onedev.server.entitymanager.IterationManager;
import io.onedev.server.entitymanager.ProjectManager;
import io.onedev.server.entitymanager.SettingManager;
+import io.onedev.server.exception.InvalidIssueFieldsException;
import io.onedev.server.model.Issue;
import io.onedev.server.model.IssueChange;
import io.onedev.server.model.IssueComment;
@@ -56,10 +58,8 @@ import io.onedev.server.model.Iteration;
import io.onedev.server.model.Project;
import io.onedev.server.model.PullRequest;
import io.onedev.server.model.User;
-import io.onedev.server.model.support.issue.field.EmptyFieldsException;
import io.onedev.server.model.support.issue.field.FieldUtils;
import io.onedev.server.model.support.issue.transitionspec.ManualSpec;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.annotation.EntityCreate;
import io.onedev.server.rest.resource.support.RestConstants;
@@ -259,14 +259,14 @@ public class IssueResource {
@QueryParam("count") @Api(example="100") int count) {
if (!SecurityUtils.isAdministrator() && count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
IssueQuery parsedQuery;
try {
IssueQueryParseOption option = new IssueQueryParseOption().withCurrentUserCriteria(true);
parsedQuery = IssueQuery.parse(null, query, option, true);
} catch (Exception e) {
- throw new InvalidParamsException("Error parsing query", e);
+ throw new NotAcceptableException("Error parsing query", e);
}
var typeReference = new TypeReference<Map<String, Object>>() {};
@@ -339,8 +339,8 @@ public class IssueResource {
try {
issueManager.open(issue);
- } catch (EmptyFieldsException e) {
- throw new InvalidParamsException(e.getMessage());
+ } catch (InvalidIssueFieldsException e) {
+ throw new NotAcceptableException(e.getMessage());
}
return issue.getId();
@@ -406,7 +406,7 @@ public class IssueResource {
for (Long iterationId: iterationIds) {
Iteration iteration = iterationManager.load(iterationId);
if (!iteration.getProject().isSelfOrAncestorOf(issue.getProject()))
- throw new InvalidParamsException("Iteration is not defined in project hierarchy of the issue");
+ throw new NotAcceptableException("Iteration is not defined in project hierarchy of the issue");
iterations.add(iteration);
}
@@ -430,8 +430,8 @@ public class IssueResource {
try {
issueChangeManager.changeFields(issue, FieldUtils.getFieldValues(issue.getProject(), fields));
- } catch (EmptyFieldsException e) {
- throw new InvalidParamsException(e.getMessage());
+ } catch (InvalidIssueFieldsException e) {
+ throw new NotAcceptableException(e.getMessage());
}
return Response.ok().build();
}
@@ -449,12 +449,18 @@ public class IssueResource {
public Response transitState(@PathParam("issueId") Long issueId, @NotNull @Valid StateTransitionData data) {
Issue issue = issueManager.load(issueId);
ManualSpec transition = settingManager.getIssueSetting().getManualSpec(issue, data.getState());
+ if (transition == null) {
+ var message = MessageFormat.format(
+ "No applicable manual transition spec found for current user (issue: {0}, from state: {1}, to state: {2})",
+ issue.getReference().toString(), issue.getState(), data.getState());
+ throw new NotAcceptableException(message);
+ }
var fieldValues = FieldUtils.getFieldValues(issue.getProject(), data.getFields());
try {
issueChangeManager.changeState(issue, data.getState(), fieldValues, transition.getPromptFields(), transition.getRemoveFields(), data.getComment());
- } catch (EmptyFieldsException e) {
- throw new InvalidParamsException(e.getMessage());
+ } catch (InvalidIssueFieldsException e) {
+ throw new NotAcceptableException(e.getMessage());
}
return Response.ok().build();
}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/PackResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/PackResource.java
index ed5336887b..89b18ff79b 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/PackResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/PackResource.java
@@ -10,6 +10,7 @@ import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
+import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@@ -26,7 +27,6 @@ import io.onedev.server.model.Pack;
import io.onedev.server.model.PackBlob;
import io.onedev.server.model.PackBlobReference;
import io.onedev.server.model.PackLabel;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.resource.support.RestConstants;
import io.onedev.server.search.entity.pack.PackQuery;
@@ -87,13 +87,13 @@ public class PackResource {
@QueryParam("count") @Api(example="100") int count) {
if (!SecurityUtils.isAdministrator() && count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
PackQuery parsedQuery;
try {
parsedQuery = PackQuery.parse(null, query, true);
} catch (Exception e) {
- throw new InvalidParamsException("Error parsing query", e);
+ throw new NotAcceptableException("Error parsing query", e);
}
return packManager.query(null, parsedQuery, false, offset, count);
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java
index 09b3ffc2ce..bb374aac0f 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/ProjectResource.java
@@ -24,6 +24,7 @@ import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
+import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
@@ -62,7 +63,6 @@ import io.onedev.server.model.support.issue.ProjectIssueSetting;
import io.onedev.server.model.support.pack.ProjectPackSetting;
import io.onedev.server.model.support.pullrequest.ProjectPullRequestSetting;
import io.onedev.server.persistence.dao.EntityCriteria;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.annotation.EntityCreate;
import io.onedev.server.rest.resource.support.RestConstants;
@@ -192,13 +192,13 @@ public class ProjectResource {
@QueryParam("count") @Api(example="100") int count) {
if (!SecurityUtils.isAdministrator() && count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
ProjectQuery parsedQuery;
try {
parsedQuery = ProjectQuery.parse(query);
} catch (Exception e) {
- throw new InvalidParamsException("Error parsing query", e);
+ throw new NotAcceptableException("Error parsing query", e);
}
return projectManager.query(parsedQuery, false, offset, count).stream()
@@ -221,7 +221,7 @@ public class ProjectResource {
throw new UnauthorizedException();
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
EntityCriteria<Iteration> criteria = EntityCriteria.of(Iteration.class);
criteria.add(Restrictions.in(Iteration.PROP_PROJECT, project.getSelfAndAncestors()));
@@ -254,7 +254,7 @@ public class ProjectResource {
throw new UnauthorizedException();
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
int sinceDay = (int) LocalDate.parse(since).toEpochDay();
int untilDay = (int) LocalDate.parse(until).toEpochDay();
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/PullRequestResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/PullRequestResource.java
index 8512528ade..f2fae04136 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/PullRequestResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/PullRequestResource.java
@@ -1,6 +1,5 @@
package io.onedev.server.rest.resource;
-import static io.onedev.server.model.support.pullrequest.MergeStrategy.SQUASH_SOURCE_BRANCH_COMMITS;
import static javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE;
import java.io.InputStream;
@@ -53,7 +52,6 @@ import io.onedev.server.model.User;
import io.onedev.server.model.support.pullrequest.AutoMerge;
import io.onedev.server.model.support.pullrequest.MergePreview;
import io.onedev.server.model.support.pullrequest.MergeStrategy;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.annotation.EntityCreate;
import io.onedev.server.rest.resource.support.RestConstants;
@@ -219,13 +217,13 @@ public class PullRequestResource {
@QueryParam("count") @Api(example="100") int count) {
if (!SecurityUtils.isAdministrator() && count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
PullRequestQuery parsedQuery;
try {
parsedQuery = PullRequestQuery.parse(null, query, true);
} catch (Exception e) {
- throw new InvalidParamsException("Error parsing query", e);
+ throw new NotAcceptableException("Error parsing query", e);
}
return pullRequestManager.query(null, parsedQuery, false, offset, count);
@@ -243,18 +241,18 @@ public class PullRequestResource {
throw new UnauthorizedException();
if (target.equals(source))
- throw new InvalidParamsException("Source and target are the same");
+ throw new NotAcceptableException("Source and target are the same");
PullRequest request = pullRequestManager.findOpen(target, source);
if (request != null)
- throw new InvalidParamsException("Another pull request already opened for this change");
+ throw new NotAcceptableException("Another pull request already opened for this change");
request = pullRequestManager.findEffective(target, source);
if (request != null) {
if (request.isOpen())
- throw new InvalidParamsException("Another pull request already opened for this change");
+ throw new NotAcceptableException("Another pull request already opened for this change");
else
- throw new InvalidParamsException("Change already merged");
+ throw new NotAcceptableException("Change already merged");
}
request = new PullRequest();
@@ -263,7 +261,7 @@ public class PullRequestResource {
source.getProject(), source.getObjectId());
if (baseCommitId == null)
- throw new InvalidParamsException("No common base for target and source");
+ throw new NotAcceptableException("No common base for target and source");
request.setTitle(data.getTitle());
request.setTarget(target);
@@ -278,7 +276,7 @@ public class PullRequestResource {
request.setMergeStrategy(request.getProject().findDefaultPullRequestMergeStrategy());
if (request.getBaseCommitHash().equals(source.getObjectName()))
- throw new InvalidParamsException("Change already merged");
+ throw new NotAcceptableException("Change already merged");
PullRequestUpdate update = new PullRequestUpdate();
update.setDate(new DateTime(request.getSubmitDate()).plusSeconds(1).toDate());
@@ -370,14 +368,14 @@ public class PullRequestResource {
if (!request.isOpen())
throw new NotAcceptableException("Pull request is closed");
- if (data.isEnabled() && request.checkMerge() == null)
+ if (data.isEnabled() && request.checkMergeCondition() == null)
throw new NotAcceptableException("This pull request is not eligible for auto-merge, as it can be merged directly now");
var autoMerge = new AutoMerge();
autoMerge.setEnabled(data.isEnabled());
autoMerge.setCommitMessage(StringUtils.trimToNull(data.getCommitMessage()));
autoMerge.setUser(user);
- var errorMessage = request.checkMergeCommitMessage(user, request, autoMerge.getCommitMessage());
+ var errorMessage = request.checkMergeCommitMessage(user, autoMerge.getCommitMessage());
if (errorMessage != null)
throw new NotAcceptableException("Error validating auto merge commit message: " + errorMessage);
@@ -393,9 +391,9 @@ public class PullRequestResource {
PullRequest request = pullRequestManager.load(requestId);
if (!SecurityUtils.canModifyPullRequest(request))
throw new UnauthorizedException();
- String errorMessage = request.checkReopen();
+ String errorMessage = request.checkReopenCondition();
if (errorMessage != null)
- return Response.status(NOT_ACCEPTABLE).entity(errorMessage).build();
+ throw new NotAcceptableException(errorMessage);
pullRequestManager.reopen(request, note);
return Response.ok().build();
@@ -409,7 +407,7 @@ public class PullRequestResource {
if (!SecurityUtils.canModifyPullRequest(request))
throw new UnauthorizedException();
if (!request.isOpen())
- return Response.status(NOT_ACCEPTABLE).entity("Pull request already closed").build();
+ throw new NotAcceptableException("Pull request already closed");
pullRequestManager.discard(request, note);
return Response.ok().build();
@@ -423,16 +421,13 @@ public class PullRequestResource {
var user = SecurityUtils.getUser();
if (!SecurityUtils.canWriteCode(user.asSubject(), request.getProject()))
throw new UnauthorizedException();
- String errorMessage = request.checkMerge();
+ String errorMessage = request.checkMergeCondition();
if (errorMessage != null)
- return Response.status(NOT_ACCEPTABLE).entity(errorMessage).build();
+ throw new NotAcceptableException(errorMessage);
- if (request.isMergeCommitMessageRequired()) {
- var branchProtection = request.getProject().getBranchProtection(request.getTargetBranch(), user);
- errorMessage = branchProtection.checkCommitMessage(note, request.getMergeStrategy() != SQUASH_SOURCE_BRANCH_COMMITS);
- if (errorMessage != null)
- return Response.status(NOT_ACCEPTABLE).entity("Error validating merge commit message: " + errorMessage).build();
- }
+ errorMessage = request.checkMergeCommitMessage(user, note);
+ if (errorMessage != null)
+ throw new NotAcceptableException("Error validating merge commit message: " + errorMessage);
pullRequestManager.merge(user, request, note);
return Response.ok().build();
@@ -449,9 +444,9 @@ public class PullRequestResource {
throw new UnauthorizedException();
}
- String errorMessage = request.checkDeleteSourceBranch();
+ String errorMessage = request.checkDeleteSourceBranchCondition();
if (errorMessage != null)
- return Response.status(NOT_ACCEPTABLE).entity(errorMessage).build();
+ throw new NotAcceptableException(errorMessage);
pullRequestManager.deleteSourceBranch(request, note);
return Response.ok().build();
@@ -468,9 +463,9 @@ public class PullRequestResource {
throw new UnauthorizedException();
}
- String errorMessage = request.checkRestoreSourceBranch();
+ String errorMessage = request.checkRestoreSourceBranchCondition();
if (errorMessage != null)
- return Response.status(NOT_ACCEPTABLE).entity(errorMessage).build();
+ throw new NotAcceptableException(errorMessage);
pullRequestManager.restoreSourceBranch(request, note);
return Response.ok().build();
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/RepositoryResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/RepositoryResource.java
index dfd221864f..4798f9edd6 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/RepositoryResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/RepositoryResource.java
@@ -1,12 +1,52 @@
package io.onedev.server.rest.resource;
+import static java.util.stream.Collectors.toList;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.validation.constraints.NotEmpty;
+import javax.validation.constraints.NotNull;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.NotAcceptableException;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.shiro.authz.UnauthorizedException;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.PersonIdent;
+
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Splitter;
+
import io.onedev.commons.utils.ExplicitException;
import io.onedev.commons.utils.StringUtils;
import io.onedev.server.entitymanager.ProjectManager;
-import io.onedev.server.git.*;
+import io.onedev.server.git.Blob;
+import io.onedev.server.git.BlobContent;
+import io.onedev.server.git.BlobEdits;
+import io.onedev.server.git.BlobIdent;
+import io.onedev.server.git.BlobIdentFilter;
+import io.onedev.server.git.GitUtils;
import io.onedev.server.git.command.LogCommand;
import io.onedev.server.git.command.LogCommit;
import io.onedev.server.git.command.RevListOptions;
@@ -15,31 +55,12 @@ import io.onedev.server.git.service.GitService;
import io.onedev.server.git.service.RefFacade;
import io.onedev.server.model.Project;
import io.onedev.server.model.User;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.resource.support.FileCreateOrUpdateRequest;
import io.onedev.server.rest.resource.support.FileEditRequest;
import io.onedev.server.search.commit.CommitQuery;
import io.onedev.server.security.SecurityUtils;
import io.onedev.server.util.RevisionAndPath;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.shiro.authz.UnauthorizedException;
-import org.eclipse.jgit.lib.FileMode;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.PersonIdent;
-
-import javax.annotation.Nullable;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.validation.constraints.NotEmpty;
-import javax.validation.constraints.NotNull;
-import javax.ws.rs.*;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.Serializable;
-import java.util.*;
-
-import static java.util.stream.Collectors.toList;
@Path("/repositories")
@Consumes(MediaType.APPLICATION_JSON)
@@ -138,7 +159,7 @@ public class RepositoryResource {
if (!SecurityUtils.canWriteCode(project))
throw new UnauthorizedException();
else if (project.getBranchRef(request.getBranchName()) != null)
- throw new InvalidParamsException("Branch '" + request.getBranchName() + "' already exists");
+ throw new NotAcceptableException("Branch '" + request.getBranchName() + "' already exists");
else if (project.getBranchProtection(request.getBranchName(), user).isPreventCreation())
throw new ExplicitException("Branch creation prohibited by branch protection rule");
@@ -217,7 +238,7 @@ public class RepositoryResource {
}
if (project.getTagRef(request.getTagName()) != null) {
- throw new InvalidParamsException("Tag '" + request.getTagName() + "' already exists");
+ throw new NotAcceptableException("Tag '" + request.getTagName() + "' already exists");
} else {
User user = SecurityUtils.getUser();
gitService.createTag(project, request.getTagName(), request.getRevision(), user.asPerson(),
@@ -257,13 +278,13 @@ public class RepositoryResource {
}
if (count > MAX_COMMITS)
- throw new InvalidParamsException("Count should not be greater than " + MAX_COMMITS);
+ throw new NotAcceptableException("Count should not be greater than " + MAX_COMMITS);
CommitQuery parsedQuery;
try {
parsedQuery = CommitQuery.parse(project, query, true);
} catch (Exception e) {
- throw new InvalidParamsException("Error parsing query", e);
+ throw new NotAcceptableException("Error parsing query", e);
}
RevListOptions options = new RevListOptions();
@@ -311,7 +332,7 @@ public class RepositoryResource {
BlobIdent blobIdent = new BlobIdent(project, revisionAndPathSegments);
if (!blobIdent.isTree()) {
- throw new InvalidParamsException("Specified path is not a directory: " + blobIdent.path);
+ throw new NotAcceptableException("Specified path is not a directory: " + blobIdent.path);
}
ObjectId revId = project.getObjectId(blobIdent.revision, true);
@@ -343,7 +364,7 @@ public class RepositoryResource {
BlobIdent blobIdent = new BlobIdent(project, revisionAndPathSegments);
if (!blobIdent.isFile()) {
- throw new InvalidParamsException("Specified path is not a file: " + blobIdent.path);
+ throw new NotAcceptableException("Specified path is not a file: " + blobIdent.path);
}
Blob blob = project.getBlob(blobIdent, true);
@@ -375,14 +396,14 @@ public class RepositoryResource {
revisionAndPath = RevisionAndPath.parse(project, revisionAndPathSegments);
RefFacade ref = project.getBranchRef(revisionAndPath.getRevision());
if (ref == null)
- throw new InvalidParamsException("Not a branch: " + revisionAndPath.getRevision());
+ throw new NotAcceptableException("Not a branch: " + revisionAndPath.getRevision());
refName = ref.getName();
oldCommitId = ref.getObjectId();
if (revisionAndPath.getPath() == null)
- throw new InvalidParamsException("Branch and file should be specified");
+ throw new NotAcceptableException("Branch and file should be specified");
} else {
if (revisionAndPathSegments.size() < 2)
- throw new InvalidParamsException("Branch and file should be specified");
+ throw new NotAcceptableException("Branch and file should be specified");
revisionAndPath = new RevisionAndPath(
revisionAndPathSegments.get(0),
StringUtils.join(revisionAndPathSegments.subList(1, revisionAndPathSegments.size())));
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/RoleResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/RoleResource.java
index 4e7335c13f..eb720154de 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/RoleResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/RoleResource.java
@@ -8,6 +8,7 @@ import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
+import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@@ -27,7 +28,6 @@ import io.onedev.server.entitymanager.AuditManager;
import io.onedev.server.entitymanager.RoleManager;
import io.onedev.server.model.Role;
import io.onedev.server.persistence.dao.EntityCriteria;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.resource.support.RestConstants;
import io.onedev.server.security.SecurityUtils;
@@ -66,7 +66,7 @@ public class RoleResource {
throw new UnauthorizedException();
if (count > RestConstants.MAX_PAGE_SIZE)
- throw new InvalidParamsException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
+ throw new NotAcceptableException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE);
EntityCriteria<Role> criteria = EntityCriteria.of(Role.class);
if (name != null)
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/SettingResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/SettingResource.java
index fa6934de1f..1bc98f39b4 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/SettingResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/SettingResource.java
@@ -11,6 +11,7 @@ import javax.inject.Singleton;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
+import javax.ws.rs.NotAcceptableException;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@@ -38,7 +39,6 @@ import io.onedev.server.model.support.administration.emailtemplates.EmailTemplat
import io.onedev.server.model.support.administration.jobexecutor.JobExecutor;
import io.onedev.server.model.support.administration.mailservice.MailService;
import io.onedev.server.model.support.administration.sso.SsoConnector;
-import io.onedev.server.rest.InvalidParamsException;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.security.SecurityUtils;
import io.onedev.server.web.page.layout.ContributedAdministrationSetting;
@@ -211,7 +211,7 @@ public class SettingResource {
throw new UnauthorizedException();
String ingressUrl = OneDev.getInstance().getIngressUrl();
if (ingressUrl != null && !ingressUrl.equals(systemSetting.getServerUrl()))
- throw new InvalidParamsException("Server URL can only be \"" + ingressUrl + "\"");
+ throw new NotAcceptableException("Server URL can only be \"" + ingressUrl + "\"");
var oldAuditContent = VersionedXmlDoc.fromBean(settingManager.getSystemSetting()).toXML();
settingManager.saveSystemSetting(systemSetting);
auditManager.audit(null, "changed system setting via RESTful API",
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/TriggerJobResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/TriggerJobResource.java
index f3fd1bc9d1..d9a4db6bf6 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/TriggerJobResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/TriggerJobResource.java
@@ -1,29 +1,37 @@
package io.onedev.server.rest.resource;
-import io.onedev.commons.utils.StringUtils;
-import io.onedev.server.entitymanager.AccessTokenManager;
-import io.onedev.server.entitymanager.ProjectManager;
-import io.onedev.server.git.GitUtils;
-import io.onedev.server.job.JobManager;
-import io.onedev.server.model.Project;
-import io.onedev.server.rest.InvalidParamsException;
-import io.onedev.server.rest.annotation.Api;
-import io.onedev.server.security.SecurityUtils;
-import org.apache.shiro.authz.UnauthorizedException;
-import org.apache.shiro.util.ThreadContext;
-import org.eclipse.jgit.revwalk.RevCommit;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.validation.constraints.NotEmpty;
-import javax.ws.rs.*;
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.NotAcceptableException;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+
+import org.apache.shiro.authz.UnauthorizedException;
+import org.apache.shiro.util.ThreadContext;
+import org.eclipse.jgit.revwalk.RevCommit;
+
+import io.onedev.commons.utils.StringUtils;
+import io.onedev.server.entitymanager.AccessTokenManager;
+import io.onedev.server.entitymanager.ProjectManager;
+import io.onedev.server.git.GitUtils;
+import io.onedev.server.job.JobManager;
+import io.onedev.server.model.Project;
+import io.onedev.server.rest.annotation.Api;
+import io.onedev.server.security.SecurityUtils;
@Api(description="This resource provides an alternative way to run job by passing all parameters via url")
@Path("/trigger-job")
@@ -92,11 +100,11 @@ public class TriggerJobResource {
String accessTokenValue, UriInfo uriInfo) {
Project project = projectManager.findByPath(projectPath);
if (project == null)
- throw new InvalidParamsException("Project not found: " + projectPath);
+ throw new NotAcceptableException("Project not found: " + projectPath);
var accessToken = accessTokenManager.findByValue(accessTokenValue);
if (accessToken == null)
- throw new InvalidParamsException("Invalid access token");
+ throw new NotAcceptableException("Invalid access token");
ThreadContext.bind(accessToken.asSubject());
try {
@@ -104,7 +112,7 @@ public class TriggerJobResource {
throw new UnauthorizedException();
if (StringUtils.isNotBlank(branch) && StringUtils.isNotBlank(tag))
- throw new InvalidParamsException("Either branch or tag should be specified, but not both");
+ throw new NotAcceptableException("Either branch or tag should be specified, but not both");
String refName;
if (branch != null)
@@ -116,7 +124,7 @@ public class TriggerJobResource {
RevCommit commit = project.getRevCommit(refName, false);
if (commit == null)
- throw new InvalidParamsException("Ref not found: " + refName);
+ throw new BadRequestException("Ref not found: " + refName);
Map<String, List<String>> jobParams = new HashMap<>();
for (Map.Entry<String, List<String>> entry: uriInfo.getQueryParameters().entrySet()) {
diff --git a/server-core/src/main/java/io/onedev/server/web/component/issue/create/NewIssueEditor.java b/server-core/src/main/java/io/onedev/server/web/component/issue/create/NewIssueEditor.java
index 9e3d784499..22c03cb1b5 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/issue/create/NewIssueEditor.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/issue/create/NewIssueEditor.java
@@ -7,6 +7,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
+import java.util.Set;
import java.util.UUID;
import javax.annotation.Nullable;
@@ -107,6 +108,8 @@ public abstract class NewIssueEditor extends FormComponentPanel<Issue> implement
Issue issue = newIssue();
Class<?> fieldBeanClass = FieldUtils.getFieldBeanClass();
Serializable fieldBean = issue.getFieldBean(fieldBeanClass, true);
+
+ System.out.println(FieldUtils.getFieldValues(null, fieldBean, Set.of("Assignees")));
var fieldNames = getIssueSetting().getPromptFieldsUponIssueOpen(getProject());
issue.setFieldValues(FieldUtils.getFieldValues(new ComponentContext(this), fieldBean,
diff --git a/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.java b/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.java
index 7e6db87041..15b22ea9f0 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.java
@@ -46,11 +46,11 @@ import io.onedev.server.buildspecmodel.inputspec.InputContext;
import io.onedev.server.buildspecmodel.inputspec.InputSpec;
import io.onedev.server.entitymanager.IssueChangeManager;
import io.onedev.server.entitymanager.SettingManager;
+import io.onedev.server.exception.InvalidIssueFieldsException;
import io.onedev.server.model.Issue;
import io.onedev.server.model.Iteration;
import io.onedev.server.model.Project;
import io.onedev.server.model.support.administration.GlobalIssueSetting;
-import io.onedev.server.model.support.issue.field.EmptyFieldsException;
import io.onedev.server.model.support.issue.field.FieldUtils;
import io.onedev.server.model.support.issue.field.spec.FieldSpec;
import io.onedev.server.search.entity.issue.IssueQuery;
@@ -315,7 +315,7 @@ abstract class BatchEditPanel extends Panel implements InputContext {
try {
OneDev.getInstance(IssueChangeManager.class).batchUpdate(
getIssueIterator(), state, confidential, iterations, fieldValues, comment, sendNotifications);
- } catch (EmptyFieldsException e) {
+ } catch (InvalidIssueFieldsException e) {
form.error(e.getMessage());
target.add(form);
return;
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/create/NewPullRequestPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/create/NewPullRequestPage.java
index d553de137b..fde67e435d 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/create/NewPullRequestPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/create/NewPullRequestPage.java
@@ -18,7 +18,6 @@ import java.util.stream.Collectors;
import javax.annotation.Nullable;
-import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.Component;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.ajax.AjaxRequestTarget;
@@ -123,9 +122,6 @@ public class NewPullRequestPage extends ProjectPage implements RevisionAnnotatio
private static final String TABS_ID = "tabs";
private static final String TAB_PANEL_ID = "tabPanel";
-
- private static final List<String> CONVENTIONAL_COMMIT_TYPES = List.of(
- "feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore", "revert");
private ProjectAndBranch target;
@@ -266,38 +262,7 @@ public class NewPullRequestPage extends ProjectPage implements RevisionAnnotatio
update.setHeadCommitHash(source.getObjectName());
update.setTargetHeadCommitHash(request.getTarget().getObjectName());
- String title;
- String description;
- var commits = update.getCommits();
- if (commits.size() == 1) {
- title = commits.get(0).getShortMessage();
- description = commits.get(0).getFullMessage().substring(title.length()).trim();
- if (description.length() == 0)
- description = null;
- } else {
- title = source.getBranch().toLowerCase();
- boolean wip = false;
- if (title.startsWith("wip-") || title.startsWith("wip_") || title.startsWith("wip/")) {
- wip = true;
- title = title.substring(4);
- }
- boolean found = false;
- for (var commitType: CONVENTIONAL_COMMIT_TYPES) {
- if (title.startsWith(commitType + "-") || title.startsWith(commitType + "_") || title.startsWith(commitType + "/")) {
- title = commitType + ": " + StringUtils.capitalize(title.substring(commitType.length() + 1).replace('-', ' ').replace('_', ' ').replace('/', ' '));
- found = true;
- break;
- }
- }
- if (!found) {
- title = StringUtils.capitalize(title.replace('-', ' ').replace('_', ' ').replace('/', ' '));
- }
- if (wip)
- title = "[WIP] " + title;
- description = null;
- }
- request.setTitle(title);
- request.setDescription(description);
+ request.generateTitleAndDescriptionIfEmpty();
getPullRequestManager().checkReviews(request, false);
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/PullRequestDetailPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/PullRequestDetailPage.java
index cf5f9059cf..c64222eb96 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/PullRequestDetailPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/pullrequests/detail/PullRequestDetailPage.java
@@ -1441,7 +1441,7 @@ public abstract class PullRequestDetailPage extends ProjectPage implements PullR
protected void onConfigure() {
super.onConfigure();
var request = getPullRequest();
- setVisible(request.isOpen() && request.checkMerge() != null);
+ setVisible(request.isOpen() && request.checkMergeCondition() != null);
}
};
@@ -2040,7 +2040,7 @@ public abstract class PullRequestDetailPage extends ProjectPage implements PullR
private boolean canOperate() {
PullRequest request = getPullRequest();
- return SecurityUtils.canWriteCode(request.getProject()) && request.checkMerge() == null;
+ return SecurityUtils.canWriteCode(request.getProject()) && request.checkMergeCondition() == null;
}
@Override
@@ -2118,7 +2118,7 @@ public abstract class PullRequestDetailPage extends ProjectPage implements PullR
private boolean canOperate() {
PullRequest request = getPullRequest();
- return SecurityUtils.canModifyPullRequest(request) && request.checkReopen() == null;
+ return SecurityUtils.canModifyPullRequest(request) && request.checkReopenCondition() == null;
}
@Override
@@ -2155,7 +2155,7 @@ public abstract class PullRequestDetailPage extends ProjectPage implements PullR
private boolean canOperate() {
PullRequest request = getPullRequest();
- return request.checkDeleteSourceBranch() == null
+ return request.checkDeleteSourceBranchCondition() == null
&& SecurityUtils.canModifyPullRequest(request)
&& SecurityUtils.canDeleteBranch(request.getSourceProject(), request.getSourceBranch());
}
@@ -2195,7 +2195,7 @@ public abstract class PullRequestDetailPage extends ProjectPage implements PullR
private boolean canOperate() {
PullRequest request = getPullRequest();
- return request.checkRestoreSourceBranch() == null
+ return request.checkRestoreSourceBranchCondition() == null
&& SecurityUtils.canModifyPullRequest(request)
&& SecurityUtils.canWriteCode(request.getSourceProject());
}
diff --git a/server-ee b/server-ee
index 360a6880e5..428b813bf4 160000
--- a/server-ee
+++ b/server-ee
@@ -1 +1 @@
-Subproject commit 360a6880e5d4c0246cf5c254c1e54f816a30ce65
+Subproject commit 428b813bf4c7e968206b247785aa9bf14bfae5f1